summaryrefslogtreecommitdiff
path: root/src/mcp/tools/read_messages.c
blob: 109becbc4c88cb799971ebde5267b2f195534b73 (plain)
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
#include "mcp/tools/common/registry.h"

#include "mcp/tools/common/common.h"
#include "mcp/tools/common/context.h"

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "base/allocator.h"
#include "storage/codec.h"
#include "mjson.h"

#define READ_DEFAULT_LIMIT 100
#define READ_MAX_LIMIT 1000
#define READ_RESPONSE_BUDGET (8U * 1024U * 1024U - 64U * 1024U)
#define CURSOR_BYTES 47U
#define CURSOR_TEXT_MAX 64U

typedef struct history_cursor
{
  int64_t timestamp;
  char message_id[27];
} history_cursor_t;

static uint64_t
session_hash(const char *value)
{
  uint64_t hash = UINT64_C(1469598103934665603);
  while (*value)
    {
      hash ^= (unsigned char)*value++;
      hash *= UINT64_C(1099511628211);
    }
  return hash;
}

static size_t
base64url_encode(const unsigned char *input, size_t length, char *output, size_t capacity)
{
  static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
  size_t source = 0, target = 0;
  while (source < length)
    {
      uint32_t value = (uint32_t)input[source++] << 16;
      unsigned available = 1;
      if (source < length)
        {
          value |= (uint32_t)input[source++] << 8;
          available++;
        }
      if (source < length)
        {
          value |= input[source++];
          available++;
        }
      if (target + available + 1 >= capacity)
        {
          return 0;
        }
      output[target++] = alphabet[(value >> 18) & 63];
      output[target++] = alphabet[(value >> 12) & 63];
      if (available > 1)
        {
          output[target++] = alphabet[(value >> 6) & 63];
        }
      if (available > 2)
        {
          output[target++] = alphabet[value & 63];
        }
    }
  output[target] = '\0';
  return target;
}

static int
base64_value(unsigned char value)
{
  if (value >= 'A' && value <= 'Z')
    {
      return value - 'A';
    }
  if (value >= 'a' && value <= 'z')
    {
      return value - 'a' + 26;
    }
  if (value >= '0' && value <= '9')
    {
      return value - '0' + 52;
    }
  if (value == '-')
    {
      return 62;
    }
  if (value == '_')
    {
      return 63;
    }
  return -1;
}

static bool
base64url_decode(const char *input, unsigned char output[CURSOR_BYTES])
{
  size_t length = strlen(input), source = 0, target = 0;
  uint32_t accumulator = 0;
  unsigned bits = 0;
  if (length != 63)
    {
      return false;
    }
  while (source < length)
    {
      int value = base64_value((unsigned char)input[source++]);
      if (value < 0)
        {
          return false;
        }
      accumulator = (accumulator << 6) | (uint32_t)value;
      bits += 6;
      if (bits >= 8)
        {
          bits -= 8;
          if (target >= CURSOR_BYTES)
            {
              return false;
            }
          output[target++] = (unsigned char)(accumulator >> bits);
          accumulator &= bits ? (UINT32_C(1) << bits) - 1 : 0;
        }
    }
  return target == CURSOR_BYTES && accumulator == 0;
}

static bool
cursor_encode(const char *session, const tiny_message_t *message, char output[CURSOR_TEXT_MAX])
{
  unsigned char data[CURSOR_BYTES] = { 0 };
  data[0] = 1;
  tiny_codec_put_u64(data + 1, session_hash(session));
  tiny_codec_put_u64(data + 9, (uint64_t)message->timestamp_ms);
  memcpy(data + 17, message->message_id, 26);
  tiny_codec_put_u32(data + 43, tiny_codec_crc32(data, 43));
  return base64url_encode(data, sizeof(data), output, CURSOR_TEXT_MAX) == 63;
}

