-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathhandler.cpp
More file actions
3351 lines (3079 loc) · 144 KB
/
handler.cpp
File metadata and controls
3351 lines (3079 loc) · 144 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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "fastmcpp/mcp/handler.hpp"
#include "fastmcpp/app.hpp"
#include "fastmcpp/mcp/tasks.hpp"
#include "fastmcpp/proxy.hpp"
#include "fastmcpp/server/sse_server.hpp"
#include "fastmcpp/telemetry.hpp"
#include "fastmcpp/util/pagination.hpp"
#include "fastmcpp/version.hpp"
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <memory>
#include <mutex>
#include <optional>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
namespace fastmcpp::mcp
{
// MCP spec error codes (SEP-compliant)
static constexpr int kJsonRpcMethodNotFound = -32601;
static constexpr int kJsonRpcInvalidParams = -32602;
static constexpr int kJsonRpcInternalError = -32603;
static constexpr int kMcpMethodNotFound = -32001; // MCP "Method not found"
static constexpr int kMcpResourceNotFound = -32002; // MCP "Resource not found"
static constexpr int kMcpToolTimeout = -32000;
static constexpr const char* kUiExtensionId = "io.modelcontextprotocol/ui";
// Helper: create fastmcp metadata namespace (parity with Python fastmcp 53e220a9)
static fastmcpp::Json make_fastmcp_meta()
{
return fastmcpp::Json{{"version", std::to_string(fastmcpp::VERSION_MAJOR) + "." +
std::to_string(fastmcpp::VERSION_MINOR) + "." +
std::to_string(fastmcpp::VERSION_PATCH)}};
}
static fastmcpp::Json merge_meta_with_ui(const std::optional<fastmcpp::Json>& meta,
const std::optional<fastmcpp::AppConfig>& app)
{
fastmcpp::Json merged = meta && meta->is_object() ? *meta : fastmcpp::Json::object();
if (app && !app->empty())
merged["ui"] = *app;
return merged;
}
static void attach_meta_ui(fastmcpp::Json& entry, const std::optional<fastmcpp::AppConfig>& app,
const std::optional<fastmcpp::Json>& meta = std::nullopt)
{
fastmcpp::Json merged = merge_meta_with_ui(meta, app);
if (!merged.empty())
entry["_meta"] = std::move(merged);
}
static std::string normalize_resource_uri(std::string uri)
{
while (uri.size() > 1 && !uri.empty() && uri.back() == '/')
uri.pop_back();
return uri;
}
static std::optional<fastmcpp::AppConfig> find_resource_app_config(const FastMCP& app,
const std::string& uri)
{
const std::string normalized = normalize_resource_uri(uri);
for (const auto& resource : app.list_all_resources())
{
if (!resource.app || resource.app->empty())
continue;
if (normalize_resource_uri(resource.uri) == normalized)
return resource.app;
}
for (const auto& templ : app.list_all_templates())
{
if (!templ.app || templ.app->empty())
continue;
if (templ.match(normalized).has_value())
return templ.app;
}
return std::nullopt;
}
static void attach_resource_content_meta_ui(fastmcpp::Json& content_json, const FastMCP& app,
const std::string& request_uri)
{
auto app_cfg = find_resource_app_config(app, request_uri);
if (!app_cfg)
return;
fastmcpp::Json meta = content_json.contains("_meta") && content_json["_meta"].is_object()
? content_json["_meta"]
: fastmcpp::Json::object();
meta["ui"] = *app_cfg;
if (!meta.empty())
content_json["_meta"] = std::move(meta);
}
static void advertise_ui_extension(fastmcpp::Json& capabilities)
{
if (!capabilities.contains("extensions") || !capabilities["extensions"].is_object())
capabilities["extensions"] = fastmcpp::Json::object();
capabilities["extensions"][kUiExtensionId] = fastmcpp::Json::object();
}
static void inject_client_extensions_meta(fastmcpp::Json& args,
const fastmcpp::server::ServerSession& session)
{
auto caps = session.capabilities();
if (!caps.contains("extensions") || !caps["extensions"].is_object())
return;
if (!args.contains("_meta") || !args["_meta"].is_object())
args["_meta"] = fastmcpp::Json::object();
args["_meta"]["client_extensions"] = caps["extensions"];
}
static fastmcpp::Json jsonrpc_error(const fastmcpp::Json& id, int code, const std::string& message)
{
return fastmcpp::Json{{"jsonrpc", "2.0"},
{"id", id.is_null() ? fastmcpp::Json() : id},
{"error", fastmcpp::Json{{"code", code}, {"message", message}}}};
}
static fastmcpp::Json jsonrpc_tool_error(const fastmcpp::Json& id, const std::exception& e)
{
if (dynamic_cast<const fastmcpp::ToolTimeoutError*>(&e))
return jsonrpc_error(id, kMcpToolTimeout, e.what());
if (dynamic_cast<const fastmcpp::NotFoundError*>(&e))
return jsonrpc_error(id, kJsonRpcInvalidParams, e.what());
return jsonrpc_error(id, kJsonRpcInternalError, e.what());
}
/// Apply pagination to a JSON array, returning a result object with the key and optional nextCursor
static fastmcpp::Json apply_pagination(const fastmcpp::Json& items, const std::string& key,
const fastmcpp::Json& params, int page_size)
{
fastmcpp::Json result_obj = {{key, items}};
if (page_size <= 0)
return result_obj;
std::string cursor_str = params.value("cursor", std::string{});
auto cursor = cursor_str.empty() ? std::nullopt : std::optional<std::string>{cursor_str};
std::vector<fastmcpp::Json> vec(items.begin(), items.end());
auto paginated = util::pagination::paginate_sequence(vec, cursor, page_size);
result_obj[key] = paginated.items;
if (paginated.next_cursor.has_value())
result_obj["nextCursor"] = *paginated.next_cursor;
return result_obj;
}
static bool schema_is_object(const fastmcpp::Json& schema)
{
if (!schema.is_object())
return false;
auto it = schema.find("type");
if (it != schema.end() && it->is_string() && it->get<std::string>() == "object")
return true;
if (schema.contains("properties"))
return true;
// Self-referencing types often use a top-level $ref into $defs.
if (schema.contains("$ref") && schema.contains("$defs"))
return true;
return false;
}
// Extract session_id from request meta (injected by transports like SSE).
static std::string extract_session_id(const fastmcpp::Json& params)
{
if (params.contains("_meta") && params["_meta"].is_object() &&
params["_meta"].contains("session_id") && params["_meta"]["session_id"].is_string())
return params["_meta"]["session_id"].get<std::string>();
return "";
}
static std::optional<fastmcpp::Json> extract_request_meta(const fastmcpp::Json& params)
{
if (params.contains("_meta") && params["_meta"].is_object())
return params["_meta"];
return std::nullopt;
}
static fastmcpp::Json normalize_output_schema_for_mcp(const fastmcpp::Json& schema)
{
if (schema.is_null())
return schema;
// Python fastmcp requires object-shaped output schemas (MCP structuredContent is a dict).
// For scalar/array outputs, wrap into {"result": ...} and annotate for clients.
if (schema_is_object(schema))
return schema;
return fastmcpp::Json{
{"type", "object"},
{"properties", fastmcpp::Json{{"result", schema}}},
{"required", fastmcpp::Json::array({"result"})},
{"x-fastmcp-wrap-result", true},
};
}
static fastmcpp::Json make_tool_entry(
const std::string& name, const std::string& description, const fastmcpp::Json& schema,
const std::optional<std::string>& title = std::nullopt,
const std::optional<std::vector<fastmcpp::Icon>>& icons = std::nullopt,
const fastmcpp::Json& output_schema = fastmcpp::Json(),
fastmcpp::TaskSupport task_support = fastmcpp::TaskSupport::Forbidden, bool sequential = false,
const std::optional<fastmcpp::AppConfig>& app = std::nullopt,
const std::optional<fastmcpp::Json>& meta = std::nullopt)
{
fastmcpp::Json entry = {
{"name", name},
};
if (title)
entry["title"] = *title;
if (!description.empty())
entry["description"] = description;
// Schema may be empty
if (!schema.is_null() && !schema.empty())
entry["inputSchema"] = schema;
else
entry["inputSchema"] = fastmcpp::Json::object();
if (!output_schema.is_null() && !output_schema.empty())
entry["outputSchema"] = normalize_output_schema_for_mcp(output_schema);
if (task_support != fastmcpp::TaskSupport::Forbidden || sequential)
{
fastmcpp::Json execution = fastmcpp::Json::object();
if (task_support != fastmcpp::TaskSupport::Forbidden)
execution["taskSupport"] = fastmcpp::to_string(task_support);
if (sequential)
execution["concurrency"] = "sequential";
entry["execution"] = execution;
}
// Add icons if present
if (icons && !icons->empty())
{
fastmcpp::Json icons_json = fastmcpp::Json::array();
for (const auto& icon : *icons)
{
fastmcpp::Json icon_obj = {{"src", icon.src}};
if (icon.mime_type)
icon_obj["mimeType"] = *icon.mime_type;
if (icon.sizes)
icon_obj["sizes"] = *icon.sizes;
icons_json.push_back(icon_obj);
}
entry["icons"] = icons_json;
}
attach_meta_ui(entry, app, meta);
entry["fastmcp"] = make_fastmcp_meta();
return entry;
}
// ---------------------------------------------------------------------------
// Simple in-process task registry (SEP-1686 subset)
// ---------------------------------------------------------------------------
namespace
{
struct TaskInfo
{
std::string task_id;
std::string task_type; // e.g., "tool"
std::string component_identifier; // tool name, prompt name, or resource URI
std::string status; // "queued", "running", "completed", "failed", "cancelled"
std::string status_message;
std::string created_at; // ISO8601 string (best-effort)
std::string last_updated_at; // ISO8601 string (best-effort)
int ttl_ms{60000};
};
inline std::string mcp_status_from_internal(const std::string& status)
{
// Per SEP-1686 final spec: tasks MUST begin in "working".
// fastmcpp tracks "queued"/"running" internally; map both to "working" externally.
if (status == "queued" || status == "running")
return "working";
return status;
}
inline std::string to_iso8601_now()
{
using clock = std::chrono::system_clock;
auto now = clock::now();
std::time_t t = clock::to_time_t(now);
#ifdef _WIN32
std::tm tm;
gmtime_s(&tm, &t);
#else
std::tm tm;
gmtime_r(&t, &tm);
#endif
std::ostringstream oss;
oss << std::put_time(&tm, "%Y-%m-%dT%H:%M:%SZ");
return oss.str();
}
class TaskRegistry
{
public:
explicit TaskRegistry(SessionAccessor session_accessor = {})
: session_accessor_(std::move(session_accessor))
{
worker_ = std::thread([this]() { worker_loop(); });
}
~TaskRegistry()
{
{
std::lock_guard<std::mutex> lock(queue_mutex_);
stop_requested_ = true;
}
queue_cv_.notify_all();
if (worker_.joinable())
worker_.join();
}
struct CreateResult
{
std::string task_id;
std::string created_at;
};
CreateResult create_task(const std::string& task_type, const std::string& component_identifier,
int ttl_ms, std::string owner_session_id)
{
TaskEntry entry;
entry.info.task_id = generate_task_id();
entry.info.task_type = task_type;
entry.info.component_identifier = component_identifier;
entry.info.status = "queued";
entry.info.status_message = "";
entry.info.ttl_ms = ttl_ms;
entry.info.created_at = to_iso8601_now();
entry.info.last_updated_at = entry.info.created_at;
entry.created_tp = std::chrono::steady_clock::now();
entry.last_updated_tp = entry.created_tp;
entry.owner_session_id = std::move(owner_session_id);
entry.cancel_requested = std::make_shared<std::atomic_bool>(false);
std::string task_id = entry.info.task_id;
std::string created_at = entry.info.created_at;
auto notify = build_status_notification(entry, /*include_non_terminal=*/true);
{
std::lock_guard<std::mutex> lock(mutex_);
tasks_[entry.info.task_id] = std::move(entry);
}
if (notify)
send_status_notification(*notify);
return {std::move(task_id), std::move(created_at)};
}
void enqueue_task(const std::string& task_id, std::function<fastmcpp::Json()> work)
{
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = tasks_.find(task_id);
if (it == tasks_.end())
return;
it->second.work = std::move(work);
}
{
std::lock_guard<std::mutex> lock(queue_mutex_);
queue_.push_back(task_id);
}
queue_cv_.notify_one();
}
std::optional<TaskInfo> get_task(const std::string& task_id)
{
purge_expired_locked();
std::lock_guard<std::mutex> lock(mutex_);
auto it = tasks_.find(task_id);
if (it == tasks_.end())
return std::nullopt;
return it->second.info;
}
std::vector<TaskInfo> list_tasks()
{
purge_expired_locked();
std::lock_guard<std::mutex> lock(mutex_);
std::vector<TaskInfo> result;
result.reserve(tasks_.size());
for (const auto& kv : tasks_)
result.push_back(kv.second.info);
return result;
}
enum class ResultState
{
NotFound,
NotReady,
Completed,
Failed,
Cancelled,
};
struct ResultQuery
{
ResultState state{ResultState::NotFound};
fastmcpp::Json payload;
std::string error_message;
};
ResultQuery get_result(const std::string& task_id)
{
purge_expired_locked();
std::lock_guard<std::mutex> lock(mutex_);
auto it = tasks_.find(task_id);
if (it == tasks_.end())
{
ResultQuery query;
query.state = ResultState::NotFound;
return query;
}
const auto& info = it->second.info;
if (info.status == "completed")
{
ResultQuery query;
query.state = ResultState::Completed;
query.payload = it->second.result_payload;
return query;
}
if (info.status == "failed")
{
ResultQuery query;
query.state = ResultState::Failed;
query.error_message = it->second.error_message;
return query;
}
if (info.status == "cancelled")
{
ResultQuery query;
query.state = ResultState::Cancelled;
query.error_message = it->second.error_message;
return query;
}
ResultQuery query;
query.state = ResultState::NotReady;
return query;
}
bool cancel(const std::string& task_id)
{
purge_expired_locked();
std::optional<StatusNotification> notify;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = tasks_.find(task_id);
if (it == tasks_.end())
return false;
auto& entry = it->second;
if (entry.cancel_requested)
entry.cancel_requested->store(true);
if (entry.info.status == "queued" || entry.info.status == "running")
{
entry.info.status = "cancelled";
entry.info.status_message = "Task cancelled";
entry.error_message = "Task cancelled";
entry.info.last_updated_at = to_iso8601_now();
entry.last_updated_tp = std::chrono::steady_clock::now();
notify = build_status_notification(entry, /*include_non_terminal=*/false);
}
}
if (notify)
send_status_notification(*notify);
return true;
}
private:
bool set_status_message(const std::string& task_id, std::string message)
{
std::optional<StatusNotification> notify;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = tasks_.find(task_id);
if (it == tasks_.end())
return false;
auto& entry = it->second;
bool terminal = (entry.info.status == "completed" || entry.info.status == "failed" ||
entry.info.status == "cancelled");
if (terminal)
return false;
if (entry.info.status_message == message)
return true;
entry.info.status_message = std::move(message);
entry.info.last_updated_at = to_iso8601_now();
entry.last_updated_tp = std::chrono::steady_clock::now();
notify = build_status_notification(entry, /*include_non_terminal=*/true);
}
if (notify)
send_status_notification(*notify);
return true;
}
static void tls_set_status_message(void* ctx, const std::string& task_id,
const std::string& message)
{
auto* self = static_cast<TaskRegistry*>(ctx);
(void)self->set_status_message(task_id, message);
}
struct TaskEntry
{
TaskInfo info;
std::chrono::steady_clock::time_point created_tp{};
std::chrono::steady_clock::time_point last_updated_tp{};
std::string owner_session_id;
std::shared_ptr<std::atomic_bool> cancel_requested;
std::function<fastmcpp::Json()> work;
fastmcpp::Json result_payload;
std::string error_message;
};
struct StatusNotification
{
std::string owner_session_id;
fastmcpp::Json params;
};
std::optional<StatusNotification> build_status_notification(const TaskEntry& entry,
bool include_non_terminal) const
{
if (entry.owner_session_id.empty())
return std::nullopt;
const auto& info = entry.info;
bool terminal =
(info.status == "completed" || info.status == "failed" || info.status == "cancelled");
if (!terminal && !include_non_terminal)
return std::nullopt;
fastmcpp::Json status_params = {
{"taskId", info.task_id}, {"status", mcp_status_from_internal(info.status)},
{"createdAt", info.created_at}, {"lastUpdatedAt", info.last_updated_at},
{"ttl", info.ttl_ms}, {"pollInterval", 1000},
};
if (!info.status_message.empty())
status_params["statusMessage"] = info.status_message;
return StatusNotification{entry.owner_session_id, std::move(status_params)};
}
void send_status_notification(const StatusNotification& notification) const
{
if (!session_accessor_)
return;
auto session = session_accessor_(notification.owner_session_id);
if (!session)
return;
session->send_notification("notifications/tasks/status", notification.params);
}
void worker_loop()
{
while (true)
{
std::string task_id;
{
std::unique_lock<std::mutex> lock(queue_mutex_);
queue_cv_.wait(lock, [&] { return stop_requested_ || !queue_.empty(); });
if (stop_requested_ && queue_.empty())
break;
task_id = std::move(queue_.front());
queue_.pop_front();
}
execute_task(task_id);
}
}
void execute_task(const std::string& task_id)
{
std::function<fastmcpp::Json()> work;
std::shared_ptr<std::atomic_bool> cancel_requested;
std::optional<StatusNotification> notify;
bool should_execute = false;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = tasks_.find(task_id);
if (it == tasks_.end())
return;
auto& entry = it->second;
cancel_requested = entry.cancel_requested;
if (cancel_requested && cancel_requested->load() && entry.info.status == "queued")
{
entry.info.status = "cancelled";
entry.info.status_message = "Task cancelled";
entry.error_message = "Task cancelled";
entry.info.last_updated_at = to_iso8601_now();
entry.last_updated_tp = std::chrono::steady_clock::now();
notify = build_status_notification(entry, /*include_non_terminal=*/false);
}
else if (entry.info.status == "queued")
{
entry.info.status = "running";
entry.info.last_updated_at = to_iso8601_now();
entry.last_updated_tp = std::chrono::steady_clock::now();
work = entry.work;
should_execute = true;
notify = build_status_notification(entry, /*include_non_terminal=*/true);
}
// else: already terminal or running - nothing to do
}
if (notify)
{
send_status_notification(*notify);
if (!should_execute)
return;
}
if (!should_execute)
return;
if (!work)
{
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = tasks_.find(task_id);
if (it == tasks_.end())
return;
auto& entry = it->second;
entry.info.status = "failed";
entry.info.status_message = "Task has no work scheduled";
entry.error_message = "Task has no work scheduled";
entry.info.last_updated_at = to_iso8601_now();
entry.last_updated_tp = std::chrono::steady_clock::now();
notify = build_status_notification(entry, /*include_non_terminal=*/false);
}
if (notify)
send_status_notification(*notify);
return;
}
bool ok = false;
fastmcpp::Json payload;
std::string error;
try
{
struct TaskTlsScope
{
explicit TaskTlsScope(TaskRegistry* registry, const std::string& task_id)
{
fastmcpp::mcp::tasks::detail::set_current_task(
registry, &TaskRegistry::tls_set_status_message, task_id);
}
~TaskTlsScope()
{
fastmcpp::mcp::tasks::detail::clear_current_task();
}
};
TaskTlsScope scope(this, task_id);
payload = work();
ok = true;
}
catch (const std::exception& e)
{
ok = false;
error = e.what();
}
catch (...)
{
ok = false;
error = "Unknown task error";
}
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = tasks_.find(task_id);
if (it == tasks_.end())
return;
auto& entry = it->second;
if (entry.cancel_requested && entry.cancel_requested->load())
{
entry.info.status = "cancelled";
entry.info.status_message = "Task cancelled";
entry.error_message = "Task cancelled";
entry.info.last_updated_at = to_iso8601_now();
entry.last_updated_tp = std::chrono::steady_clock::now();
}
else if (ok)
{
entry.result_payload = std::move(payload);
entry.info.status = "completed";
entry.info.status_message = "Task completed successfully";
}
else
{
entry.info.status = "failed";
entry.info.status_message = "Task failed";
entry.error_message = error.empty() ? "Task failed" : error;
}
entry.info.last_updated_at = to_iso8601_now();
entry.last_updated_tp = std::chrono::steady_clock::now();
notify = build_status_notification(entry, /*include_non_terminal=*/false);
}
if (notify)
send_status_notification(*notify);
}
void purge_expired_locked()
{
std::lock_guard<std::mutex> lock(mutex_);
purge_expired_locked_no_lock();
}
void purge_expired_locked_no_lock()
{
auto now = std::chrono::steady_clock::now();
for (auto it = tasks_.begin(); it != tasks_.end();)
{
const auto& entry = it->second;
const auto& info = entry.info;
bool terminal = (info.status == "completed" || info.status == "failed" ||
info.status == "cancelled");
if (!terminal)
{
++it;
continue;
}
auto age_ms =
std::chrono::duration_cast<std::chrono::milliseconds>(now - entry.last_updated_tp)
.count();
if (age_ms > info.ttl_ms)
it = tasks_.erase(it);
else
++it;
}
}
std::string generate_task_id()
{
uint64_t id = next_id_.fetch_add(1, std::memory_order_relaxed) + 1;
return "task-" + std::to_string(id);
}
std::mutex mutex_;
std::unordered_map<std::string, TaskEntry> tasks_;
std::atomic<uint64_t> next_id_{0};
std::mutex queue_mutex_;
std::condition_variable queue_cv_;
std::deque<std::string> queue_;
bool stop_requested_{false};
std::thread worker_;
SessionAccessor session_accessor_;
};
// Helper: convert a tool invocation JSON result into an MCP CallToolResult payload.
// For tools that declare an outputSchema, include structuredContent for parity with Python fastmcp.
fastmcpp::Json build_fastmcp_tool_result(const fastmcpp::Json& result,
bool include_structured_content = false)
{
// If the tool already returned a CallToolResult-like object, preserve it (including isError,
// structuredContent, and _meta).
if (result.is_object() && result.contains("content"))
{
fastmcpp::Json payload = result;
if (!payload["content"].is_array())
{
if (payload["content"].is_object())
payload["content"] = fastmcpp::Json::array({payload["content"]});
else
payload["content"] = fastmcpp::Json::array();
}
if (payload.contains("structuredContent") && !payload["structuredContent"].is_object())
payload["structuredContent"] =
fastmcpp::Json{{"result", std::move(payload["structuredContent"])}};
return payload;
}
fastmcpp::Json content = fastmcpp::Json::array();
if (result.is_array())
content = result;
else if (result.is_string())
content = fastmcpp::Json::array(
{fastmcpp::Json{{"type", "text"}, {"text", result.get<std::string>()}}});
else
content =
fastmcpp::Json::array({fastmcpp::Json{{"type", "text"}, {"text", result.dump()}}});
fastmcpp::Json payload = fastmcpp::Json{{"content", content}};
if (include_structured_content)
{
if (result.is_object())
payload["structuredContent"] = result;
else
payload["structuredContent"] = fastmcpp::Json{{"result", result}};
}
return payload;
}
// Extract SEP-1686 task TTL from request params._meta if present.
inline bool extract_task_ttl(const fastmcpp::Json& params, int& ttl_ms_out)
{
ttl_ms_out = 60000;
if (!params.contains("_meta") || !params["_meta"].is_object())
return false;
const auto& meta = params["_meta"];
auto it = meta.find("modelcontextprotocol.io/task");
if (it == meta.end() || !it->is_object())
return false;
const auto& task_meta = *it;
if (task_meta.contains("ttl") && task_meta["ttl"].is_number_integer())
ttl_ms_out = task_meta["ttl"].get<int>();
return true;
}
inline fastmcpp::Json tasks_capabilities()
{
return fastmcpp::Json{
{"list", fastmcpp::Json::object()},
{"cancel", fastmcpp::Json::object()},
{"requests",
fastmcpp::Json{
{"tools", fastmcpp::Json{{"call", fastmcpp::Json::object()}}},
{"prompts", fastmcpp::Json{{"get", fastmcpp::Json::object()}}},
{"resources", fastmcpp::Json{{"read", fastmcpp::Json::object()}}},
}},
};
}
inline bool app_supports_tasks(const fastmcpp::FastMCP& app)
{
for (const auto& [name, tool] : app.list_all_tools())
if (tool && tool->task_support() != fastmcpp::TaskSupport::Forbidden)
return true;
for (const auto& res : app.list_all_resources())
if (res.task_support != fastmcpp::TaskSupport::Forbidden)
return true;
for (const auto& [name, prompt] : app.list_all_prompts())
if (prompt && prompt->task_support != fastmcpp::TaskSupport::Forbidden)
return true;
return false;
}
inline std::optional<fastmcpp::TaskSupport> find_tool_task_support(const fastmcpp::FastMCP& app,
const std::string& name)
{
for (const auto& [tool_name, tool] : app.list_all_tools())
if (tool_name == name && tool)
return tool->task_support();
return std::nullopt;
}
inline std::optional<fastmcpp::TaskSupport> find_prompt_task_support(const fastmcpp::FastMCP& app,
const std::string& name)
{
for (const auto& [prompt_name, prompt] : app.list_all_prompts())
if (prompt_name == name && prompt)
return prompt->task_support;
return std::nullopt;
}
inline std::optional<fastmcpp::TaskSupport> find_resource_task_support(const fastmcpp::FastMCP& app,
const std::string& uri)
{
for (const auto& res : app.list_all_resources())
if (res.uri == uri)
return res.task_support;
return std::nullopt;
}
} // namespace
std::function<fastmcpp::Json(const fastmcpp::Json&)>
make_mcp_handler(const std::string& server_name, const std::string& version,
const tools::ToolManager& tools,
const std::unordered_map<std::string, std::string>& descriptions,
const std::unordered_map<std::string, fastmcpp::Json>& input_schemas_override,
const std::optional<std::string>& instructions)
{
return [server_name, version, &tools, descriptions, input_schemas_override,
instructions](const fastmcpp::Json& message) -> fastmcpp::Json
{
try
{
const auto id = message.contains("id") ? message.at("id") : fastmcpp::Json();
std::string method = message.value("method", "");
fastmcpp::Json params = message.value("params", fastmcpp::Json::object());
const std::string session_id = extract_session_id(params);
if (method == "initialize")
{
fastmcpp::Json result_obj = {
{"protocolVersion", "2024-11-05"},
{"capabilities", fastmcpp::Json{{"tools", fastmcpp::Json::object()}}},
{"serverInfo", fastmcpp::Json{{"name", server_name}, {"version", version}}},
};
if (instructions.has_value())
result_obj["instructions"] = *instructions;
return fastmcpp::Json{{"jsonrpc", "2.0"}, {"id", id}, {"result", result_obj}};
}
if (method == "ping")
{
return fastmcpp::Json{
{"jsonrpc", "2.0"}, {"id", id}, {"result", fastmcpp::Json::object()}};
}
if (method == "tools/list")
{
fastmcpp::Json tools_array = fastmcpp::Json::array();
for (auto& name : tools.list_names())
{
// Get full tool object to access all fields
const auto& tool = tools.get(name);
fastmcpp::Json schema = fastmcpp::Json::object();
auto it = input_schemas_override.find(name);
if (it != input_schemas_override.end())
{
schema = it->second;
}
else
{
try
{
schema = tool.input_schema();
}
catch (...)
{
schema = fastmcpp::Json::object();
}
}
// Get description from override map or from tool
std::string desc = "";
auto dit = descriptions.find(name);
if (dit != descriptions.end())
desc = dit->second;
else if (tool.description())
desc = *tool.description();
tools_array.push_back(make_tool_entry(
name, desc, schema, tool.title(), tool.icons(), tool.output_schema(),
tool.task_support(), tool.sequential(), tool.app()));
}
return fastmcpp::Json{{"jsonrpc", "2.0"},
{"id", id},
{"result", fastmcpp::Json{{"tools", tools_array}}}};
}
if (method == "tools/call")
{
std::string name = params.value("name", "");
fastmcpp::Json args = params.value("arguments", fastmcpp::Json::object());
if (name.empty())
return jsonrpc_error(id, kJsonRpcInvalidParams, "Missing tool name");
auto span = telemetry::server_span(
"tool " + name, "tools/call", server_name, "tool", name,
extract_request_meta(params),
session_id.empty() ? std::nullopt : std::optional<std::string>(session_id));
try
{
const auto& tool = tools.get(name);
bool has_output_schema = !tool.output_schema().is_null();
auto result = tools.invoke(name, args);
fastmcpp::Json result_payload =
build_fastmcp_tool_result(result, has_output_schema);
return fastmcpp::Json{