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

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

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

#include "base/allocator.h"

static tiny_metadata_parse_status_t
metadata_check_known_fields(const char *json, int length, const char **error)
{
  int offset = 0, key_offset, key_length, value_offset, value_length, value_type;
  while ((offset = mjson_next(json,
                              length,
                              offset,
                              &key_offset,
                              &key_length,
                              &value_offset,
                              &value_length,
                              &value_type))
         != 0)
    {
      char key[32];
      int decoded = mjson_get_string(json + key_offset, key_length, "$", key, sizeof(key));
      (void)value_offset;
      (void)value_length;
      (void)value_type;
      if (decoded <= 0 || decoded >= (int)sizeof(key))
        {
          *error = "metadata_json contains an invalid field name";
          return TINY_METADATA_PARSE_INVALID;
        }
      key[decoded] = '\0';
      if (strcmp(key, "tool_call_id") != 0 && strcmp(key, "tags") != 0
          && strcmp(key, "memory_tier") != 0 && strcmp(key, "memory_kind") != 0
          && strcmp(key, "importance") != 0 && strcmp(key, "summary") != 0
          && strcmp(key, "relations") != 0 && strcmp(key, "source_message_ids") != 0)
        {
          *error = "metadata_json contains an unknown field";
          return TINY_METADATA_PARSE_INVALID;
        }
    }
  return TINY_METADATA_PARSE_OK;
}