static bool
cursor_decode(const char *session, const char *value, history_cursor_t *cursor)
{
  unsigned char data[CURSOR_BYTES];
  if (!value || !value[0] || !base64url_decode(value, data) || data[0] != 1
      || tiny_codec_get_u64(data + 1) != session_hash(session)
      || tiny_codec_get_u32(data + 43) != tiny_codec_crc32(data, 43))
    {
      return false;
    }
  memcpy(cursor->message_id, data + 17, 26);
  cursor->message_id[26] = '\0';
  cursor->timestamp = (int64_t)tiny_codec_get_u64(data + 9);
  return cursor->timestamp >= 0 && tiny_message_id_valid(cursor->message_id);
}

static int
compare_cursor(const tiny_message_t *message, const history_cursor_t *cursor)
{
  if (message->timestamp_ms < cursor->timestamp)
    {
      return -1;
    }
  if (message->timestamp_ms > cursor->timestamp)
    {
      return 1;
    }
  return strcmp(message->message_id, cursor->message_id);
}

static size_t
escaped_size(const char *value, size_t length)
{
  size_t position, total = 0;
  for (position = 0; position < length; ++position)
    {
      unsigned char byte = (unsigned char)value[position];
      total += byte < 0x20 ? 6 : (byte == '"' || byte == '\\' ? 2 : 1);
    }
  return total;
}

typedef struct context_edge
{
  size_t entry_index;
  tiny_relation_type_t type;
  size_t depth;
  bool incoming;
  int64_t timestamp;
  char message_id[TINY_MESSAGE_ID_LENGTH + 1];
} context_edge_t;

static bool
relation_type_mask(const char *json, uint32_t *mask)
{
  int offset = 0, key_offset, key_length, value_offset, value_length, value_type;
  if (!json)
    {
      *mask = UINT32_MAX;
      return true;
    }
  if (mjson_find(json, (int)strlen(json), "$", NULL, NULL) != MJSON_TOK_ARRAY)
    {
      return false;
    }
  *mask = 0;
  while ((offset = mjson_next(json,
                              (int)strlen(json),
                              offset,
                              &key_offset,
                              &key_length,
                              &value_offset,
                              &value_length,
                              &value_type))
         != 0)
    {
      char value[24];
      int decoded;
      tiny_relation_type_t type;
      if (value_type != MJSON_TOK_STRING
          || (decoded
              = mjson_get_string(json + value_offset, value_length, "$", value, sizeof(value)))
                 <= 0
          || decoded >= (int)sizeof(value))
        {
          return false;
        }
      value[decoded] = '\0';
      if (!tiny_relation_type_parse(value, &type))
        {
          return false;
        }
      *mask |= UINT32_C(1) << (unsigned)type;
    }
  return true;
}

static int
compare_context_edges(const void *left, const void *right)
{
  const context_edge_t *a = left, *b = right;
  if (a->depth != b->depth)
    {
      return a->depth < b->depth ? -1 : 1;
    }
  if (a->type != b->type)
    {
      return a->type < b->type ? -1 : 1;
    }
  if (a->timestamp != b->timestamp)
    {
      return a->timestamp < b->timestamp ? -1 : 1;
    }
  return strcmp(a->message_id, b->message_id);
}

