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

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

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

#include "base/allocator.h"

static int
compare_history(const void *left, const void *right)
{
  const tiny_store_entry_t *a = *(const tiny_store_entry_t *const *)left;
  const tiny_store_entry_t *b = *(const tiny_store_entry_t *const *)right;
  if (a->message.timestamp_ms < b->message.timestamp_ms)
    {
      return -1;
    }
  if (a->message.timestamp_ms > b->message.timestamp_ms)
    {
      return 1;
    }
  return strcmp(a->message.message_id, b->message.message_id);
}

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 *session = tiny_mcp_tool_get_string(tool, "session_id", TINY_SESSION_ID_MAX);
  const tiny_store_entry_t **items = NULL;
  size_t index, count = 0;
  tiny_json_buffer_t json;
  if (!context || !session || !session[0])
    {
      free(session);
      tiny_mcp_tool_add_error(result, "VALIDATION_ERROR", "session_id is required");
      return;
    }
  items = malloc((tiny_store_entry_count(context->store) + 1) * sizeof(*items));
  if (!items)
    {
      free(session);
      tiny_mcp_tool_add_error(result, "INTERNAL_ERROR", "out of memory");
      return;
    }
  for (index = 0; index < tiny_store_entry_count(context->store); ++index)
    {
      const tiny_store_entry_t *entry = tiny_store_entry(context->store, index);
      if (!entry->deleted && strcmp(entry->message.session_id, session) == 0)
        {
          items[count++] = entry;
        }
    }
  qsort(items, count, sizeof(*items), compare_history);
  tiny_json_init(&json);
  tiny_json_raw(&json, "{\"history\":[");
  for (index = 0; index < count; ++index)
    {
      if (index)
        {
          tiny_json_raw(&json, ",");
        }
      tiny_mcp_tool_append_message(&json, &items[index]->message);
    }
  tiny_json_raw(&json, "]}");
  tiny_mcp_tool_add_json(result, &json);
  tiny_json_free(&json);
  free(items);
  free(session);
}

bool
tiny_mcp_register_read_messages(mcpc_server_t *server)
{
  mcpc_tool_t *tool = tiny_mcp_tool_new("read_messages", "Read a session", call_read_messages);
  return tool && tiny_mcp_tool_add_property(tool, "session_id", "Session ID", MCPC_U8STR)
         && mcpc_server_add_tool(server, tool) == MCPC_EC_0;
}