tiny_metadata_parse_status_t
tiny_mcp_parse_metadata(const char *json,
                        tiny_message_t *message,
                        tiny_metadata_mask_t *present,
                        const char **error)
{
  const char *tool_call = NULL, *tier = NULL, *tags = NULL, *kind = NULL, *summary = NULL;
  const char *relations = NULL, *sources = NULL;
  int tool_call_len = 0, tier_len = 0, tags_len = 0, kind_len = 0, summary_len = 0;
  int relations_len = 0, sources_len = 0;
  int offset = 0, key_offset, key_length, value_offset, value_length, value_type;
  int length = (int)strlen(json);
  int tool_call_type, tier_type, tags_type;
  int kind_type, summary_type, importance_type;
  int relations_type, sources_type;
  double importance = 50;
  tiny_metadata_mask_t fields = 0;
  if (error)
    {
      *error = NULL;
    }
  if (!json || !message || !error)
    {
      return TINY_METADATA_PARSE_INVALID;
    }
  if (strcmp(json, "{}") == 0)
    {
      return TINY_METADATA_PARSE_OK;
    }
  if (mjson_find(json, length, "$", NULL, NULL) != MJSON_TOK_OBJECT)
    {
      *error = "metadata_json must be a JSON object";
      return TINY_METADATA_PARSE_INVALID;
    }
  if (metadata_check_known_fields(json, length, error) != TINY_METADATA_PARSE_OK)
    {
      return TINY_METADATA_PARSE_INVALID;
    }
  tool_call_type = mjson_find(json, length, "$.tool_call_id", &tool_call, &tool_call_len);
  tier_type = mjson_find(json, length, "$.memory_tier", &tier, &tier_len);
  tags_type = mjson_find(json, length, "$.tags", &tags, &tags_len);
  kind_type = mjson_find(json, length, "$.memory_kind", &kind, &kind_len);
  summary_type = mjson_find(json, length, "$.summary", &summary, &summary_len);
  importance_type = mjson_find(json, length, "$.importance", NULL, NULL);
  relations_type = mjson_find(json, length, "$.relations", &relations, &relations_len);
  sources_type = mjson_find(json, length, "$.source_message_ids", &sources, &sources_len);
#define REQUIRE_METADATA_TYPE(actual, expected, field, type_name)                                  \
  do                                                                                               \
    {                                                                                              \
      if ((actual) != MJSON_TOK_INVALID && (actual) != (expected))                                 \
        {                                                                                          \
          *error = "metadata_json." field " must be " type_name;                                   \
          return TINY_METADATA_PARSE_INVALID;                                                      \
        }                                                                                          \
    }                                                                                              \
  while (0)
  REQUIRE_METADATA_TYPE(tool_call_type, MJSON_TOK_STRING, "tool_call_id", "a string");
  REQUIRE_METADATA_TYPE(tier_type, MJSON_TOK_STRING, "memory_tier", "a string");
  REQUIRE_METADATA_TYPE(tags_type, MJSON_TOK_ARRAY, "tags", "an array");
  REQUIRE_METADATA_TYPE(kind_type, MJSON_TOK_STRING, "memory_kind", "a string");
  REQUIRE_METADATA_TYPE(summary_type, MJSON_TOK_STRING, "summary", "a string");
  REQUIRE_METADATA_TYPE(importance_type, MJSON_TOK_NUMBER, "importance", "an integer");
  REQUIRE_METADATA_TYPE(relations_type, MJSON_TOK_ARRAY, "relations", "an array");
  REQUIRE_METADATA_TYPE(sources_type, MJSON_TOK_ARRAY, "source_message_ids", "an array");
#undef REQUIRE_METADATA_TYPE
  fields |= tool_call_type != MJSON_TOK_INVALID ? TINY_METADATA_TOOL_CALL_ID : 0;
  fields |= tags_type != MJSON_TOK_INVALID ? TINY_METADATA_TAGS : 0;
  fields |= tier_type != MJSON_TOK_INVALID ? TINY_METADATA_TIER : 0;
  fields |= kind_type != MJSON_TOK_INVALID ? TINY_METADATA_KIND : 0;
  fields |= importance_type != MJSON_TOK_INVALID ? TINY_METADATA_IMPORTANCE : 0;
  fields |= summary_type != MJSON_TOK_INVALID ? TINY_METADATA_SUMMARY : 0;
  fields |= relations_type != MJSON_TOK_INVALID ? TINY_METADATA_RELATIONS : 0;
  fields |= sources_type != MJSON_TOK_INVALID ? TINY_METADATA_SOURCES : 0;
  if (relations_type == MJSON_TOK_ARRAY)
    {
      offset = 0;
      while ((offset = mjson_next(relations,
                                  relations_len,
                                  offset,
                                  &key_offset,
                                  &key_length,
                                  &value_offset,
                                  &value_length,
                                  &value_type))
             != 0)
        {
          tiny_relation_t relation;
          char type[24];
          int decoded_type, decoded_id;
          tiny_relation_t *resized;
          if (value_type != MJSON_TOK_OBJECT
              || message->metadata.relation_count >= TINY_RELATION_COUNT_MAX)
            {
              *error = "metadata_json.relations must contain at most 32 objects";
              return TINY_METADATA_PARSE_INVALID;
            }
          decoded_type = mjson_get_string(
              relations + value_offset, value_length, "$.type", type, sizeof(type));
          decoded_id = mjson_get_string(relations + value_offset,
                                        value_length,
                                        "$.message_id",
                                        relation.message_id,
                                        sizeof(relation.message_id));
          if (decoded_type <= 0 || decoded_type >= (int)sizeof(type)
              || decoded_id != TINY_MESSAGE_ID_LENGTH)
            {
              *error = "metadata_json.relations entries require type and a 26-character message_id";
              return TINY_METADATA_PARSE_INVALID;
            }
          type[decoded_type] = '\0';
          relation.message_id[decoded_id] = '\0';
          if (!tiny_relation_type_parse(type, &relation.type)
              || !tiny_message_id_valid(relation.message_id))
            {
              *error = "metadata_json.relations contains an invalid type or message_id";
              return TINY_METADATA_PARSE_INVALID;
            }
          resized = realloc(message->metadata.relations,
                            (message->metadata.relation_count + 1) * sizeof(*resized));
          if (!resized)
            {
              *error = "metadata_json allocation failed";
              return TINY_METADATA_PARSE_NO_MEMORY;
            }
          message->metadata.relations = resized;
          message->metadata.relations[message->metadata.relation_count++] = relation;
        }
    }
  if (sources_type == MJSON_TOK_ARRAY)
    {
      offset = 0;
      while ((offset = mjson_next(sources,
                                  sources_len,
                                  offset,
                                  &key_offset,
                                  &key_length,
                                  &value_offset,
                                  &value_length,
                                  &value_type))
             != 0)
        {
          char *id;
          char **resized;
          int decoded;
          if (value_type != MJSON_TOK_STRING
              || message->metadata.source_count >= TINY_SOURCE_COUNT_MAX)
            {
              *error = "metadata_json.source_message_ids must contain at most 64 strings";
              return TINY_METADATA_PARSE_INVALID;
            }
          id = malloc(TINY_MESSAGE_ID_LENGTH + 1);
          if (!id)
            {
              *error = "metadata_json allocation failed";
              return TINY_METADATA_PARSE_NO_MEMORY;
            }
          decoded = mjson_get_string(
              sources + value_offset, value_length, "$", id, TINY_MESSAGE_ID_LENGTH + 1);
          if (decoded != TINY_MESSAGE_ID_LENGTH)
            {
              free(id);
              *error = "metadata_json.source_message_ids entries must be 26-character ULIDs";
              return TINY_METADATA_PARSE_INVALID;
            }
          id[decoded] = '\0';
          if (!tiny_message_id_valid(id))
            {
              free(id);
              *error = "metadata_json.source_message_ids contains an invalid ULID";
              return TINY_METADATA_PARSE_INVALID;
            }
          resized = realloc(message->metadata.source_message_ids,
                            (message->metadata.source_count + 1) * sizeof(*resized));
          if (!resized)
            {
              free(id);
              *error = "metadata_json allocation failed";
              return TINY_METADATA_PARSE_NO_MEMORY;
            }
          message->metadata.source_message_ids = resized;
          message->metadata.source_message_ids[message->metadata.source_count++] = id;
        }
    }
  if (importance_type == MJSON_TOK_NUMBER)
    {
      if (mjson_get_number(json, length, "$.importance", &importance) <= 0)
        {
          *error = "metadata_json.importance must be an integer from 0 to 100";
          return TINY_METADATA_PARSE_INVALID;
        }
      if (importance < 0 || importance > 100 || importance != (double)(uint8_t)importance)
        {
          *error = "metadata_json.importance must be an integer from 0 to 100";
          return TINY_METADATA_PARSE_INVALID;
        }
      message->metadata.importance = (uint8_t)importance;
    }
  if (kind_type == MJSON_TOK_STRING)
    {
      char value[24];
      int decoded = mjson_get_string(json, length, "$.memory_kind", value, sizeof(value));
      if (decoded <= 0 || decoded >= (int)sizeof(value))
        {
          *error = "metadata_json.memory_kind contains an invalid value";
          return TINY_METADATA_PARSE_INVALID;
        }
      value[decoded] = '\0';
      if (!tiny_kind_parse(value, &message->metadata.memory_kind))
        {
          *error = "metadata_json.memory_kind contains an invalid value";
          return TINY_METADATA_PARSE_INVALID;
        }
    }
  if (summary_type == MJSON_TOK_STRING)
    {
      int decoded;
      message->metadata.summary = malloc(TINY_SUMMARY_MAX + 1);
      if (!message->metadata.summary)
        {
          *error = "metadata_json allocation failed";
          return TINY_METADATA_PARSE_NO_MEMORY;
        }
      decoded = mjson_get_string(
          json, length, "$.summary", message->metadata.summary, TINY_SUMMARY_MAX + 1);
      if (decoded < 0 || decoded > TINY_SUMMARY_MAX
          || (decoded && !tiny_utf8_valid(message->metadata.summary, (size_t)decoded)))
        {
          *error = "metadata_json.summary must be valid UTF-8 up to 4096 bytes";
          return TINY_METADATA_PARSE_INVALID;
        }
      message->metadata.summary[decoded] = '\0';
      if (decoded == 0)
        {
          free(message->metadata.summary);
          message->metadata.summary = NULL;
        }
    }
  if (tool_call_type == MJSON_TOK_STRING)
    {
      int decoded;
      message->metadata.tool_call_id = malloc(TINY_TOOL_CALL_ID_MAX + 1);
      if (!message->metadata.tool_call_id)
        {
          *error = "metadata_json allocation failed";
          return TINY_METADATA_PARSE_NO_MEMORY;
        }
      decoded = mjson_get_string(json,
                                 length,
                                 "$.tool_call_id",
                                 message->metadata.tool_call_id,
                                 TINY_TOOL_CALL_ID_MAX + 1);
      if (decoded < 0 || decoded > TINY_TOOL_CALL_ID_MAX
          || !tiny_utf8_valid(message->metadata.tool_call_id, (size_t)decoded))
        {
          *error = "metadata_json.tool_call_id must be valid UTF-8 up to 256 bytes";
          return TINY_METADATA_PARSE_INVALID;
        }
      message->metadata.tool_call_id[decoded] = '\0';
    }
  if (tier_type == MJSON_TOK_STRING)
    {
      char tier_value[16];
      int decoded = mjson_get_string(json, length, "$.memory_tier", tier_value, sizeof(tier_value));
      if (decoded < 0 || decoded >= (int)sizeof(tier_value))
        {
          *error = "metadata_json.memory_tier contains an invalid value";
          return TINY_METADATA_PARSE_INVALID;
        }
      tier_value[decoded] = '\0';
      if (!tiny_tier_parse(tier_value, &message->metadata.memory_tier))
        {
          *error = "metadata_json.memory_tier contains an invalid value";
          return TINY_METADATA_PARSE_INVALID;
        }
    }
  if (tags_type == MJSON_TOK_ARRAY)
    {
      offset = 0;
      while ((offset = mjson_next(tags,
                                  tags_len,
                                  offset,
                                  &key_offset,
                                  &key_length,
                                  &value_offset,
                                  &value_length,
                                  &value_type))
             != 0)
        {
          char *tag;
          char **resized;
          int decoded;
          if (value_type != MJSON_TOK_STRING || message->metadata.tag_count >= TINY_TAG_COUNT_MAX)
            {
              *error = "metadata_json.tags must contain at most 32 strings";
              return TINY_METADATA_PARSE_INVALID;
            }
          tag = malloc(TINY_TAG_MAX + 1);
          if (!tag)
            {
              *error = "metadata_json allocation failed";
              return TINY_METADATA_PARSE_NO_MEMORY;
            }
          decoded = mjson_get_string(tags + value_offset, value_length, "$", tag, TINY_TAG_MAX + 1);
          if (decoded <= 0 || decoded > TINY_TAG_MAX || !tiny_utf8_valid(tag, (size_t)decoded))
            {
              free(tag);
              *error = "metadata_json.tags entries must be non-empty valid UTF-8 up to 128 bytes";
              return TINY_METADATA_PARSE_INVALID;
            }
          tag[decoded] = '\0';
          resized = realloc(message->metadata.tags,
                            (message->metadata.tag_count + 1) * sizeof(*message->metadata.tags));
          if (!resized)
            {
              free(tag);
              *error = "metadata_json allocation failed";
              return TINY_METADATA_PARSE_NO_MEMORY;
            }
          message->metadata.tags = resized;
          message->metadata.tags[message->metadata.tag_count++] = tag;
        }
    }
  if (present)
    {
      *present = fields;
    }
  if (!tiny_metadata_valid(&message->metadata))
    {
      *error = "metadata_json contains duplicate or inconsistent metadata values";
      return TINY_METADATA_PARSE_INVALID;
    }
  return TINY_METADATA_PARSE_OK;
}