static void
call_context_view(tiny_mcp_tools_context_t *context, const mcpc_tool_t *tool, mcpc_ucbr_t *result)
{
  char *message_id = tiny_mcp_tool_get_string(tool, "message_id", TINY_MESSAGE_ID_LENGTH);
  char *types_json = tiny_mcp_tool_get_string(tool, "relation_types_json", 256);
  int32_t before = 1, after = 1, relation_depth = 1;
  mcpc_errcode_t before_status
      = mcpc_tool_get_tpropval_i32(tool, (const char8_t *)"before", &before);
  mcpc_errcode_t after_status = mcpc_tool_get_tpropval_i32(tool, (const char8_t *)"after", &after);
  mcpc_errcode_t depth_status
      = mcpc_tool_get_tpropval_i32(tool, (const char8_t *)"relation_depth", &relation_depth);
  const tiny_store_entry_t *target = NULL;
  const size_t *entries = NULL;
  const tiny_relation_reference_t *incoming = NULL;
  size_t session_entry_count = 0, position, target_position = SIZE_MAX, emitted, message_count = 1;
  size_t incoming_count = 0;
  size_t target_index, queue[50], queue_depth[50], queue_head = 0, queue_count = 0;
  context_edge_t edges[49];
  size_t edge_count = 0;
  bool *visited = NULL, truncated = false;
  uint32_t type_mask;
  tiny_json_buffer_t json;
  if (!message_id || before < 0 || before > 10 || after < 0 || after > 10 || relation_depth < 0
      || relation_depth > 2
      || (before_status != MCPC_EC_0 && before_status != MCPC_EC_ANYDATA_NOTFOUND)
      || (after_status != MCPC_EC_0 && after_status != MCPC_EC_ANYDATA_NOTFOUND)
      || (depth_status != MCPC_EC_0 && depth_status != MCPC_EC_ANYDATA_NOTFOUND)
      || !relation_type_mask(types_json, &type_mask) || !context
      || !tiny_mcp_tools_ensure_memory_index(context)
      || !tiny_memory_index_find(context->memory_index, message_id, &target_index))
    {
      tiny_mcp_tool_add_error(result, "VALIDATION_ERROR", "invalid context view arguments");
      free(message_id);
      free(types_json);
      return;
    }
  target = tiny_store_entry(context->store, target_index);
  if (!target || target->deleted || !tiny_mcp_tools_ensure_history_index(context)
      || !tiny_history_index_session(
          context->history_index, target->message.session_id, &entries, &session_entry_count))
    {
      tiny_mcp_tool_add_error(result, "NOT_FOUND", "message context was not found");
      free(message_id);
      free(types_json);
      return;
    }
  for (position = 0; position < session_entry_count; ++position)
    {
      if (strcmp(tiny_store_entry(context->store, entries[position])->message.message_id,
                 message_id)
          == 0)
        {
          target_position = position;
          break;
        }
    }
  if (target_position == SIZE_MAX
      || !(visited = calloc(tiny_store_entry_count(context->store), sizeof(bool))))
    {
      tiny_mcp_tool_add_error(result, "INTERNAL_ERROR", "context index allocation failed");
      free(message_id);
      free(types_json);
      return;
    }
  visited[target_index] = true;
  queue[queue_count] = target_index;
  queue_depth[queue_count++] = 0;
  while (queue_head < queue_count && edge_count < 49)
    {
      size_t current_index = queue[queue_head];
      size_t depth = queue_depth[queue_head++];
      const tiny_store_entry_t *current = tiny_store_entry(context->store, current_index);
      size_t relation;
      if (depth >= (size_t)relation_depth)
        {
          continue;
        }
      for (relation = 0; relation < current->message.metadata.relation_count; ++relation)
        {
          const tiny_relation_t *value = &current->message.metadata.relations[relation];
          size_t related_index;
          const tiny_store_entry_t *related;
          if (!(type_mask & (UINT32_C(1) << (unsigned)value->type))
              || !tiny_memory_index_find(context->memory_index, value->message_id, &related_index)
              || visited[related_index])
            {
              continue;
            }
          related = tiny_store_entry(context->store, related_index);
          visited[related_index] = true;
          edges[edge_count].entry_index = related_index;
          edges[edge_count].type = value->type;
          edges[edge_count].depth = depth + 1;
          edges[edge_count].incoming = false;
          edges[edge_count].timestamp = related->message.timestamp_ms;
          memcpy(edges[edge_count].message_id,
                 related->message.message_id,
                 sizeof(edges[edge_count].message_id));
          edge_count++;
          if (!related->deleted && queue_count < 50)
            {
              queue[queue_count] = related_index;
              queue_depth[queue_count++] = depth + 1;
            }
          if (edge_count == 49)
            {
              truncated = true;
              break;
            }
        }
      if (edge_count == 49)
        {
          break;
        }
      if (!tiny_memory_index_incoming(
              context->memory_index, current->message.message_id, &incoming, &incoming_count))
        {
          continue;
        }
      for (relation = 0; relation < incoming_count && edge_count < 49; ++relation)
        {
          const tiny_store_entry_t *related
              = tiny_store_entry(context->store, incoming[relation].source_index);
          if (!(type_mask & (UINT32_C(1) << (unsigned)incoming[relation].type))
              || visited[incoming[relation].source_index])
            {
              continue;
            }
          visited[incoming[relation].source_index] = true;
          edges[edge_count].entry_index = incoming[relation].source_index;
          edges[edge_count].type = incoming[relation].type;
          edges[edge_count].depth = depth + 1;
          edges[edge_count].incoming = true;
          edges[edge_count].timestamp = related->message.timestamp_ms;
          memcpy(edges[edge_count].message_id,
                 related->message.message_id,
                 sizeof(edges[edge_count].message_id));
          edge_count++;
          if (!related->deleted && queue_count < 50)
            {
              queue[queue_count] = incoming[relation].source_index;
              queue_depth[queue_count++] = depth + 1;
            }
        }
    }
  qsort(edges, edge_count, sizeof(*edges), compare_context_edges);
  tiny_json_init(&json);
  tiny_json_raw(&json, "{\"message\":");
  tiny_mcp_tool_append_message(&json, &target->message);
  tiny_json_raw(&json, ",\"chronological_context\":{\"before\":[");
  emitted = 0;
  position = target_position > (size_t)before ? target_position - (size_t)before : 0;
  for (; position < target_position; ++position)
    {
      const tiny_store_entry_t *entry = tiny_store_entry(context->store, entries[position]);
      if (entry && !entry->deleted)
        {
          tiny_json_buffer_t item;
          tiny_json_init(&item);
          tiny_mcp_tool_append_message(&item, &entry->message);
          if (message_count >= 50 || item.failed
              || json.length + item.length + 256 > READ_RESPONSE_BUDGET)
            {
              truncated = true;
              tiny_json_free(&item);
              break;
            }
          if (emitted++)
            {
              tiny_json_raw(&json, ",");
            }
          tiny_json_raw_n(&json, item.data, item.length);
          tiny_json_free(&item);
          message_count++;
        }
    }
  tiny_json_raw(&json, "],\"after\":[");
  emitted = 0;
  for (position = target_position + 1; position < session_entry_count && emitted < (size_t)after;
       ++position)
    {
      const tiny_store_entry_t *entry = tiny_store_entry(context->store, entries[position]);
      if (entry && !entry->deleted)
        {
          tiny_json_buffer_t item;
          tiny_json_init(&item);
          tiny_mcp_tool_append_message(&item, &entry->message);
          if (message_count >= 50 || item.failed
              || json.length + item.length + 256 > READ_RESPONSE_BUDGET)
            {
              truncated = true;
              tiny_json_free(&item);
              break;
            }
          if (emitted++)
            {
              tiny_json_raw(&json, ",");
            }
          tiny_json_raw_n(&json, item.data, item.length);
          tiny_json_free(&item);
          message_count++;
        }
    }
  tiny_json_raw(&json, "]},\"relations\":[");
  emitted = 0;
  for (position = 0; position < edge_count; ++position)
    {
      const context_edge_t *edge = &edges[position];
      const tiny_store_entry_t *related = tiny_store_entry(context->store, edge->entry_index);
      tiny_json_buffer_t item;
      tiny_json_init(&item);
      tiny_json_raw(&item, "{\"type\":");
      tiny_json_string(&item, tiny_relation_type_name(edge->type));
      tiny_json_raw(&item,
                    edge->incoming ? ",\"direction\":\"incoming\"" : ",\"direction\":\"outgoing\"");
      tiny_json_raw(&item, ",\"depth\":");
      tiny_json_u64(&item, edge->depth);
      if (related && !related->deleted)
        {
          tiny_json_raw(&item, ",\"message\":");
          tiny_mcp_tool_append_message(&item, &related->message);
        }
      else
        {
          tiny_json_raw(&item, ",\"message_id\":");
          tiny_json_string(&item, edge->message_id);
          tiny_json_raw(&item, ",\"status\":\"deleted\"");
        }
      tiny_json_raw(&item, "}");
      if (message_count >= 50 || item.failed
          || json.length + item.length + 256 > READ_RESPONSE_BUDGET)
        {
          truncated = true;
          tiny_json_free(&item);
          break;
        }
      if (emitted++)
        {
          tiny_json_raw(&json, ",");
        }
      tiny_json_raw_n(&json, item.data, item.length);
      tiny_json_free(&item);
      if (related && !related->deleted)
        {
          message_count++;
        }
    }
  tiny_json_raw(&json, "],\"session\":{\"session_id\":");
  tiny_json_string(&json, target->message.session_id);
  tiny_json_raw(&json, ",\"message_count\":");
  tiny_json_u64(&json, session_entry_count);
  tiny_json_raw(&json, "},\"truncated\":");
  tiny_json_raw(&json, truncated ? "true" : "false");
  tiny_json_raw(&json, "}");
  tiny_mcp_tool_add_json(result, &json);
  tiny_json_free(&json);
  free(visited);
  free(message_id);
  free(types_json);
}

