Skip to content

search_messages: find threads by words, when the Web API implements search - #39

Merged
markmnl merged 3 commits into
mainfrom
search-tool
Nov 26, 2026
Merged

markmnl merged 3 commits into
mainfrom
search-tool

Conversation

@markmnl

@markmnl markmnl commented Nov 22, 2026

Copy link
Copy Markdown
Owner

Adds search_messages, which finds threads by the words in their topic, addresses, attachment names and text body. It uses GET /fmsg/search, an optional fmsg Web API endpoint (markmnl/fmsg-webapi#70), and is listed only where the Web API implements it.

The tool

  • Inputs: query (may be empty), unread_only, with_attachments, drafts_only, in_trash, sort (newest/oldest), limit (1–50, default 10) and offset.

  • Results: one summary per thread:

    • root and topic;
    • time of the newest message;
    • message_count and unread;
    • participants;
    • latest (the newest message);
    • match: where the words were found.

    The results also carry total, next_offset and terms. Read a thread with get_thread.

  • Annotations: READ_ONLY (read-only, closed-world, non-destructive). It needs fmsg:read over OAuth.

  • Instructions: they point to search_messages when it is listed, and keep "There is no search" when it isn't.

When it's listed

  • The check: FmsgClient.searchSupported() sends a query with no words, q=-. A Web API that implements search answers 200 without searching. 501, 404 or 400 (an older Web API that takes the path as a message id) mean no. Anything else can't tell.
  • The cache: src/search-support.ts keeps the answer per Web API URL for 10 minutes. When a Web API starts supporting search, the tool appears without restarting the server. Concurrent checks share one request, bounded at 2 seconds.
  • No token exchange just to list tools: over HTTP the check runs only when the caller already holds a Web API token. Over OAuth, tools/list therefore stays free of token exchanges. Until the answer is known, the last known answer stands, or the tool is listed if there is none yet.
  • Refusals: a 501 or 404 at call time explains itself and is remembered. A 503 asks for more specific words.
  • No credentials: a stdio server without credentials lists no search tool.

Testing

  • New test/search.test.ts (12 tests):
    • listing and instructions, with and without search;
    • thread grouping and summaries;
    • filter mapping and paging;
    • 501 and 503 answers;
    • the check's three outcomes, cache expiry, and listing when the host can't be reached;
    • no token exchange just to list tools;
    • HTTP listing for both implemented and 501.
  • The fake Web API gains a configurable /fmsg/search (implemented, 501, or no route).
  • test/oauth.test.ts: the "does not retry 403" test now ignores the one search check when counting upstream requests.
  • npm run typecheck, npm run build and npx vitest run pass (309 tests).

🤖 Generated with Claude Code

…earch

search_messages finds threads by the words in their topic, addresses,
attachment names and text body, with unread, attachment, draft and trash
filters, and summarises each result: topic, counts, participants, newest
message and where the words matched.

It uses GET /fmsg/search, an optional fmsg Web API endpoint, and is listed
only when the Web API implements it. The server asks with a query that has
no words (200 where implemented; 501, 404 or 400 where not) and keeps the
answer per Web API for 10 minutes. Listing tools never starts a token
exchange to find out: until the answer is known the tool is listed, and a
refusal at call time explains itself and is remembered. The instructions
point to search_messages when it is listed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@markmnl markmnl left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work: the per-API cache, never exchanging a token just to list tools, and staying listed while the answer is unknown are all good calls. One bug and a couple of suggestions:

1. Trashed messages are counted (bug). Per the contract (fmsg-webapi#70), `messages` includes messages in the trash (`trash` set) so the thread can be grouped. `summarizeThreads` only drops reactions and edits (`counted`). So with the default `in_trash: false`:

  • `message_count` and `unread` include deleted messages;
  • `latest` can be a deleted message.

Suggest filtering `m.trash` out of `counted` unless `in_trash`. Keep using all messages for grouping, which is what they're there for.

2. Treat 400 at call time the way the probe does. `searchSupported()` reads 400 as "no": an older Web API takes `/fmsg/search` as `/fmsg/:id`. But the tool's catch only handles 404/405/501. Before the first probe settles, the tool is listed by default. On an older Web API a call then fails with a raw `GET /fmsg/search?q=… 400 invalid message id` instead of "This fmsg host doesn't support search". Matching the probe's list, or matching 400 only when the error says the id is invalid, would fix it.

3. Don't make a request wait for the probe (suggestion). `searchAvailable` runs for every MCP HTTP request. When the cached answer is stale and the caller holds a token, that request waits up to 2 s for the probe, even if it's a `tools/call` for something else. Stale-while-revalidate would avoid it: return `lastKnown` straight away and start the probe without awaiting it. The next request gets the fresh answer.

4. Small things:

  • Tool list changes: when a call learns 501 mid-session, the client keeps its cached tool list, as no `notifications/tools/list_changed` is sent. That's fine given the explanatory error, but worth a comment.
  • `root` in `ID_KEYS`: it now applies to every JSON response, not just search. That's correct today, but a future numeric `root` that isn't a message id would be stringified. A comment saying so would help.
  • Query in error text: the search query only ends up in the tool's error text (`GET /fmsg/search?q=…`), which goes back to the caller and not to server logs (`safeLog` logs `error.message` only). Good, and in line with the contract's "keep `q` out of logs".

- Leave trashed messages and edits out of thread counts and latest unless
  searching the trash; the host returns them for grouping.
- Treat 400 "invalid message id" at call time as no search, like the probe.
- A stale support answer no longer makes a request wait: it stands while the
  Web API is asked again in the background.
- Comments on tools/list_changed and root in ID_KEYS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@markmnl markmnl left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at b74a1e7 against the contract that merged as markmnl/fmsg-webapi#70. One thing I'd fix before merging (inline, src/search-support.ts); the rest matches.

Verified:

  • Contract: the query mapping (q, sort, files, unread, scope=drafts, trash=only, limit, offset), the response shape, the q=-&limit=1 probe and the fmsg:read scope all match the merged README.
  • root in ID_KEYS: fmsg-webapi has no other JSON key named root (threads and indicators use root_id), so nothing else is stringified by it today.
  • Thread summaries: edits, reactions and trashed messages are left out of counts as the contract asks, and trashed ones are kept with in_trash.
  • npm run typecheck passes and npx vitest run passes (304 passed, 6 skipped).

One thing to be aware of, not a blocker: fmsg-webapi main answers 501, so every host is "no search" today. A server that has just started lists search_messages, and says so in its instructions, until the first request that already holds a Web API token gets the 501. After that the answer is shared process-wide, so only the first session or two see it. If that first impression matters, treating "no answer yet" as not listed would avoid it, at the cost of the first session on a search-capable host.

Comment thread src/search-support.ts Outdated
const timedOut = new Promise<SearchSupport>((resolve) => signal.addEventListener("abort", () => resolve("unknown"), { once: true }));
running = Promise.race([probe(signal).catch((): SearchSupport => "unknown"), timedOut])
.then((result) => {
if (result !== "unknown") this.remember(apiUrl, result === "yes");

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An "unknown" answer is never remembered, so every request asks again, and waits. While the probe can't get a definite answer (the route times out, or a proxy answers 429/502/503), known stays empty, so searchAvailable takes the last === undefined branch on every request and awaits supported() again. Over HTTP that is every MCP request, tool calls included, because the handler awaits searchAvailable before building the server.

Measured with a throwaway test against this branch:

probe result 20 sequential requests
always "unknown" 20 probes
never returns each request waits the full timeout (3 requests = 3 × timeout; 2s each by default)

So an incident on the Web API side doubles the upstream request rate from this server, and a slow /fmsg/search adds up to 2s to every call, including send_message. With rate limiting it feeds itself: 429 is "unknown", so the next request probes again.

Suggested fix: remember "unknown" too, for a short time (30 to 60 seconds), and return "listed" from that entry without probing. Something like a retryAfter timestamp per URL that searchAvailable checks before the hasToken() branch. A test that calls searchAvailable repeatedly with a probe returning "unknown" and asserts one probe would pin it.

Comment thread src/client/client.ts Outdated
await response.body?.cancel();
return "yes";
} catch (error) {
if (error instanceof FmsgHttpError && [400, 404, 405, 501].includes(error.status)) return "no";

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the probe counts any 400 as "no search", while search_messages itself only does so for 400 with invalid message id. A host that implements search but answers 400 to the probe for another reason would be remembered as unsupported for 10 minutes and the tool hidden. Using the same test in both places (the message check from src/tools/search.ts) keeps them consistent.

A probe that couldn't tell (timeout, 429, 5xx, unreachable) left nothing
remembered, so every MCP request probed again and, over HTTP, waited for
it: up to the 2 second timeout on each call while the route hung.

- After such a probe the last answer (or "listed" when there is none)
  stands for a minute before the Web API is asked again.
- The probe and the tool read a refusal the same way (searchNotImplemented):
  a 400 other than an older Web API's "invalid message id" is a search that
  refused its parameters, not a missing one.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@markmnl

markmnl commented Nov 26, 2026

Copy link
Copy Markdown
Owner Author

Pushed 2eda538 for the two points from the review.

  • A probe that can't tell now holds the next one off for a minute. During that minute the last answer stands (or the tool is listed when there is none) and no request waits. A definite answer, including a 501 at call time, ends the wait.
  • The probe and the tool read a refusal the same way (searchNotImplemented): 501, 404, 405, or the 400 invalid message id of a Web API older than search. Any other 400 is now "can't tell" for the probe instead of "no search".

Against the throwaway measurements from the review: 20 requests with a probe that can't tell now make 1 probe (was 20), and with a probe that never answers only the first request waits.

Tests added in test/search.test.ts for both, plus the last-answer-stands case. npm run typecheck, npm run build and npx vitest run pass (308 passed, 6 skipped).

@markmnl
markmnl merged commit b8c1900 into main Nov 26, 2026
4 checks passed
@markmnl
markmnl deleted the search-tool branch November 26, 2026 03:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant