Muhammad Fari Madyan
Hire me
MCP Server · part 3 of 6

Building a Remote MCP Server on GCP Part 3: The Search Behind the Tool — BM25 in Memory, AND then OR & Fixing more_like_this

Part three of a Building a Remote MCP Server on GCP series that opens with a quiz: 194 Markdown articles become a 4.2 MB index at build time, MiniSearch with boosts and fuzzy matching, AND then OR with matchMode, a more_like_this bug that matched series templates, the fix (same series 79.1% to 68.3%), and the ceiling of lexical similarity.

Muhammad Fari Madyan

· 15 min read

Baca dalam Bahasa Indonesia →

Opening: "Similar Articles" That Were Only Similar in Shape

After the server worked, I tried more_like_this on my article about idempotency. I expected articles about duplicate requests, outbox, webhooks, or locking. The top five were:

  1. Node.js & TypeScript Part 1: The Event Loop
  2. Node.js & TypeScript Part 4: Graceful Shutdown
  3. Node.js & TypeScript Part 10: Generics
  4. GCP for Backend Engineers Part 3: Messaging
  5. Node.js & TypeScript Part 3: Stateless Scaling

Four of five came from the same series. Not because they were about the same thing, but because they looked the same: every part of that series has a "Warm-Up Quiz: Do You Still Remember?" heading, a "Summary", a title that starts with "Node.js & TypeScript Backend Part", and a description that starts with "Part ... of a Node.js & TypeScript series that opens with a quiz". My similarity search was matching the template.

Part 2 designed the tools. This part opens what is behind them: how the index is built, how a query is ranked, and how I found, fixed and measured this bug, including what the fix could not solve.


Warm-Up Quiz: Do You Still Remember?

Answer first. All correct? Jump to the Summary. Missed one? Let's refresh the material.

Question 1. The search first requires every word to match, and falls back to "any word" when nothing matches. What must the tool tell the model in the fallback case?

  • A. Nothing, results are results
  • B. That no article matched every word, so these results are weaker
  • C. That the server is overloaded
Show the answer to question 1

B. My search returns matchMode: "any" and the text says "no article matched every word". Section 4 shows a query where this matters a lot.

Question 2. Why is the index built at build time into a JSON file, instead of reading the Markdown files when the server starts?

  • A. JSON is smaller than Markdown
  • B. The server image only needs one data file, startup does no parsing of the blog's source, and the index is tied to a specific deploy
  • C. MiniSearch cannot read Markdown
Show the answer to question 2

B. The build step cleans the Markdown, attaches series and topic data from the blog's own code, and writes data/articles.json. The server only loads it. Section 1 has the details.

Question 3. In BM25, why does a word that appears in almost every document add little to the score?

  • A. BM25 ignores words longer than 10 letters
  • B. Inverse document frequency: a word that is everywhere does not help tell documents apart
  • C. Common words are removed by the database
Show the answer to question 3

B. IDF lowers the weight of common words. But a template phrase that appears in one whole series is not common across the blog, so it still gets weight. That is exactly the more_like_this bug.

Question 4. A user searches with the Indonesian spelling idempotensi. What makes the article titled "Idempotency" still come first?

  • A. A synonym list
  • B. Fuzzy matching: for words longer than four letters, a small number of edits is allowed
  • C. Machine translation
Show the answer to question 4

B. idempotensi and idempotency are two edits apart. My search allows edits up to 20% of the word length for words longer than four letters.

Question 5. After the fix, the share of "similar" results from the same series dropped from 79.1% to 68.3%. Does that prove the results are better?

  • A. Yes, lower is always better
  • B. No, it is a proxy. The fix was accepted after reading real examples, and a stronger version with even lower numbers was rejected because its results were worse
  • C. No, the number should go up
Show the answer to question 5

B. A proxy metric points in a direction, it does not judge quality. Section 6 shows the version I rejected.


1. From 194 Markdown Files to One JSON File

The blog's articles are Markdown files in the website's repository. The series and topics live in TypeScript code (blogList, BLOG_SERIES, BLOG_TOPICS). The MCP server lives in a folder in the same repository, so a build script can import both directly:

BASH
$ npm run index
> tsx scripts/build-index.ts