static size_t
simple_cursor(const char *cursor, bool *valid)
{
  char *end = NULL;
  unsigned long long value;
  if (!cursor)
    {
      *valid = true;
      return 0;
    }
  value = strtoull(cursor, &end, 10);
  *valid = cursor[0] && end && !*end && value <= SIZE_MAX;
  return *valid ? (size_t)value : 0;
}

static bool
session_cursor_encode(int64_t last_message_at, const char *session_id, char output[CURSOR_TEXT_MAX])
{
  unsigned char data[CURSOR_BYTES] = { 0 };
  data[0] = 2;
  tiny_codec_put_u64(data + 1, (uint64_t)last_message_at);
  tiny_codec_put_u32(data + 9,
                     tiny_codec_crc32((const unsigned char *)session_id, strlen(session_id)));
  memcpy(data + 13, session_id, strlen(session_id));
  tiny_codec_put_u32(data + 43, tiny_codec_crc32(data, 43));
  return base64url_encode(data, sizeof(data), output, CURSOR_TEXT_MAX) == 63;
}

static bool
session_cursor_decode(const char *cursor,
                      int64_t *last_message_at,
                      char session_id[TINY_SESSION_ID_MAX + 1])
{
  unsigned char data[CURSOR_BYTES];
  size_t length;
  if (!cursor || !cursor[0] || !base64url_decode(cursor, data) || data[0] != 2)
    {
      return false;
    }
  *last_message_at = (int64_t)tiny_codec_get_u64(data + 1);
  length = tiny_codec_get_u32(data + 9);
  if (length == 0 || length > TINY_SESSION_ID_MAX
      || tiny_codec_crc32(data, 43) != tiny_codec_get_u32(data + 43))
    {
      return false;
    }
  memcpy(session_id, data + 13, length);
  session_id[length] = '\0';
  return tiny_utf8_valid(session_id, length);
}

