/* tool_search: see toolsearch.h. The ranker is Pi's (packages/coding-agent/src/extensions/
* tool-search/tool.ts): Okapi BM25 over a tool's description and its schema's descriptions and
* property names, with the tool's name weighed three times a term's IDF, and a query that is a
* tool's own name ranking it first. Differences: words are split at ASCII boundaries (text
* outside ASCII stays whole), and schema `$ref`s and server descriptions are not read. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include <ctype.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sqlite3.h"
#include "toolsearch.h"
#define TS_DEFAULT_LIMIT 8
#define TS_NAME_WEIGHT 3.0
#define TS_K1 1.2
#define TS_B 0.75
const char pic_toolsearch_schema[] =
"{\"name\":\"tool_search\",\"description\":\"# Tool discovery\\n\\nSearches over deferred tool metadata with BM25 "
"and exposes matching tools for the next model call.\\n\\nSome of the tools, such as tools of MCP servers, may "
"not have been provided to you upfront, and you should use this tool (`tool_search`) to search for the required "
"tools. For MCP tool discovery, always use `tool_search`.\",\"input_schema\":{\"type\":\"object\",\"properties\":"
"{\"query\":{\"type\":\"string\",\"description\":\"Search query for deferred tools.\"},\"limit\":{\"type\":"
"\"number\",\"description\":\"Maximum number of tools to return. Defaults to 8.\"}},\"required\":[\"query\"]}}";
/* ---- words ----------------------------------------------------------------------------------- */
typedef struct {
char **v;
size_t n, cap;
} ts_words;
static void ts_words_free(ts_words *w) {
for (size_t i = 0; i < w->n; i++) {
free(w->v[i]);
}
free(w->v);
memset(w, 0, sizeof *w);
}
static int ts_words_add(ts_words *w, const char *s, size_t n) {
char *d;
if (w->n == w->cap) {
size_t cap = w->cap ? w->cap * 2 : 16;
char **grown = realloc(w->v, cap * sizeof *grown);
if (!grown) {
return -1;
}
w->v = grown;
w->cap = cap;
}
if (!(d = malloc(n + 1))) {
return -1;
}
memcpy(d, s, n);
d[n] = '\0';
w->v[w->n++] = d;
return 0;
}
static int ts_has(const ts_words *w, const char *s) {
for (size_t i = 0; i < w->n; i++) {
if (strcmp(w->v[i], s) == 0) {
return 1;
}
}
return 0;
}
static size_t ts_count(const ts_words *w, const char *s) {
size_t c = 0;
for (size_t i = 0; i < w->n; i++) {
c += strcmp(w->v[i], s) == 0;
}
return c;
}
static const char *const ts_stop[] = {"a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "in",
"is", "it", "of", "on", "or", "that", "the", "this", "to", "with"};
static int ts_is_stop(const char *w) {
for (size_t i = 0; i < sizeof ts_stop / sizeof ts_stop[0]; i++) {
if (strcmp(w, ts_stop[i]) == 0) {
return 1;
}
}
return 0;
}
static int ts_ends(const char *w, size_t n, const char *suffix) {
size_t k = strlen(suffix);
return n >= k && memcmp(w + n - k, suffix, k) == 0;
}
/* Pi's naive singular: issues -> issue, searches -> search. W (N bytes, plain ASCII) is shortened. */
static size_t ts_stem(char *w, size_t n) {
if (n > 4 && ts_ends(w, n, "ies")) {
w[n - 3] = 'y';
return n - 2;
}
if (n > 4 && (ts_ends(w, n, "ches") || ts_ends(w, n, "shes") || ts_ends(w, n, "sses") || ts_ends(w, n, "xes") ||
ts_ends(w, n, "zes"))) {
return n - 2;
}
if (n > 3 && w[n - 1] == 's' && w[n - 2] != 's') {
return n - 1;
}
return n;
}
/* The words of TEXT: split at case and punctuation boundaries, lowercased, without stop words,
* singular. 0, or -1 out of memory. */
static int ts_tokenize(const char *text, ts_words *out) {
size_t len = strlen(text), n = 0;
char *buf = malloc(2 * len + 2), *p;
int rc = 0;
if (!buf) {
return -1;
}
for (size_t i = 0; i < len; i++) {
unsigned char c = (unsigned char)text[i], prev = i ? (unsigned char)text[i - 1] : 0,
next = i + 1 < len ? (unsigned char)text[i + 1] : 0;
if ((isupper(c) && (islower(prev) || isdigit(prev))) || (isupper(c) && isupper(prev) && islower(next))) {
buf[n++] = ' ';
}
buf[n++] = c >= 0x80 || isalnum(c) ? (char)(c >= 0x80 ? c : tolower(c)) : ' ';
}
buf[n] = '\0';
for (p = buf; *p && rc == 0;) {
size_t k = strcspn(p, " ");
if (k) {
int plain = 1;
for (size_t i = 0; i < k; i++) {
plain &= (unsigned char)p[i] < 0x80;
}
if (plain) {
char word[256];
if (k < sizeof word) {
memcpy(word, p, k);
word[k] = '\0';
if (!ts_is_stop(word)) {
rc = ts_words_add(out, word, ts_stem(word, k));
}
}
} else {
rc = ts_words_add(out, p, k);
}
}
p += k + (p[k] ? 1 : 0);
}
free(buf);
return rc;
}
/* ---- documents -------------------------------------------------------------------------------- */
typedef struct {
const pic_tool_def *def;
ts_words name, local, text; /* the name's words, those of its last `__` part, and the rest */
} ts_doc;
typedef struct {
size_t at;
double score;
int covered, exact;
} ts_match;
/* The tool's description, its schema's descriptions and its property names, as one text (malloc'd). */
static char *ts_text(sqlite3 *db, const char *json) {
sqlite3_stmt *q = NULL;
char *out = NULL;
if (sqlite3_prepare_v2(db,
"SELECT group_concat(v, ' ') FROM ("
" SELECT json_extract(?1, '$.description') AS v"
" UNION ALL SELECT value FROM json_tree(?1, '$.input_schema') WHERE key = 'description' AND type = 'text'"
" UNION ALL SELECT t.key FROM json_tree(?1, '$.input_schema') t WHERE t.parent IN"
" (SELECT id FROM json_tree(?1, '$.input_schema') WHERE key = 'properties'))",
-1, &q, NULL) != SQLITE_OK) {
return NULL;
}
sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
out = strdup((const char *)sqlite3_column_text(q, 0));
}
sqlite3_finalize(q);
return out ? out : strdup("");
}
/* Pi's normalizeName: trimmed, lowercase, anything but [a-z0-9_$] as '_'. */
static void ts_normalize(const char *s, char *out, size_t cap) {
size_t n = 0, end = strlen(s);
while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n') {
s++;
end--;
}
while (end && (s[end - 1] == ' ' || s[end - 1] == '\t' || s[end - 1] == '\r' || s[end - 1] == '\n')) {
end--;
}
for (size_t i = 0; i < end && n + 1 < cap; i++) {
unsigned char c = (unsigned char)tolower((unsigned char)s[i]);
out[n++] = isalnum(c) || c == '_' || c == '$' ? (char)c : '_';
}
out[n] = '\0';
}
static int ts_exact(const char *query, const char *name) {
char norm[256], suffix[260];
ts_normalize(name, norm, sizeof norm);
(void)snprintf(suffix, sizeof suffix, "__%s", query);
return strcmp(norm, query) == 0 || ts_ends(norm, strlen(norm), suffix);
}
static int ts_by_rank(const void *a, const void *b) {
const ts_match *x = a, *y = b;
if (x->exact != y->exact) {
return y->exact - x->exact;
}
if (x->covered != y->covered) {
return y->covered - x->covered;
}
if (x->score != y->score) {
return x->score < y->score ? 1 : -1;
}
return x->at < y->at ? -1 : x->at > y->at; /* ties keep document order */
}
/* Pi's Bm25Ranker over DOCS: up to LIMIT matches in rank order into OUT (room for LIMIT); the count. */
static size_t ts_rank(const char *query, const ts_doc *docs, size_t n, size_t limit, ts_match *out) {
ts_words terms = {NULL, 0, 0}, uniq = {NULL, 0, 0};
double *idf = NULL, avg = 0, bonus = 0;
ts_match *all = NULL;
size_t found = 0;
char exactq[256];
if (n == 0 || limit == 0 || ts_tokenize(query, &terms) != 0) {
ts_words_free(&terms);
return 0;
}
for (size_t i = 0; i < terms.n; i++) {
if (!ts_has(&uniq, terms.v[i]) && ts_words_add(&uniq, terms.v[i], strlen(terms.v[i])) != 0) {
goto done;
}
}
if (uniq.n == 0 || !(idf = calloc(uniq.n, sizeof *idf)) || !(all = calloc(n, sizeof *all))) {
goto done;
}
for (size_t i = 0; i < n; i++) {
avg += (double)docs[i].text.n;
}
avg = avg / (double)n;
if (avg == 0) {
avg = 1;
}
for (size_t t = 0; t < uniq.n; t++) {
size_t df = 0;
for (size_t i = 0; i < n; i++) {
df += ts_has(&docs[i].name, uniq.v[t]) || ts_has(&docs[i].text, uniq.v[t]);
}
idf[t] = log(1 + ((double)n - (double)df + 0.5) / ((double)df + 0.5));
bonus += idf[t];
}
ts_normalize(query, exactq, sizeof exactq);
for (size_t i = 0; i < n; i++) {
double norm = TS_K1 * (1 - TS_B + TS_B * (double)docs[i].text.n / avg), score = 0;
int covered = 0, whole = docs[i].local.n > 0;
for (size_t t = 0; t < uniq.n; t++) {
double count = (double)ts_count(&docs[i].text, uniq.v[t]);
double weight = (ts_has(&docs[i].name, uniq.v[t]) ? TS_NAME_WEIGHT : 0) + count * (TS_K1 + 1) / (count + norm);
covered += weight > 0;
score += idf[t] * weight;
}
for (size_t k = 0; k < docs[i].local.n; k++) {
whole &= ts_has(&uniq, docs[i].local.v[k]);
}
if (score == 0) {
continue;
}
if (whole) {
score += bonus;
}
all[found++] = (ts_match){i, score, covered, ts_exact(exactq, docs[i].def->name)};
}
if (found > 1) { /* glibc: qsort's array may not be NULL, even empty */
qsort(all, found, sizeof *all, ts_by_rank);
}
if (found > limit) {
found = limit;
}
memcpy(out, all, found * sizeof *out);
done:
free(all);
free(idf);
ts_words_free(&terms);
ts_words_free(&uniq);
return found;
}
/* ---- the tool ------------------------------------------------------------------------------------ */
static char *ts_say(int *is_error, int error, const char *fmt, ...) {
va_list ap;
int n;
char *out;
va_start(ap, fmt);
n = vsnprintf(NULL, 0, fmt, ap);
va_end(ap);
if (n < 0 || !(out = malloc((size_t)n + 1))) {
return NULL;
}
va_start(ap, fmt);
(void)vsnprintf(out, (size_t)n + 1, fmt, ap);
va_end(ap);
*is_error = error;
return out;
}
static void ts_docs_free(ts_doc *docs, size_t n) {
for (size_t i = 0; i < n; i++) {
ts_words_free(&docs[i].name);
ts_words_free(&docs[i].local);
ts_words_free(&docs[i].text);
}
free(docs);
}
static char *ts_run(void *state, const char *workspace, const char *tool, const pic_tool_args *args,
const pic_tool_hooks *h, int *is_error) {
sqlite3 *db = NULL;
sqlite3_stmt *q = NULL;
const pic_tool_def *deferred[256];
ts_doc *docs = NULL;
ts_match *hits = NULL;
char *query = NULL, *declared = NULL, *out = NULL, *names = NULL;
double limit = TS_DEFAULT_LIMIT;
size_t nd, n = 0, found = 0, cap;
(void)state;
(void)workspace;
(void)tool;
(void)args;
*is_error = 0;
if (h->started == NULL || h->started(h->ctx, NULL, 0) != 0) {
return NULL;
}
if (sqlite3_open(":memory:", &db) != SQLITE_OK ||
sqlite3_prepare_v2(db,
"SELECT CASE WHEN json_valid(?1) THEN json_extract(?1, '$.query') END,"
" CASE WHEN json_valid(?1) THEN json_type(?1, '$.limit') END,"
" CASE WHEN json_valid(?1) THEN json_extract(?1, '$.limit') END",
-1, &q, NULL) != SQLITE_OK) {
out = ts_say(is_error, 1, "tool_search could not read its input");
goto done;
}
sqlite3_bind_text(q, 1, h->input ? h->input : "{}", -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW) {
if (sqlite3_column_type(q, 0) == SQLITE_TEXT) {
query = strdup((const char *)sqlite3_column_text(q, 0));
}
if (sqlite3_column_type(q, 1) != SQLITE_NULL) {
const char *type = (const char *)sqlite3_column_text(q, 1);
double v = sqlite3_column_double(q, 2);
if ((strcmp(type, "integer") != 0 && strcmp(type, "real") != 0) || v != floor(v) || v <= 0) {
out = ts_say(is_error, 1, "limit must be a positive integer");
goto done;
}
limit = v;
}
}
if (!query || !*query || strspn(query, " \t\r\n") == strlen(query)) {
out = ts_say(is_error, 1, "query must not be empty");
goto done;
}
nd = pic_toolset_deferred(deferred, sizeof deferred / sizeof deferred[0]);
declared = h->declared ? h->declared(h->declared_ctx) : NULL;
docs = calloc(nd ? nd : 1, sizeof *docs);
for (size_t i = 0; docs && i < nd; i++) {
const char *name = deferred[i]->name, *last = name, *at;
char *text;
size_t k = strlen(name);
int taken = 0;
for (const char *d = declared; d && *d;) {
size_t len = strcspn(d, "\n");
taken |= len == k && strncmp(d, name, k) == 0;
d += len + (d[len] ? 1 : 0);
}
if (taken) {
continue; /* already declared on this branch: not a candidate */
}
for (at = strstr(name, "__"); at; at = strstr(last, "__")) {
last = at + 2;
}
if (!(text = ts_text(db, deferred[i]->schema))) {
continue;
}
docs[n].def = deferred[i];
if (ts_tokenize(name, &docs[n].name) != 0 || ts_tokenize(last, &docs[n].local) != 0 ||
ts_tokenize(text, &docs[n].text) != 0) {
free(text);
ts_words_free(&docs[n].name);
ts_words_free(&docs[n].local);
ts_words_free(&docs[n].text);
continue;
}
free(text);
n++;
}
cap = limit > (double)n ? n : (size_t)limit;
hits = calloc(cap ? cap : 1, sizeof *hits);
if (!docs || !hits) {
out = ts_say(is_error, 1, "out of memory");
goto done;
}
found = ts_rank(query, docs, n, cap, hits);
if (found == 0) {
out = ts_say(is_error, 0, "No matching tools found.");
goto done;
}
{
size_t room = 64;
char *p;
for (size_t i = 0; i < found; i++) {
room += 2 * strlen(docs[hits[i].at].def->schema) + 8;
}
out = malloc(room);
names = malloc(room);
if (!out || !names) {
free(out);
free(names);
out = names = NULL;
out = ts_say(is_error, 1, "out of memory");
goto done;
}
p = out + snprintf(out, room, "Loaded %zu tool%s. They are available from your next call:", found, found == 1 ? "" : "s");
names[0] = '\0';
for (size_t i = 0; i < found; i++) {
const pic_tool_def *d = docs[hits[i].at].def;
sqlite3_stmt *m = NULL;
const char *first = "";
char *line = NULL;
if (sqlite3_prepare_v2(db, "SELECT trim(CASE WHEN instr(d, char(10)) THEN substr(d, 1, instr(d, char(10)) - 1) ELSE d END)"
" FROM (SELECT coalesce(json_extract(?1, '$.description'), '') AS d)",
-1, &m, NULL) == SQLITE_OK) {
sqlite3_bind_text(m, 1, d->schema, -1, SQLITE_STATIC);
if (sqlite3_step(m) == SQLITE_ROW && sqlite3_column_text(m, 0)) {
line = strdup((const char *)sqlite3_column_text(m, 0));
}
}
sqlite3_finalize(m);
first = line ? line : first;
p += snprintf(p, room - (size_t)(p - out), "\n- %s: %s", d->name, first);
strcat(names, d->name);
strcat(names, "\n");
free(line);
}
if (h->reveal) {
h->reveal->data = names;
h->reveal->len = strlen(names);
names = NULL;
}
}
done:
sqlite3_finalize(q);
sqlite3_close(db);
ts_docs_free(docs, n);
free(hits);
free(query);
free(declared);
free(names);
return out;
}
static int ts_default(void) { return pic_tool_has_deferred(); }
const pic_tool_def pic_toolsearch_tool = {"tool_search", pic_toolsearch_schema, 1, 1, PIC_TIER_BUNDLED, 0, ts_default,
ts_run, NULL, 1};