wrote 194 articles (98 en, 96 id), 11 series, 4.2 MB → data/articles.json

For each article, the script:

  1. Removes navigation that is not content. Every series article starts with a "Series Navigation" block and a "Read in English" link. Those links appear in every part, so they are noise for search:
TS
export function cleanMarkdown(markdown: string): string {
  let text = markdown.replace(/\r\n/g, "\n");
  text = text.replace(/^## (Navigasi Series|Series Navigation)\n[\s\S]*?\n---\n/m, "");
  text = text.replace(/^(🇬🇧|🇮🇩) \[[^\]]*\]\([^)]*\)\s*$/gmu, "");
  text = text.replace(/^\s*---\s*\n/, "");
  return text.replace(/\n{3,}/g, "\n\n").trim();
}
  1. Keeps two versions of the body. The cleaned Markdown for get_article, and a plain-text version for search, with code blocks, link URLs, images and Markdown symbols removed.
  2. Extracts the headings (## and ###). They get their own field and their own boost.
  3. Attaches metadata from code. Series name, part number, total parts, categories and topics come from the same constants the website uses, so the MCP server and the website never disagree.

Why at build time and not at startup?

  • Startup stays simple. The server reads one JSON file (37 ms) and builds the search index (394 ms). It never touches the website's source.
  • The index matches the deploy. The data that answers a query is exactly the data that was tested before deploying.
  • No database. 4.2 MB fits in memory many times over. For 194 articles, a database would add a network hop, a bill, and nothing else.

2. Ranking: BM25 with Field Boosts

The search engine is MiniSearch, a small JavaScript library with BM25-style ranking. In one sentence, BM25 gives a document a higher score when the query's words appear in it often, when those words are rare in the rest of the collection, and when the document is not so long that every word appears in it anyway.

Where a word appears also matters. A match in the title says more than a match in paragraph twelve:

TS
this.engine = new MiniSearch({
  idField: "id",
  fields: ["title", "description", "headingsText", "text", "seriesName", "categoriesText"],
  storeFields: ["lang", "slug", "topics"],
  processTerm: (term) => {
    const value = normalize(term);
    return value.length < 2 || STOPWORDS.has(value) ? null : value;
  },
  searchOptions: {
    boost: { title: 4, headingsText: 2, description: 2, seriesName: 1.5, categoriesText: 1.5 },
    fuzzy: (term) => (term.length > 4 ? 0.2 : false),
    prefix: (term) => term.length > 2,
  },
});
SettingValueReason
title boost4A query word in the title is the strongest signal
headingsText, description boost2Written summaries of what the article covers
seriesName, categoriesText boost1.5"firestore" should prefer Firestore articles
text1The body, the largest and noisiest field
fuzzy20% edits, words over 4 lettersidempotensi finds "Idempotency". Short words stay exact so jwt does not match jit
prefixwords over 2 letterscach already finds cache and caching

Two more details matter for a bilingual blog:

  • Normalization: lowercase, and diacritics removed, so a word typed with or without an accent matches.
  • Stopwords in both languages: the, how, what in English and yang, dan, bagaimana, kenapa in Indonesian. Without them, an "any word" match would treat "kenapa" as evidence.

3. Every Word First, Then Any Word

A search engine has to choose between two failure modes:

  • AND (every word must match): precise, but a long query easily returns nothing.
  • OR (any word may match): never empty, but full of weak matches.

My search tries AND first, and falls back to OR only when AND finds nothing:

TS
let matchMode: SearchResponse["matchMode"] = "all";
let results = this.engine.search(query, { combineWith: "AND", filter });
if (results.length === 0) {
  matchMode = "any";
  results = this.engine.search(query, { combineWith: "OR", filter });
}
results = results.slice(0, MAX_RESULTS);

Results are capped at 50, and offset is capped at 50 too. Nobody needs page eleven of a blog search, and the cap keeps a confused client from paging forever.

The search flow: build-time index from Markdown, then each query tries every word first, falls back to any word with a matchMode flag, applies language, series and topic filters, and returns short hits


4. Real Queries, Real Behavior

Here is what this looks like with real queries against the index (recreated locally):

QueryModeTotalFirst result
cache stampedeall11GCP for Backend Engineers Part 6: Scale and Cost (ID)
outbox patternall10Firestore, Caching & Search Part 5: Keeping a Search Index in Sync
idempotensi (lang id)all12Node.js & TypeScript Part 12: Idempotency (ID)
kubernetes cache stampedeany50GCP for Backend Engineers Part 6 (ID)
blockchain kubernetesany13Node.js & TypeScript Part 4: Graceful Shutdown (ID)

The last row is the important one. I have never written about blockchain. No article matches both words, so the search falls back to any word, and "kubernetes" appears in the graceful shutdown article. The result is honest in a narrow sense, but it is not an answer to the question.

This is why matchMode exists. The text the model reads begins with:

TEXT
13 article(s) for "blockchain kubernetes" (no article matched every word; these match some of them):

With that line, a good model says "your blog does not seem to cover blockchain; the closest is an article that mentions Kubernetes". Without it, the same model might present a graceful shutdown article as a blockchain resource.

Speed is not a concern at this size. Measured in-process over 2,000 queries, search() takes a p50 of 0.34 ms and a p95 of 0.85 ms.


5. The more_like_this Bug

The first version of more_like_this was the obvious one: take the article's title, description and all its headings, and search with them as an OR query.

TS
const query = [source.title, source.description, ...source.headings].join(" ");

Look at what that query contains for the idempotency article:

Part of the queryExampleAbout the subject?
Title prefix"Node.js & TypeScript Backend Part 12:"No, same for 13 articles
Description lead-in"Part twelve of a Node.js & TypeScript series that opens with a quiz:"No, same pattern for the whole series
Template headings"Warm-Up Quiz: Do You Still Remember?", "Summary", "Closing & What's Next"No, shared by dozens of articles
Real headings"Why the Same Request Arrives Twice", "Payment Webhooks: Where All the Tools Meet"Yes

BM25's IDF lowers the weight of words that are common across the whole blog. But "Warm-Up Quiz" is not common across the whole blog. It is common inside a few series, and very rare elsewhere. So it gets a high weight, and every article of the same series scores high because of it.

The fix was to describe the article by its subject only:

TS
/** "2. Summary" and "Summary" count as the same heading. */
const headingKey = (heading: string): string => normalize(heading.replace(/^\d+\.\s*/, "")).trim();

// In the constructor: headings that appear in at least three articles are template, not subject.
this.templateHeadings = new Set([...headingCount].filter(([, count]) => count >= 3).map(([heading]) => heading));

subjectQuery(article: Article): string {
  const title = article.series ? article.title.slice(article.title.indexOf(":") + 1) : article.title;
  const colon = article.description.indexOf(":");
  const description =
    colon > 0 && /\b(series|seri)\b/i.test(article.description.slice(0, colon)) ? article.description.slice(colon + 1) : article.description;
  const headings = article.headings
    .filter((heading) => !this.templateHeadings.has(headingKey(heading)))
    .map((heading) => heading.replace(/^\d+\.\s*/, "").replace(/^(Opening|Pembuka|Pembukaan):\s*/i, ""));
  return [title, description, ...headings].join(" ");
}

Three rules, all derived from the data instead of a hand-written list:

  • Title: for series articles, drop everything before the first colon.
  • Description: drop the lead-in before the first colon, but only if that lead-in mentions a series.
  • Headings: drop any heading that appears in three or more articles. The threshold finds "Summary", "Warm-Up Quiz" and "Closing" without me listing them, and it keeps updating as I add series.

A regression test pins the behavior:

TS
test("more_like_this ignores template headings shared by many articles", () => {
  const article = search.get("node-ts-backend-part-12-idempotency", "en")!;
  const query = search.subjectQuery(article);
  assert.ok(!/Warm-Up Quiz|Summary|Closing/.test(query), query.slice(0, 200));
  assert.ok(!query.startsWith("Node.js & TypeScript Backend Part"), "series prefix is dropped");
  assert.match(query, /Idempotency/);
});

6. Measuring the Fix, and the Version I Rejected

I do not have a labeled golden set for "similar articles", so I used two proxies over all 194 articles, top five results each:

  • Same series: what share of results come from the same series as the source article (for articles in a series). The series navigation already links those parts, so a high share means the tool adds little.
  • Shares a topic: what share of results share at least one topic with the source. A sanity check that results did not become random.
VersionSame seriesShares a topic
Before (title + description + all headings)79.1%87.6%
Fix: subject query68.3%79.8%
Fix + search only title, description, headings62.0%74.3%

The third row has the "best" same-series number. I rejected it anyway. Restricting the search to the short fields made the ranking depend on a handful of words, and the examples got noisier. For idempotency, it ranked the Generics article first. The subject query alone ranked GCP Part 3: Messaging first, an article about Pub/Sub and redelivered messages, which is where idempotency matters most.

This is the idempotency example after the fix, with real scores:

RankArticleScore
1GCP for Backend Engineers Part 3: Messaging20,574
2Node.js & TypeScript Part 1: The Event Loop14,621
3System Design Roadmap Part 1: Networking Basics13,935
4Node.js & TypeScript Part 4: Graceful Shutdown13,704
5Node.js & TypeScript Part 10: Generics13,640
8System Design Roadmap Part 3: Patterns (idempotent APIs, outbox)12,782
10Exam Integrity: Concurrency & Optimistic Locking11,068

Better, and still not good enough. The article I would recommend most, System Design Roadmap Part 3, which covers idempotent APIs and the outbox pattern, is in eighth place. The optimistic locking article, which solves a closely related problem, is tenth. They use different words for related ideas, and lexical search only sees words.

That is the honest ceiling of BM25 for similarity. The next step would be embeddings: represent each article as a vector and compare meaning instead of words. My own semantic search evaluation showed that embeddings are not automatically better and cost real latency, so this would need its own measurement. For a "read next" list, the fix above is good enough to ship.

One cost to know about: more_like_this builds a long OR query from a whole article, so it is slower than a normal search. In-process, p50 15.5 ms and p95 23.8 ms, against 0.34 ms for search(). Still small next to the network, but forty times slower is worth knowing.


7. Three Search Traps Behind a Tool

Trap one: hiding the fallback. Falling back from AND to OR is fine. Hiding it is not. The model needs to know when results are weak, or it presents them with confidence.

Trap two: indexing the template. Navigation, quizzes, "Summary" headings and repeated lead-ins look like content to a search engine. Remove them at build time, or derive them from the data as I did with the three-article threshold.

Trap three: optimizing a proxy. The version with the lowest same-series share was the worst to read. Use numbers to find problems and compare versions, then read real examples before you ship.


Summary

  • Build time: 194 Markdown articles become data/articles.json (4.2 MB) with navigation removed, plain text for search, headings, and series and topic data from the website's own code. Startup: 37 ms to parse, 394 ms to index.
  • Ranking: BM25-style MiniSearch, boosts title 4, headings and description 2, series and categories 1.5. Fuzzy (20%, words over 4 letters), prefix (over 2 letters), diacritics removed, stopwords in English and Indonesian.
  • AND, then OR, with matchMode reported to the model. blockchain kubernetes shows why the flag matters. Results and offsets are capped at 50. search() p50 0.34 ms.
  • The more_like_this bug: the query matched series templates. The fix uses the subject only: title and description without the series lead-in, and headings that appear in fewer than three articles.
  • Measured: same-series share 79.1% → 68.3%, shared topic 87.6% → 79.8%. A version with 62.0% was rejected after reading examples. The best match for idempotency is still eighth: the ceiling of lexical similarity.

Next

A fix like this is only safe if something would catch it breaking. In Part 4, we test and observe the server: tests with a real MCP client over HTTP, the MCP Inspector, JSON logs that Cloud Logging understands, and a load test where my first benchmark measured my own rate limiter instead of the server.

ShareLinkedInXWhatsApp

Written by Muhammad Fari Madyan

Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

Work with me
← part 2Designing Tools for a Modelpart 4 →Testing and Observability

Muhammad Fari Madyan

Senior Backend Engineer building real-time, high-concurrency systems that hold up in production. Co-founder of LampungDev. Based in Bandar Lampung, Indonesia (UTC+7), working remote.

Work

Case studiesCahTixExam platform, 4 stacksOpen source

© 2026 Muhammad Fari Madyan

Designed and built by Muhammad Fari Madyan