static int
compare_session_by_last_then_id(const void *left, const void *right)
{
  const tiny_history_index_session_info_t *a = left;
  const tiny_history_index_session_info_t *b = right;
  if (a->last_message_at != b->last_message_at)
    {
      return a->last_message_at < b->last_message_at ? -1 : 1;
    }
  return strcmp(a->session_id, b->session_id);
}

static void
call_sessions_view(tiny_mcp_tools_context_t *context, const mcpc_tool_t *tool, mcpc_ucbr_t *result)
{
  char *cursor = tiny_mcp_tool_get_string(tool, "cursor", CURSOR_TEXT_MAX);
  int32_t limit = READ_DEFAULT_LIMIT;
  tiny_json_buffer_t json;
  mcpc_errcode_t limit_status = mcpc_tool_get_tpropval_i32(tool, (const char8_t *)"limit", &limit);
  int64_t cursor_last = 0;
  char cursor_session[TINY_SESSION_ID_MAX + 1] = { 0 };
  bool has_cursor = cursor && cursor[0];
  size_t emitted = 0, index, position;
  const tiny_history_index_t *history;
  tiny_history_index_session_info_t *sessions = NULL;
  size_t session_count = 0;
  bool cursor_ok = !has_cursor || session_cursor_decode(cursor, &cursor_last, cursor_session);

  if (!context || !cursor_ok || limit < 1 || limit > READ_MAX_LIMIT
      || (limit_status != MCPC_EC_0 && limit_status != MCPC_EC_ANYDATA_NOTFOUND)
      || !tiny_mcp_tools_ensure_history_index(context) || !(history = context->history_index))
    {
      tiny_mcp_tool_add_error(result, "VALIDATION_ERROR", "invalid sessions view arguments");
      free(cursor);
      return;
    }

  session_count = tiny_history_index_session_count(history);
  if (session_count > 0)
    {
      sessions = malloc(session_count * sizeof(*sessions));
      if (!sessions)
        {
          tiny_mcp_tool_add_error(result, "INTERNAL_ERROR", "sessions allocation failed");
          free(cursor);
          return;
        }
      for (index = 0; index < session_count; ++index)
        {
          const char *session_id;
          const size_t *entries;
          size_t count;
          if (!tiny_history_index_session_at(history, index, &session_id, &entries, &count))
            {
              free(sessions);
              tiny_mcp_tool_add_error(result, "INTERNAL_ERROR", "session enumeration failed");
              free(cursor);
              return;
            }
          sessions[index].session_id = session_id;
          sessions[index].last_message_at
              = count > 0
                    ? tiny_store_entry(context->store, entries[count - 1])->message.timestamp_ms
                    : 0;
        }
      qsort(sessions, session_count, sizeof(*sessions), compare_session_by_last_then_id);
    }

  tiny_json_init(&json);
  tiny_json_raw(&json, "{\"sessions\":[");
  for (position = 0; position < session_count && emitted < (size_t)limit; ++position)
    {
      const char *session_id = sessions[position].session_id;
      const size_t *entries;
      size_t count, representative_index = SIZE_MAX;
      int64_t started = INT64_MAX, ended = 0;
      int kind_counts[6] = { 0 };
      const tiny_store_entry_t *representative = NULL;
      const char *summary = NULL;
      if (has_cursor
          && (sessions[position].last_message_at < cursor_last
              || (sessions[position].last_message_at == cursor_last
                  && strcmp(session_id, cursor_session) <= 0)))
        {
          continue;
        }
      if (!tiny_history_index_session(history, session_id, &entries, &count))
        {
          continue;
        }
      for (index = 0; index < count; ++index)
        {
          const tiny_store_entry_t *entry = tiny_store_entry(context->store, entries[index]);
          if (!entry || entry->deleted)
            {
              continue;
            }
          kind_counts[entry->message.metadata.memory_kind - 1]++;
          started = entry->message.timestamp_ms < started ? entry->message.timestamp_ms : started;
          ended = entry->message.timestamp_ms > ended ? entry->message.timestamp_ms : ended;
          representative_index = entries[index];
          representative = entry;
        }
      if (representative_index == SIZE_MAX)
        {
          continue;
        }
      if (emitted++)
        {
          tiny_json_raw(&json, ",");
        }
      summary = representative->message.metadata.summary ? representative->message.metadata.summary
                                                         : representative->message.content;
      tiny_json_raw(&json, "{\"session_id\":");
      tiny_json_string(&json, session_id);
      tiny_json_raw(&json, ",\"message_count\":");
      tiny_json_u64(&json, count);
      tiny_json_raw(&json, ",\"kind_counts\":{\"conversation\":");
      tiny_json_i64(&json, kind_counts[0]);
      tiny_json_raw(&json, ",\"episode\":");
      tiny_json_i64(&json, kind_counts[1]);
      tiny_json_raw(&json, ",\"semantic\":");
      tiny_json_i64(&json, kind_counts[2]);
      tiny_json_raw(&json, ",\"procedure\":");
      tiny_json_i64(&json, kind_counts[3]);
      tiny_json_raw(&json, ",\"preference\":");
      tiny_json_i64(&json, kind_counts[4]);
      tiny_json_raw(&json, ",\"summary\":");
      tiny_json_i64(&json, kind_counts[5]);
      tiny_json_raw(&json, "},\"representative_summary\":");
      tiny_json_string(&json, summary);
      tiny_json_raw(&json, ",\"started_at\":");
      tiny_json_i64(&json, started);
      tiny_json_raw(&json, ",\"last_message_at\":");
      tiny_json_i64(&json, ended);
      tiny_json_raw(&json, "}");
    }
  tiny_json_raw(&json, "]");
  if (emitted == (size_t)limit && position < session_count)
    {
      char next[CURSOR_TEXT_MAX];
      if (session_cursor_encode(
              sessions[position - 1].last_message_at, sessions[position - 1].session_id, next))
        {
          tiny_json_raw(&json, ",\"nextCursor\":");
          tiny_json_string(&json, next);
        }
    }
  tiny_json_raw(&json, "}");
  tiny_mcp_tool_add_json(result, &json);
  tiny_json_free(&json);
  free(sessions);
  free(cursor);
}

