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

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

#include "base/allocator.h"

static void
call_rebuild_index(const mcpc_tool_t *tool, mcpc_ucbr_t *result)
{
  tiny_mcp_tools_context_t *context = tiny_mcp_tools_context_current();
  tiny_rebuild_report_t report;
  tiny_search_index_t *rebuilt;
  tiny_history_index_t *history;
  tiny_store_status_t status;
  tiny_json_buffer_t json;
  (void)tool;
  if (!context)
    {
      tiny_mcp_tool_add_error(result, "INTERNAL_ERROR", "tool context is unavailable");
      return;
    }
  status = tiny_store_rebuild(context->store, &report);
  if (status != TINY_STORE_OK)
    {
      tiny_mcp_tool_add_error(result, tiny_store_status_name(status), "index rebuild failed");
      return;
    }
  tiny_history_index_free(context->history_index);
  context->history_index = NULL;
  rebuilt = tiny_mcp_tools_build_search_index(context->store);
  history = tiny_history_index_build(context->store);
  if (!rebuilt || !history)
    {
      tiny_search_index_free(rebuilt);
      tiny_history_index_free(history);
      tiny_search_index_free(context->search_index);
      context->search_index = NULL;
      tiny_mcp_tool_add_error(result, "INTERNAL_ERROR", "search index allocation failed");
      return;
    }
  tiny_search_index_free(context->search_index);
  context->search_index = rebuilt;
  context->history_index = history;
  tiny_json_init(&json);
  tiny_json_raw(&json, "{\"status\":\"OK\",\"messages_indexed\":");
  tiny_json_u64(&json, report.messages_indexed);
  tiny_json_raw(&json, ",\"records_removed\":");
  tiny_json_u64(&json, report.records_removed);
  tiny_json_raw(&json, ",\"bytes_before\":");
  tiny_json_u64(&json, report.bytes_before);
  tiny_json_raw(&json, ",\"bytes_after\":");
  tiny_json_u64(&json, report.bytes_after);
  tiny_json_raw(&json, "}");
  tiny_mcp_tool_add_json(result, &json);
  tiny_json_free(&json);
}

bool
tiny_mcp_register_rebuild_index(mcpc_server_t *server)
{
  mcpc_tool_t *tool = tiny_mcp_tool_new("rebuild_index", "Compact and rebuild", call_rebuild_index);
  return tool && mcpc_server_add_tool(server, tool) == MCPC_EC_0;
}