cxxmcp 1.3.0
C++ MCP SDK
Loading...
Searching...
No Matches
client.hpp
Go to the documentation of this file.
1// Copyright (c) 2025 [caomengxuan666]
2
3#pragma once
4
13
14#include <atomic>
15#include <chrono>
16#include <condition_variable>
17#include <cstdint>
18#include <functional>
19#include <memory>
20#include <mutex>
21#include <optional>
22#include <string>
23#include <string_view>
24#include <unordered_map>
25#include <utility>
26#include <vector>
27
40#include "cxxmcp/request.hpp"
41
42namespace mcp::client {
43
44struct HttpAuthChallenge;
45using HttpAuthRefreshHandler =
46 std::function<std::optional<std::string>(const HttpAuthChallenge&)>;
47
52 std::string method;
54 std::string url;
57 std::optional<std::string> access_token;
59 std::optional<std::string> nonce;
60};
61
65 std::string proof;
67 std::string authorization_scheme = "DPoP";
68};
69
73 std::function<core::Result<std::optional<HttpDpopProof>>(
75
79 std::string endpoint;
80
82 std::chrono::milliseconds timeout{30000};
83};
84
87struct ClientHandler;
88struct ClientHandlerInterface;
89
95 std::function<core::Result<protocol::JsonRpcResponse>(
97
102using TransportNotificationHandler = std::function<core::Result<core::Unit>(
104
112 public:
113 virtual ~Transport() = default;
114
119 const protocol::JsonRpcRequest& request) = 0;
120
125 const protocol::JsonRpcNotification& notification);
126
137 TransportRequestHandler request_handler,
138 TransportNotificationHandler notification_handler = {}) {
139 (void)request_handler;
140 (void)notification_handler;
141 return core::Unit{};
142 }
143
148 virtual void stop() noexcept {}
149};
150
160class Client {
161 public:
162#if defined(CXXMCP_ENABLE_HTTP)
165 struct StreamableHttpEndpoint {
169 std::string uri;
170
172 std::string host;
174 std::uint16_t port = 80;
176 std::string path = "/mcp";
178 std::unordered_map<std::string, std::string> headers;
179
183 std::optional<std::string> auth_header;
184
187 HttpAuthRefreshHandler auth_refresh_handler;
188
192 HttpDpopRequestSigner dpop_request_signer;
193
197 bool stateless = false;
198
200 std::chrono::milliseconds timeout{30000};
201 };
202#endif
203
207 std::string command;
209 std::vector<std::string> args;
211 std::string cwd;
213 std::unordered_map<std::string, std::string> env;
214 };
215
216 using Root = protocol::Root;
217
222 std::function<void(std::string_view, std::string_view)>;
223
225 using InitializedHandler = std::function<void()>;
226
231 std::function<void(const protocol::RequestId&, std::string_view)>;
232
235 using ListChangedHandler = std::function<void()>;
236
239 using ResourceUpdatedHandler = std::function<void(const std::string&)>;
240
243 std::function<void(const protocol::ProgressNotificationParams&)>;
244
247 using ElicitationCompleteHandler = std::function<void(std::string_view)>;
248
250 using TaskStatusHandler = std::function<void(const protocol::Task&)>;
251
255 std::function<core::Result<protocol::RootsListResult>()>;
256 using RootsListRequestCancellationHandler =
257 std::function<core::Result<protocol::RootsListResult>(CancellationToken)>;
258
263 std::function<core::Result<protocol::CreateMessageResult>(
265 using SamplingRequestCancellationHandler =
266 std::function<core::Result<protocol::CreateMessageResult>(
268
273 std::function<core::Result<protocol::CreateElicitationResult>(
275 using ElicitationRequestCancellationHandler =
276 std::function<core::Result<protocol::CreateElicitationResult>(
278
282 using CustomRequestHandler = std::function<core::Result<protocol::Json>(
284 using CustomRequestCancellationHandler =
285 std::function<core::Result<protocol::Json>(
287 using ListRootsRequestHandler = RootsListRequestHandler;
288 using CreateMessageRequestHandler = SamplingRequestHandler;
289 using CreateElicitationRequestHandler = ElicitationRequestHandler;
290
293 std::function<void(const protocol::JsonRpcNotification&)>;
294
295#if defined(CXXMCP_ENABLE_HTTP)
299 static Client connect_streamable_http(StreamableHttpEndpoint endpoint);
300
304 static Client connect_streamable_http(std::string uri);
305
309 static Client connect_legacy_sse(StreamableHttpEndpoint endpoint);
310
314 static Client connect_legacy_sse(std::string uri);
315#endif
316
322
325 explicit Client(std::unique_ptr<Transport> transport);
326 Client(const Client&) = delete;
327 Client& operator=(const Client&) = delete;
328 Client(Client&& other) noexcept;
329 Client& operator=(Client&& other) noexcept;
330
335 core::Result<protocol::Json> initialize(std::string client_name = "cxxmcp",
336 std::string client_version = "0");
337
344 std::string client_version,
345 RequestOptions options);
346
348 std::optional<protocol::ServerCapabilities> server_capabilities() const;
349
353
358 std::string reason = {});
359
366 protocol::ProgressToken progress_token, double progress,
367 std::optional<double> total = std::nullopt, std::string message = {});
368
371
374
377
380 const protocol::PaginatedRequestParams& params = {});
381
384
387 const protocol::PromptsGetParams& params);
388
391 std::string_view name,
392 const protocol::Json& arguments = protocol::Json::object());
393
396
399 const protocol::PaginatedRequestParams& params = {});
400
403
406 const protocol::ResourcesReadParams& params);
407
410 std::string_view uri);
411
415
419 const protocol::PaginatedRequestParams& params = {});
420
425
428
431 const protocol::PaginatedRequestParams& params = {});
432
436
439
442 const protocol::ToolCall& call);
443
446 std::string_view name,
447 const protocol::Json& arguments = protocol::Json::object());
448
452
455
458 std::string_view prompt_name, std::string_view argument_name,
459 std::string current_value,
460 protocol::Json context = protocol::Json::object());
461
465 std::string_view uri_template, std::string_view argument_name,
466 std::string current_value,
467 protocol::Json context = protocol::Json::object());
468
471 std::string_view prompt_name, std::string_view argument_name,
472 std::string current_value,
473 protocol::Json context = protocol::Json::object());
474
477 std::string_view uri_template, std::string_view argument_name,
478 std::string current_value,
479 protocol::Json context = protocol::Json::object());
480
485
488
492
495 const protocol::Json& request);
496
499
503
506
509
511 core::Result<protocol::Task> get_task(std::string_view task_id);
512
516
518 core::Result<protocol::Task> cancel_task(std::string_view task_id);
519
523
525 core::Result<protocol::Json> task_result(std::string_view task_id);
526
529 const protocol::LoggingSetLevelParams& params);
530
532 core::Result<core::Unit> set_level(std::string_view level);
533
535 core::Result<core::Unit> subscribe(std::string_view uri);
536
539
542
545 std::string method, protocol::Json params = protocol::Json::object(),
546 RequestOptions options = {});
547
551 template <class T, class Parser>
553 Parser parser, RequestOptions options = {}) {
555 request.method = std::move(method);
556 request.params = std::move(params);
557 request.id = next_request_id();
558 if (options.meta.has_value()) {
559 request.meta = std::move(options.meta);
560 }
561 request.transport_headers = std::move(options.headers);
562 request.protocol_version_override = std::move(options.protocol_version);
563
564 const auto request_id = request.id;
565 ++in_flight_requests_;
566 auto in_flight_mutex = &in_flight_mutex_;
567 auto in_flight_cv = in_flight_cv_;
568 auto in_flight_count = &in_flight_requests_;
570 request_id, options.timeout, options.cancellation_token,
571 [this, request_id](std::string reason) mutable {
572 return notify_cancelled(std::move(request_id), std::move(reason));
573 },
574 [this, request = std::move(request), parser = std::move(parser),
575 in_flight_mutex, in_flight_cv,
576 in_flight_count]() mutable -> core::Result<T> {
577 auto payload = raw_request(request);
578 core::Result<T> result;
579 if (!payload) {
580 result = mcp::core::unexpected(payload.error());
581 } else {
582 result = parser(*payload);
583 }
584 {
585 std::lock_guard lock(*in_flight_mutex);
586 --(*in_flight_count);
587 in_flight_cv->notify_one();
588 }
589 return result;
590 });
591 }
592
595 RequestOptions options = {});
596
599 RequestOptions options = {});
600
603 RequestOptions options = {});
604
609
612 const protocol::ToolCall& call, RequestOptions options = {});
613
616 std::string_view name,
617 const protocol::Json& arguments = protocol::Json::object(),
618 RequestOptions options = {});
619
622 const protocol::ToolCall& call, RequestOptions options = {});
623
626 const protocol::PromptsGetParams& params, RequestOptions options = {});
627
630 std::string_view name,
631 const protocol::Json& arguments = protocol::Json::object(),
632 RequestOptions options = {});
633
636 const protocol::ResourcesReadParams& params, RequestOptions options = {});
637
640 std::string_view uri, RequestOptions options = {});
641
644 const protocol::CompleteParams& request, RequestOptions options = {});
645
648 RequestOptions options = {});
649
652 const protocol::CreateMessageParams& request,
653 RequestOptions options = {});
654
657 const protocol::Json& request, RequestOptions options = {});
658
662 RequestOptions options = {});
663
666 const protocol::Json& request, RequestOptions options = {});
667
670 RequestOptions options = {});
671
674 const protocol::TaskGetParams& request, RequestOptions options = {});
675
678 RequestOptions options = {});
679
682 const protocol::TaskCancelParams& request, RequestOptions options = {});
683
686 RequestOptions options = {});
687
690 const protocol::TaskResultParams& request, RequestOptions options = {});
691
694 RequestOptions options = {});
695
698 const protocol::JsonRpcNotification& notification);
699
701 std::vector<protocol::Root> list_roots() const;
702
708 Client& set_roots(std::vector<protocol::Root> roots);
709
714
717
720
723
726
729
732
735
738
741
744
747
749 Client& on_list_roots_request(ListRootsRequestHandler handler);
750 Client& on_list_roots_request(RootsListRequestCancellationHandler handler);
751
753 Client& on_create_message_request(CreateMessageRequestHandler handler);
754 Client& on_create_message_request(SamplingRequestCancellationHandler handler);
755
758 CreateElicitationRequestHandler handler);
759 Client& on_create_elicitation_request(
760 ElicitationRequestCancellationHandler handler);
761
765 Client& on_custom_request(CustomRequestCancellationHandler handler);
766
769 Client& on_roots_list_request(RootsListRequestCancellationHandler handler);
770
773 Client& on_sampling_request(SamplingRequestCancellationHandler handler);
774
777 Client& on_elicitation_request(ElicitationRequestCancellationHandler handler);
778
781
784
789 Client& set_handler(const ClientHandler& handler);
790
794 Client& set_handler(const ClientHandlerInterface& handler);
795
799
803 const protocol::JsonRpcNotification& notification);
804
808 const protocol::JsonRpcRequest& request);
809
812 const protocol::JsonRpcRequest& request);
813
816 const protocol::JsonRpcNotification& notification);
817
819 void stop() noexcept;
820
824
825 private:
826 template <typename Handler>
827 Handler copy_handler(Handler Client::* slot) const {
828 std::lock_guard<std::mutex> lock(*handlers_mutex_);
829 return this->*slot;
830 }
831
832 template <typename Handler>
833 void store_handler(Handler Client::* slot, Handler handler) {
834 std::lock_guard<std::mutex> lock(*handlers_mutex_);
835 this->*slot = std::move(handler);
836 }
837
838 core::Result<protocol::Json> send_request(std::string method,
839 protocol::Json params);
842 core::Result<core::Unit> ensure_transport_started();
843 core::Result<core::Unit> record_server_capabilities(
844 const protocol::Json& initialize_payload);
845 bool server_capabilities_known() const noexcept;
846 bool supports_server_completion() const noexcept;
847 bool supports_server_logging() const noexcept;
848 bool supports_server_resource_subscribe() const noexcept;
849 bool supports_server_task_list() const noexcept;
850 bool supports_server_task_cancel() const noexcept;
851 bool supports_server_tasks() const noexcept;
852 bool supports_server_task_tool_call() const noexcept;
853 std::optional<protocol::ClientCapabilities> capabilities_snapshot() const;
854 std::optional<protocol::ServerCapabilities> server_capabilities_snapshot()
855 const;
856 CancellationToken begin_request_cancellation(
857 const protocol::RequestId& request_id);
858 void end_request_cancellation(const protocol::RequestId& request_id) noexcept;
859 void cancel_request(const protocol::RequestId& request_id) noexcept;
860 std::int64_t next_request_id() noexcept {
861 return next_request_id_.fetch_add(1, std::memory_order_relaxed);
862 }
863
864 std::unique_ptr<Transport> transport_;
865 std::atomic<std::int64_t> next_request_id_{1};
866 bool transport_started_ = false;
867 std::vector<protocol::Root> roots_;
868 std::optional<protocol::Json> last_initialize_params_;
869 std::optional<protocol::ClientCapabilities> capabilities_;
870 std::optional<protocol::ServerCapabilities> server_capabilities_;
871 InitializedHandler initialized_handler_;
872 CancelledHandler cancelled_handler_;
873 LoggingMessageHandler logging_message_handler_;
874 ListChangedHandler tool_list_changed_handler_;
875 ListChangedHandler prompt_list_changed_handler_;
876 ListChangedHandler resource_list_changed_handler_;
877 ResourceUpdatedHandler resource_updated_handler_;
878 ProgressHandler progress_handler_;
879 ElicitationCompleteHandler elicitation_complete_handler_;
880 TaskStatusHandler task_status_handler_;
881 ListChangedHandler roots_list_changed_handler_;
882 RootsListRequestHandler roots_list_request_handler_;
883 RootsListRequestCancellationHandler roots_list_request_cancellation_handler_;
884 SamplingRequestHandler sampling_request_handler_;
885 SamplingRequestCancellationHandler sampling_request_cancellation_handler_;
886 ElicitationRequestHandler elicitation_request_handler_;
887 ElicitationRequestCancellationHandler
888 elicitation_request_cancellation_handler_;
889 CustomRequestHandler custom_request_handler_;
890 CustomRequestCancellationHandler custom_request_cancellation_handler_;
891 RawNotificationHandler raw_notification_handler_;
892 mutable std::shared_ptr<std::mutex> state_mutex_ =
893 std::make_shared<std::mutex>();
894 mutable std::shared_ptr<std::mutex> handlers_mutex_ =
895 std::make_shared<std::mutex>();
896 std::shared_ptr<std::mutex> active_request_cancellations_mutex_ =
897 std::make_shared<std::mutex>();
898 std::shared_ptr<std::unordered_map<std::string, CancellationSource>>
899 active_request_cancellations_ = std::make_shared<
900 std::unordered_map<std::string, CancellationSource>>();
901
902 std::atomic<int> in_flight_requests_{0};
903 mutable std::mutex in_flight_mutex_;
904 std::shared_ptr<std::condition_variable> in_flight_cv_ =
905 std::make_shared<std::condition_variable>();
906};
907
908} // namespace mcp::client
909
MCP client and server capability declarations.
Copyable token observed by cancellation-aware SDK operations.
Definition cancellation.hpp:104
Definition request.hpp:123
High-level MCP client compatibility API.
Definition client.hpp:160
Client & on_task_status(TaskStatusHandler handler)
Registers a callback for task status notifications.
core::Result< std::vector< protocol::ToolDefinition > > list_tools()
Lists one page of tool definitions advertised by the server.
core::Result< core::Unit > unsubscribe(std::string_view uri)
Unsubscribes from resource update notifications for a URI.
Client & on_logging_message(LoggingMessageHandler handler)
Registers a callback for logging message notifications.
core::Result< protocol::Json > raw_request(const protocol::JsonRpcRequest &request)
Sends a raw JSON-RPC request and returns the raw result JSON.
Client & on_list_roots_request(ListRootsRequestHandler handler)
Registers a handler for server list-roots requests.
RequestHandle< protocol::ToolResult > call_tool_async(std::string_view name, const protocol::Json &arguments=protocol::Json::object(), RequestOptions options={})
Asynchronously calls a tool by name.
core::Result< std::vector< protocol::Resource > > list_all_resources()
Lists all resources, following pagination cursors until exhausted.
core::Result< protocol::PromptsListResult > list_prompts_page(const protocol::PaginatedRequestParams &params={})
Lists one typed page of prompts, preserving pagination metadata.
RequestHandle< std::vector< protocol::Prompt > > list_prompts_async(RequestOptions options={})
Asynchronously lists prompts and parses the typed response.
core::Result< protocol::Task > get_task(std::string_view task_id)
Gets a task by task identifier.
core::Result< protocol::PromptsGetResult > get_prompt(const protocol::PromptsGetParams &params)
Gets a prompt by protocol parameter object.
std::function< void(std::string_view, std::string_view)> LoggingMessageHandler
Receives logging messages from the server.
Definition client.hpp:222
core::Result< std::vector< protocol::ToolDefinition > > list_all_tools()
Lists all tool definitions, following pagination cursors until exhausted.
RequestHandle< T > request_async(std::string method, protocol::Json params, Parser parser, RequestOptions options={})
Sends a cancellable typed request and parses its result payload.
Definition client.hpp:552
std::function< void(const protocol::ProgressNotificationParams &)> ProgressHandler
Receives progress notifications associated with a progress token.
Definition client.hpp:243
core::Result< core::Unit > subscribe(std::string_view uri)
Subscribes to resource update notifications for a URI.
Client & on_initialized(InitializedHandler handler)
Registers a callback for initialized notifications.
std::optional< protocol::ServerCapabilities > server_capabilities() const
Returns server capabilities learned from initialize(), if known.
core::Result< protocol::Json > initialize(std::string client_name="cxxmcp", std::string client_version="0")
Sends the MCP initialize request.
core::Result< core::Unit > notify_roots_list_changed()
Notifies the server that the client's roots list changed.
core::Result< core::Unit > notify(const protocol::JsonRpcNotification &notification)
Sends a raw JSON-RPC notification.
core::Result< protocol::CreateElicitationResult > create_elicitation(const protocol::CreateElicitationRequestParam &request)
Sends an elicitation request using typed protocol parameters.
core::Result< core::Unit > notify_progress(protocol::ProgressToken progress_token, double progress, std::optional< double > total=std::nullopt, std::string message={})
Sends a progress notification.
std::function< void(const std::string &)> ResourceUpdatedHandler
Receives resource update notifications.
Definition client.hpp:239
core::Result< protocol::Json > create_elicitation(const protocol::Json &request)
Sends an elicitation request using raw JSON parameters.
core::Result< core::Unit > ping()
Sends an MCP ping request.
Client & on_roots_list_request(RootsListRequestHandler handler)
Compatibility alias for on_list_roots_request().
std::function< core::Result< protocol::RootsListResult >()> RootsListRequestHandler
Handles a server request for the client's current roots.
Definition client.hpp:255
core::Result< std::vector< protocol::Prompt > > list_all_prompts()
Lists all prompts, following pagination cursors until exhausted.
Client & on_cancelled(CancelledHandler handler)
Registers a callback for cancellation notifications.
Client & on_prompt_list_changed(ListChangedHandler handler)
Registers a callback for prompt list change notifications.
Client & on_elicitation_complete(ElicitationCompleteHandler handler)
Registers a callback for elicitation completion notifications.
Client & on_create_elicitation_request(CreateElicitationRequestHandler handler)
Registers a handler for server elicitation requests.
RequestHandle< protocol::Json > task_result_async(const protocol::TaskResultParams &request, RequestOptions options={})
Asynchronously gets a task result using typed protocol parameters.
Client & set_roots(std::vector< protocol::Root > roots)
Replaces the roots advertised by this client.
Client & on_elicitation_request(ElicitationRequestHandler handler)
Compatibility alias for on_create_elicitation_request().
RequestHandle< protocol::Task > cancel_task_async(std::string_view task_id, RequestOptions options={})
Asynchronously cancels a task by identifier.
core::Result< protocol::Json > complete(const protocol::Json &request)
Requests completion using raw JSON parameters.
Client & on_sampling_request(SamplingRequestHandler handler)
Compatibility alias for on_create_message_request().
RequestHandle< protocol::ToolResult > call_tool_async(const protocol::ToolCall &call, RequestOptions options={})
Asynchronously calls a tool and parses the typed response.
core::Result< std::vector< protocol::Task > > list_all_tasks()
Lists all tasks, following pagination cursors until exhausted.
core::Result< std::vector< std::string > > complete_resource_simple(std::string_view uri_template, std::string_view argument_name, std::string current_value, protocol::Json context=protocol::Json::object())
Returns resource completion values only.
Client(std::unique_ptr< Transport > transport)
Constructs a client from a custom transport.
core::Result< core::Unit > start()
Starts the underlying transport receive side if the transport needs explicit startup.
RequestHandle< protocol::Task > cancel_task_async(const protocol::TaskCancelParams &request, RequestOptions options={})
Asynchronously cancels a task using typed protocol parameters.
core::Result< protocol::CompleteResult > complete(const protocol::CompleteParams &request)
Requests completion using typed protocol parameters.
RequestHandle< std::vector< protocol::Resource > > list_resources_async(RequestOptions options={})
Asynchronously lists resources and parses the typed response.
void stop() noexcept
Stops the underlying transport and clears receive-side state.
core::Result< protocol::Json > request(const protocol::JsonRpcRequest &request)
Sends a raw JSON-RPC request and returns its result JSON.
core::Result< core::Unit > notify_initialized()
Sends the initialized notification after a successful initialize exchange.
core::Result< protocol::Task > get_task(const protocol::TaskGetParams &request)
Gets a task using typed protocol parameters.
RequestHandle< std::vector< protocol::ToolDefinition > > list_tools_async(RequestOptions options={})
Asynchronously lists tools and parses the typed response.
RequestHandle< protocol::Json > create_message_async(const protocol::Json &request, RequestOptions options={})
Asynchronously sends a raw sampling request.
Client & on_progress(ProgressHandler handler)
Registers a callback for progress notifications.
core::Result< protocol::ToolResult > call_raw(std::string_view name, const protocol::Json &arguments=protocol::Json::object())
Calls a tool by name with optional JSON arguments.
static Client connect_stdio(StdioEndpoint endpoint)
Creates a client connected to a child process over stdio.
core::Result< protocol::PromptsGetResult > get_prompt(std::string_view name, const protocol::Json &arguments=protocol::Json::object())
Gets a prompt by name and optional JSON arguments.
core::Result< protocol::ResourcesReadResult > read_resource(std::string_view uri)
Reads a resource by URI.
core::Result< std::vector< protocol::ResourceTemplate > > list_resource_templates()
Lists one page of resource templates advertised by the server.
core::Result< protocol::Task > cancel_task(std::string_view task_id)
Cancels a task by task identifier.
std::function< void(const protocol::RequestId &, std::string_view)> CancelledHandler
Receives cancellation notifications for in-flight requests.
Definition client.hpp:231
std::function< core::Result< protocol::Json >(const protocol::JsonRpcRequest &)> CustomRequestHandler
Handles non-built-in server requests.
Definition client.hpp:283
core::Result< std::vector< std::string > > complete_prompt_simple(std::string_view prompt_name, std::string_view argument_name, std::string current_value, protocol::Json context=protocol::Json::object())
Returns prompt completion values only.
core::Result< protocol::Json > initialize(std::string client_name, std::string client_version, RequestOptions options)
Sends the MCP initialize request with per-request options.
RequestHandle< protocol::PromptsGetResult > get_prompt_async(const protocol::PromptsGetParams &params, RequestOptions options={})
Asynchronously gets a prompt and parses the typed response.
Client & set_capabilities(protocol::ClientCapabilities capabilities)
Sets client capabilities used during initialization.
RequestHandle< protocol::Json > request_async(std::string method, protocol::Json params=protocol::Json::object(), RequestOptions options={})
Sends a cancellable raw request with an auto-generated id.
core::Result< protocol::CreateMessageResult > create_message(const protocol::CreateMessageParams &request)
Sends a sampling createMessage request using typed protocol parameters.
Client & on_resource_updated(ResourceUpdatedHandler handler)
Registers a callback for resource update notifications.
Client & on_create_message_request(CreateMessageRequestHandler handler)
Registers a handler for server sampling createMessage requests.
core::Result< protocol::CompletionResult > complete_resource_argument(std::string_view uri_template, std::string_view argument_name, std::string current_value, protocol::Json context=protocol::Json::object())
Completes a resource template argument using RMCP-style helper parameters.
Client & on_custom_request(CustomRequestHandler handler)
Registers a handler for custom server requests not handled by the built-in client dispatcher.
core::Result< protocol::CompletionResult > complete_prompt_argument(std::string_view prompt_name, std::string_view argument_name, std::string current_value, protocol::Json context=protocol::Json::object())
Completes a prompt argument using RMCP-style helper parameters.
RequestHandle< protocol::ResourcesReadResult > read_resource_async(const protocol::ResourcesReadParams &params, RequestOptions options={})
Asynchronously reads a resource and parses the typed response.
std::vector< protocol::Root > list_roots() const
Returns the roots currently advertised by this client.
core::Result< core::Unit > set_level(std::string_view level)
Sets the server logging level by level name.
RequestHandle< protocol::Json > task_result_async(std::string_view task_id, RequestOptions options={})
Asynchronously gets a task result by identifier.
core::Result< protocol::ResourceTemplatesListResult > list_resource_templates_page(const protocol::PaginatedRequestParams &params={})
Lists one typed page of resource templates.
std::function< core::Result< protocol::CreateMessageResult >(const protocol::CreateMessageParams &)> SamplingRequestHandler
Handles a server sampling request.
Definition client.hpp:264
RequestHandle< protocol::CreateTaskResult > call_tool_task_async(const protocol::ToolCall &call, RequestOptions options={})
Asynchronously starts a task-aware tool call.
std::function< void(std::string_view)> ElicitationCompleteHandler
Receives completion notifications for elicitation flows.
Definition client.hpp:247
Client & on_tool_list_changed(ListChangedHandler handler)
Registers a callback for tool list change notifications.
RequestHandle< protocol::PromptsGetResult > get_prompt_async(std::string_view name, const protocol::Json &arguments=protocol::Json::object(), RequestOptions options={})
Asynchronously gets a prompt by name.
RequestHandle< protocol::ResourcesReadResult > read_resource_async(std::string_view uri, RequestOptions options={})
Asynchronously reads a resource by URI.
core::Result< core::Unit > handle_notification(const protocol::JsonRpcNotification &notification)
Dispatches an inbound notification through built-in and registered handlers.
core::Result< protocol::ResourcesListResult > list_resources_page(const protocol::PaginatedRequestParams &params={})
Lists one typed page of resources, preserving pagination metadata.
RequestHandle< protocol::CreateElicitationResult > create_elicitation_async(const protocol::CreateElicitationRequestParam &request, RequestOptions options={})
Asynchronously creates an elicitation request.
RequestHandle< protocol::Json > create_elicitation_async(const protocol::Json &request, RequestOptions options={})
Asynchronously sends a raw elicitation request.
std::function< void()> ListChangedHandler
Receives list-change notifications for prompts, resources, tools, or roots.
Definition client.hpp:235
core::Result< std::vector< protocol::Task > > list_tasks()
Lists one page of tasks advertised by the server.
core::Result< protocol::CreateTaskResult > call_tool_task(const protocol::ToolCall &call)
Calls a task-aware tool and returns the created task handle.
core::Result< protocol::ResourcesReadResult > read_resource(const protocol::ResourcesReadParams &params)
Reads a resource by protocol parameter object.
RequestHandle< protocol::Task > get_task_async(const protocol::TaskGetParams &request, RequestOptions options={})
Asynchronously gets a task using typed protocol parameters.
core::Result< protocol::Json > task_result(const protocol::TaskResultParams &request)
Gets a task result using typed protocol parameters.
core::Result< std::vector< protocol::Resource > > list_resources()
Lists one page of resources advertised by the server.
RequestHandle< std::vector< protocol::Task > > list_tasks_async(RequestOptions options={})
Asynchronously lists tasks and parses the typed response.
core::Result< protocol::ToolsListResult > list_tools_page(const protocol::PaginatedRequestParams &params={})
Lists one typed page of tool definitions.
RequestHandle< protocol::CreateMessageResult > create_message_async(const protocol::CreateMessageParams &request, RequestOptions options={})
Asynchronously creates a sampling message.
Client & on_custom_notification(RawNotificationHandler handler)
Compatibility alias for on_raw_notification().
std::function< void()> InitializedHandler
Receives notifications that the peer completed initialization.
Definition client.hpp:225
core::Result< core::Unit > raw_notification(const protocol::JsonRpcNotification &notification)
Sends a raw JSON-RPC notification.
std::function< void(const protocol::JsonRpcNotification &)> RawNotificationHandler
Observes every inbound notification after built-in dispatch.
Definition client.hpp:293
std::function< core::Result< protocol::CreateElicitationResult >(const protocol::CreateElicitationRequestParam &)> ElicitationRequestHandler
Handles a server elicitation request.
Definition client.hpp:274
core::Result< protocol::ToolResult > call_tool(const protocol::ToolCall &call)
Calls a tool using a protocol ToolCall object.
core::Result< core::Unit > notify_cancelled(protocol::RequestId request_id, std::string reason={})
Sends a cancellation notification for a request.
RequestHandle< protocol::Json > complete_async(const protocol::Json &request, RequestOptions options={})
Asynchronously sends a raw completion request.
Client & on_roots_list_changed(ListChangedHandler handler)
Registers a callback for roots list change notifications.
RequestHandle< protocol::CompleteResult > complete_async(const protocol::CompleteParams &request, RequestOptions options={})
Asynchronously completes a prompt/resource argument.
core::Result< protocol::Task > cancel_task(const protocol::TaskCancelParams &request)
Cancels a task using typed protocol parameters.
RequestHandle< protocol::Task > get_task_async(std::string_view task_id, RequestOptions options={})
Asynchronously gets a task by identifier.
core::Result< protocol::Json > create_message(const protocol::Json &request)
Sends a sampling createMessage request using raw JSON parameters.
Client & on_resource_list_changed(ListChangedHandler handler)
Registers a callback for resource list change notifications.
std::function< void(const protocol::Task &)> TaskStatusHandler
Receives task status notifications.
Definition client.hpp:250
core::Result< protocol::JsonRpcResponse > handle_request(const protocol::JsonRpcRequest &request)
Dispatches an inbound server request through built-in and custom handlers.
core::Result< protocol::TaskListResult > list_tasks_page(const protocol::TaskListParams &request={})
Lists one typed task page, preserving pagination metadata.
RequestHandle< std::vector< protocol::ResourceTemplate > > list_resource_templates_async(RequestOptions options={})
Asynchronously lists resource templates and parses the typed response.
core::Result< core::Unit > set_level(const protocol::LoggingSetLevelParams &params)
Sets the server logging level using typed protocol parameters.
core::Result< std::vector< protocol::ResourceTemplate > > list_all_resource_templates()
Lists all resource templates, following pagination cursors until exhausted.
core::Result< std::vector< protocol::Prompt > > list_prompts()
Lists one page of prompts advertised by the server.
Client & on_raw_notification(RawNotificationHandler handler)
Registers an observer for raw inbound notifications.
core::Result< protocol::Json > task_result(std::string_view task_id)
Gets a task result by task identifier.
Abstract client transport used by Client to exchange JSON-RPC messages.
Definition client.hpp:111
virtual core::Result< core::Unit > start(TransportRequestHandler request_handler, TransportNotificationHandler notification_handler={})
Starts receiving inbound messages for transports that need an active loop.
Definition client.hpp:136
virtual core::Result< core::Unit > send_notification(const protocol::JsonRpcNotification &notification)
Sends a JSON-RPC notification without waiting for a response.
virtual core::Result< protocol::JsonRpcResponse > send(const protocol::JsonRpcRequest &request)=0
Sends a JSON-RPC request and waits for the corresponding response.
virtual void stop() noexcept
Requests transport shutdown.
Definition client.hpp:148
std::function< core::Result< std::optional< HttpDpopProof > >(const HttpDpopRequestContext &)> HttpDpopRequestSigner
Signs one outbound HTTP request with a fresh DPoP proof.
Definition client.hpp:74
std::function< core::Result< core::Unit >(const protocol::JsonRpcNotification &)> TransportNotificationHandler
Handles JSON-RPC notifications sent by the server to this client.
Definition client.hpp:103
std::function< core::Result< protocol::JsonRpcResponse >(const protocol::JsonRpcRequest &)> TransportRequestHandler
Handles JSON-RPC requests sent by the server to this client.
Definition client.hpp:96
Aggregate callback configuration for mcp::client::Client.
Completion request and result payloads.
Elicitation request, result, and schema payloads.
Logging level and notification payloads.
Prompt discovery and rendering payloads.
Shared JSON, JSON-RPC, error, cancellation, and progress model types.
std::variant< std::int64_t, std::string > ProgressToken
Identifier used to associate progress notifications with a request.
Definition types.hpp:215
nlohmann::json Json
JSON value type used by all protocol DTOs.
Definition types.hpp:28
std::variant< std::int64_t, std::string > RequestId
JSON-RPC request or response identifier.
Definition types.hpp:56
Request lifecycle helpers for cancellable SDK calls.
Resource listing, template, subscription, and read payloads.
Shared result and error primitives used by the public cxxmcp SDK.
std::monostate Unit
Success value for operations that only need to report failure.
Definition result.hpp:55
tl::expected< T, Error > Result
Alias for the SDK result type.
Definition result.hpp:64
Client root discovery payloads.
Client-side model sampling request and response payloads.
JSON-RPC method names and message construction/parsing helpers.
Options for an outbound SDK request.
Definition request.hpp:103
Contract-style client handler interface.
Definition handler.hpp:27
Optional callback bundle for configuring a Client in one call.
Definition handler.hpp:106
Basic options for endpoint-oriented client construction.
Definition client.hpp:77
std::chrono::milliseconds timeout
Per-operation timeout used by transports that support request deadlines.
Definition client.hpp:82
std::string endpoint
Remote endpoint URI or implementation-defined endpoint string.
Definition client.hpp:79
Endpoint options for launching a child process over stdio.
Definition client.hpp:205
std::unordered_map< std::string, std::string > env
Extra environment variables for the child process.
Definition client.hpp:213
std::string cwd
Optional working directory for the child process.
Definition client.hpp:211
std::vector< std::string > args
Command-line arguments passed to the executable.
Definition client.hpp:209
std::string command
Executable to launch.
Definition client.hpp:207
DPoP material produced for one outbound HTTP request.
Definition client.hpp:63
std::string authorization_scheme
Authorization scheme replacing Bearer, normally "DPoP".
Definition client.hpp:67
std::string proof
Value for the DPoP header (proof JWT).
Definition client.hpp:65
Context handed to a DPoP request signer for one outbound HTTP request (SEP-1932 / RFC 9449).
Definition client.hpp:50
std::string url
Absolute request URL the proof is bound to (htu).
Definition client.hpp:54
std::optional< std::string > nonce
Latest DPoP-Nonce value supplied by the server, when known.
Definition client.hpp:59
std::string method
HTTP method of the outbound request, e.g. "POST" or "GET".
Definition client.hpp:52
std::optional< std::string > access_token
Access token being sent on the request, bound via ath; unset when the request carries no token.
Definition client.hpp:57
Capabilities advertised by an MCP client during initialization.
Definition capabilities.hpp:296
Parameters for completion/complete.
Definition completion.hpp:98
Parameters for elicitation/create.
Definition elicitation.hpp:335
Parameters for sampling/createMessage.
Definition sampling.hpp:231
JSON-RPC notification envelope for one-way MCP messages.
Definition types.hpp:137
JSON-RPC request envelope carrying an MCP method invocation.
Definition types.hpp:99
std::string method
JSON-RPC method name such as tools/call or initialize.
Definition types.hpp:101
Parameters for logging/setLevel.
Definition logging.hpp:42
Shared pagination params for MCP list requests that use cursor.
Definition types.hpp:43
Parameters for notifications/progress.
Definition types.hpp:226
Parameters for prompts/get.
Definition prompt.hpp:181
Parameters for resources/read.
Definition resource.hpp:227
One client root entry.
Definition roots.hpp:24
Parameters for tasks/cancel.
Definition task.hpp:234
Parameters for tasks/get.
Definition task.hpp:209
Parameters for tasks/list.
Definition task.hpp:187
Snapshot of an asynchronous task.
Definition task.hpp:144
Parameters for tools/call.
Definition tool.hpp:335
Tool definition, call, and result payloads.