static void
call_read_messages(const mcpc_tool_t *tool, mcpc_ucbr_t *result)
{
  tiny_mcp_tools_context_t *context = tiny_mcp_tools_context_current();
  char *view = tiny_mcp_tool_get_string(tool, "view", 16);
  char *session = tiny_mcp_tool_get_string(tool, "session_id", TINY_SESSION_ID_MAX);
  char *cursor_text = tiny_mcp_tool_get_string(tool, "cursor", CURSOR_TEXT_MAX);
  int32_t requested_limit = READ_DEFAULT_LIMIT;
  mcpc_errcode_t limit_status
      = mcpc_tool_get_tpropval_i32(tool, (const char8_t *)"limit", &requested_limit);
  const size_t *entries = NULL;
  size_t entry_count = 0, position = 0, emitted = 0, outer_size = 256;
  history_cursor_t cursor;
  bool has_cursor = cursor_text != NULL, more = false;
  const tiny_message_t *last = NULL;
  tiny_json_buffer_t json;

  if (view && strcmp(view, "context") == 0)
    {
      call_context_view(context, tool, result);
      free(view);
      free(session);
      free(cursor_text);
      return;
    }
  if (view && strcmp(view, "sessions") == 0)
    {
      call_sessions_view(context, tool, result);
      free(view);
      free(session);
      free(cursor_text);
      return;
    }
  if (view && strcmp(view, "history") != 0)
    {
      tiny_mcp_tool_add_error(result, "VALIDATION_ERROR", "unsupported read_messages view");
      free(view);
      free(session);
      free(cursor_text);
      return;
    }
  free(view);

  if (!context || !session || !session[0]
      || (limit_status != MCPC_EC_0 && limit_status != MCPC_EC_ANYDATA_NOTFOUND)
      || requested_limit < 1 || requested_limit > READ_MAX_LIMIT
      || (has_cursor && !cursor_decode(session, cursor_text, &cursor)))
    {
      tiny_mcp_tool_add_error(result, "VALIDATION_ERROR", "invalid read_messages arguments");
      free(session);
      free(cursor_text);
      return;
    }
  if (!tiny_mcp_tools_ensure_history_index(context)
      || !tiny_history_index_session(context->history_index, session, &entries, &entry_count))
    {
      tiny_mcp_tool_add_error(result, "INTERNAL_ERROR", "history index allocation failed");
      free(session);
      free(cursor_text);
      return;
    }
  if (has_cursor)
    {
      size_t low = 0, high = entry_count;
      while (low < high)
        {
          size_t middle = low + (high - low) / 2;
          const tiny_store_entry_t *entry = tiny_store_entry(context->store, entries[middle]);
          if (compare_cursor(&entry->message, &cursor) <= 0)
            {
              low = middle + 1;
            }
          else
            {
              high = middle;
            }
        }
      position = low;
    }

  tiny_json_init(&json);
  tiny_json_raw(&json, "{\"history\":[");
  while (position < entry_count && emitted < (size_t)requested_limit)
    {
      const tiny_store_entry_t *entry = tiny_store_entry(context->store, entries[position]);
      tiny_json_buffer_t item;
      size_t item_size;
      if (!entry || entry->deleted)
        {
          position++;
          continue;
        }
      tiny_json_init(&item);
      tiny_mcp_tool_append_message(&item, &entry->message);
      item_size = escaped_size(item.data, item.length) + (emitted ? 2 : 0);
      if (item.failed || (emitted && outer_size + item_size > READ_RESPONSE_BUDGET))
        {
          tiny_json_free(&item);
          if (item.failed)
            {
              json.failed = true;
            }
          more = true;
          break;
        }
      if (emitted)
        {
          tiny_json_raw(&json, ",");
        }
      tiny_json_raw_n(&json, item.data, item.length);
      outer_size += item_size;
      emitted++;
      last = &entry->message;
      position++;
      tiny_json_free(&item);
    }
  if (!more)
    {
      size_t lookahead = position;
      while (lookahead < entry_count)
        {
          const tiny_store_entry_t *entry = tiny_store_entry(context->store, entries[lookahead++]);
          if (entry && !entry->deleted)
            {
              more = true;
              break;
            }
        }
    }
  tiny_json_raw(&json, "]");
  if (more && last)
    {
      char next_cursor[CURSOR_TEXT_MAX];
      if (!cursor_encode(session, last, next_cursor))
        {
          json.failed = true;
        }
      else
        {
          tiny_json_raw(&json, ",\"nextCursor\":");
          tiny_json_string(&json, next_cursor);
        }
    }
  tiny_json_raw(&json, "}");
  if (json.failed)
    {
      tiny_mcp_tool_add_error(result, "INTERNAL_ERROR", "response allocation failed");
    }
  else
    {
      tiny_mcp_tool_add_json(result, &json);
    }
  tiny_json_free(&json);
  free(session);
  free(cursor_text);
}