static void
call_write_message(const mcpc_tool_t *tool, mcpc_ucbr_t *result)
{
  tiny_mcp_tools_context_t *context = tiny_mcp_tools_context_current();
  tiny_message_t input, written;
  tiny_store_status_t status;
  char *role = NULL, *metadata = NULL;
  const char *metadata_error = NULL;
  tiny_metadata_parse_status_t metadata_status = TINY_METADATA_PARSE_OK;
  tiny_json_buffer_t json;
  tiny_message_init(&input);
  tiny_message_init(&written);
  input.session_id = tiny_mcp_tool_get_string(tool, "session_id", TINY_SESSION_ID_MAX);
  role = tiny_mcp_tool_get_string(tool, "role", 16);
  input.content = tiny_mcp_tool_get_string(tool, "content", TINY_CONTENT_MAX);
  metadata = tiny_mcp_tool_get_string(tool, "metadata_json", TINY_CONTENT_MAX);
  bool valid = context && input.session_id && input.session_id[0] && role && input.content
               && input.content[0] && tiny_role_parse(role, &input.role);
  if (valid)
    {
      metadata_status
          = tiny_mcp_parse_metadata(metadata ? metadata : "{}", &input, NULL, &metadata_error);
    }
  if (!valid)
    {
      tiny_mcp_tool_add_error(result, "VALIDATION_ERROR", "invalid write_message arguments");
    }
  else if (metadata_status == TINY_METADATA_PARSE_NO_MEMORY)
    {
      tiny_mcp_tool_add_error(result, "INTERNAL_ERROR", metadata_error);
    }
  else if (metadata_status == TINY_METADATA_PARSE_INVALID)
    {
      tiny_mcp_tool_add_error(result, "VALIDATION_ERROR", metadata_error);
    }
  else
    {
      status = tiny_store_write(context->store, &input, &written);
      if (status != TINY_STORE_OK)
        {
          tiny_mcp_tool_add_error(
              result, tiny_store_status_name(status), "message was not written");
        }
      else
        {
          tiny_mcp_tools_invalidate_indexes(context);
          tiny_json_init(&json);
          tiny_json_raw(&json, "{\"status\":\"OK\",\"message\":");
          tiny_mcp_tool_append_message(&json, &written);
          tiny_json_raw(&json, "}");
          tiny_mcp_tool_add_json(result, &json);
          tiny_json_free(&json);
        }
    }
  free(role);
  free(metadata);
  tiny_message_free(&input);
  tiny_message_free(&written);
}

bool
tiny_mcp_register_write_message(mcpc_server_t *server)
{
  mcpc_tool_t *tool
      = tiny_mcp_tool_new("write_message",
                          "Append and durably persist a conversation message. Use it to store "
                          "information that should remain available after server restarts.",
                          call_write_message);
  return tool
         && tiny_mcp_tool_add_property(
             tool, "session_id", "Conversation session that owns the message.", MCPC_U8STR, true)
         && tiny_mcp_tool_add_property(
             tool, "role", "Message author role: user, assistant, or system.", MCPC_U8STR, true)
         && tiny_mcp_tool_add_property(
             tool, "content", "UTF-8 message text to persist.", MCPC_U8STR, true)
         && tiny_mcp_tool_add_property(tool,
                                       "metadata_json",
                                       "Optional JSON object string containing tool_call_id, tags, "
                                       "memory_tier, memory_kind, importance, summary, relations, "
                                       "and/or source_message_ids; "
                                       "defaults to {}.",
                                       MCPC_U8STR,
                                       false)
         && mcpc_server_add_tool(server, tool) == MCPC_EC_0;
}