bool
tiny_mcp_register_read_messages(mcpc_server_t *server)
{
  mcpc_tool_t *tool
      = tiny_mcp_tool_new("read_messages",
                          "Read persisted messages from one known session in chronological order. "
                          "Returns a paginated history for reconstructing that conversation.",
                          call_read_messages);
  return tool
         && tiny_mcp_tool_add_property(
             tool, "view", "Read view: history (default), context, or sessions.", MCPC_U8STR, false)
         && tiny_mcp_tool_add_property(tool,
                                       "session_id",
                                       "Conversation session whose chronological history to read.",
                                       MCPC_U8STR,
                                       false)
         && tiny_mcp_tool_add_property(
             tool, "message_id", "Message ULID required by the context view.", MCPC_U8STR, false)
         && tiny_mcp_tool_add_property(
             tool, "before", "Context messages before the target, from 0 to 10.", MCPC_I32, false)
         && tiny_mcp_tool_add_property(
             tool, "after", "Context messages after the target, from 0 to 10.", MCPC_I32, false)
         && tiny_mcp_tool_add_property(tool,
                                       "relation_depth",
                                       "Relation traversal depth from 0 to 2; defaults to 1.",
                                       MCPC_I32,
                                       false)
         && tiny_mcp_tool_add_property(tool,
                                       "relation_types_json",
                                       "Optional JSON array string of relation types to follow.",
                                       MCPC_U8STR,
                                       false)
         && tiny_mcp_tool_add_property(
             tool,
             "limit",
             "Maximum messages to return in this page, from 1 to 1000; defaults to 100.",
             MCPC_I32,
             false)
         && tiny_mcp_tool_add_property(
             tool,
             "cursor",
             "Opaque nextCursor returned by a previous read_messages call; "
             "omit for the first page.",
             MCPC_U8STR,
             false)
         && mcpc_server_add_tool(server, tool) == MCPC_EC_0;
}