DEV Community

Valentin
Valentin

Posted on AI-assisted

I turned a markdown knowledge base into a public MCP server on Cloudflare Pages (no vectors, no database)

I run a free reference site for foreigners in Spain: residence permits, health care, work, benefits, taxes. It has about 380 guides in Spanish, English and Ukrainian. Each guide is a markdown file, and each one is checked against an official source (the Spanish official gazette, the BOE, or a ministry page) before it goes live.

AI assistants already read the site. What I wanted was for them to get the guide as structured data, with the date we last checked it and the official source attached, instead of a scraped page with the context stripped out. So I added a small read-only MCP server to the same Cloudflare Pages project. This post covers how it works and what I would do differently.

Why no RAG

Early on I had planned a RAG layer: embeddings, a vector store, re-indexing on every change. I dropped it. The knowledge base is a folder of markdown files with rich frontmatter: topic, status, valid from/until, verified date, official source, Q&A pairs. For 380 documents, plain keyword scoring over title, slug, keywords and summary is good enough, and it is transparent: when a result is wrong, I can see why.

The rule I care about most in this domain is "don't confidently quote a rule that no longer applies". A vector store does not know that a grant closed last week. Frontmatter does: the site's list of grants open now is filtered by the same status and deadline fields.

Architecture

content/**/*.md  ──(Astro build)──►  /mcp-data/{es,en,uk}.json   (static snapshot)
                                              │
                         POST /mcp  ──►  Pages Function  ──►  core.mjs (JSON-RPC + 3 tools)
Enter fullscreen mode Exit fullscreen mode
  • Snapshot at build time. The Astro build already parses every card for the website. One more endpoint writes a per-language JSON file with only what the MCP tools need: slug, title, summary, first paragraph, up to 5 Q&A pairs, status, dates, and the domain of the official source. It is about 1.3 MB for English. No separate pipeline: every deploy refreshes it.
  • A Pages Function for /mcp. It is stateless Streamable HTTP with plain JSON responses. No sessions, no auth, no writes, no personal data.
  • The protocol and tools live in one plain ES module (core.mjs, ~370 lines), so I can unit-test it with node --test without Wrangler.

The function itself is tiny:

import { handleHttp } from '../mcp/core.mjs';

const TTL_MS = 5 * 60 * 1000;
const cache = {}; // lang -> { at, snap }

async function loadSnapshot(env, request, lang) {
  const hit = cache[lang];
  if (hit && Date.now() - hit.at < TTL_MS) return hit.snap;
  // ASSETS serves the static file directly, without another trip through Functions
  const r = await env.ASSETS.fetch(new URL(`/mcp-data/${lang}.json`, request.url));
  if (!r.ok) throw new Error(`snapshot ${lang}: HTTP ${r.status}`);
  const snap = await r.json();
  if (snap.schema !== 1) throw new Error('unexpected snapshot schema');
  cache[lang] = { at: Date.now(), snap };
  return snap;
}

export async function onRequest({ request, env }) {
  return handleHttp(request, (lang) => loadSnapshot(env, request, lang));
}
Enter fullscreen mode Exit fullscreen mode

env.ASSETS.fetch is the part I like: the snapshot is a static asset, so reading it does not count as another Function invocation, and the in-memory cache keeps hot isolates from re-parsing it on every call.

Three tools

  • search_guides(query, lang?, limit?): keyword search, closed and expired items filtered out, guides ranked above news on ties, fresher first.
  • get_guide(slug, lang?): summary, key questions, freshness, status and where to check.
  • about_guia(): what the site covers, guide counts by topic, data freshness and what is not included.

The ranking is deliberately boring:

function scoreCard(c, toks) {
  const title = fold(c.title), kw = fold((c.keywords || []).join(' ')),
        sum = fold(c.summary), ov = fold(c.overview), slug = fold(c.slug.replace(/-/g, ' '));
  let s = 0;
  for (const t of toks) {
    if (title.includes(t)) s += 3;
    if (slug.includes(t)) s += 2;
    if (kw.includes(t)) s += 2;
    if (sum.includes(t)) s += 1;
    if (ov.includes(t)) s += 1;
  }
  return s;
}
Enter fullscreen mode Exit fullscreen mode

fold lowercases and strips accents, so "tramitación" and "tramitacion" match. If the query is in Cyrillic and no language is given, the server answers in Ukrainian. Otherwise it defaults to English.

Status and freshness are part of the answer

This is the part that matters for legal-ish content:

// closed if status says so or valid_until is in the past
export function effectiveStatus(card, now) {
  if (card.status === 'closed') return 'closed';
  if (card.valid_until) {
    const until = Date.parse(`${card.valid_until}T23:59:59Z`);
    if (!Number.isNaN(until) && until < now) return 'closed';
  }
  return card.status || 'unknown';
}
Enter fullscreen mode Exit fullscreen mode
  • A guide whose valid_until has passed becomes closed at request time, even if nobody has redeployed.
  • Closed, expired and unknown items return the status only, with no content. An assistant can say "this grant closed", but it can't quote its requirements as if they still applied.
  • Every guide carries verified_at. Anything older than 120 days comes back with stale: true.

Server-level guidance goes into the MCP instructions field: it is general information, not legal advice; mention the verification date and the official source; say so when something is stale.

Keep instructions out of tool descriptions

One of my unit tests checks that tool descriptions contain no instructions to the model, only a description of what the tool does. Tool descriptions are the place where prompt injection lives in third-party servers, and I did not want mine to look like one. Behavioural guidance goes in instructions, where clients expect it and users can read it.

The other tests cover the boring HTTP edges, and they are worth having: GET returns server info, OPTIONS handles CORS preflight, notifications get 202 with no body, bodies over 64 KB are rejected, PUT gets 405, and a broken snapshot becomes a tool error instead of a crashed function.

Try it

curl -s -X POST https://guiaextranjeros.es/mcp \
  -H 'content-type: application/json' \
  -H 'accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search_guides","arguments":{"query":"digital nomad visa","limit":2}}}'
Enter fullscreen mode Exit fullscreen mode

You can also add https://guiaextranjeros.es/mcp as a remote MCP server in any client that supports Streamable HTTP. It is listed in the official MCP Registry as es.guiaextranjeros/guia. Domain ownership was proven with an HTTP file under /.well-known/, so no DNS change was needed.

What I learned

  1. Watch your middleware. A root _middleware.js in Pages runs on every request, including static assets. On the free plan, Functions have a daily invocation quota, so an MCP endpoint that gets hammered by monitoring bots can eat into the budget the rest of the site needs.
  2. Most traffic is bots, at first. Directory crawlers and uptime monitors make up most of the early calls. Don't treat MCP call counts as a KPI.
  3. Snapshot boundaries are a product decision. The server returns the summary, the first paragraph and up to five Q&A pairs, plus a link to the full guide. That is enough for an assistant to answer the common question and send the person to the full steps and documents.
  4. Versions in the registry are immutable. Bump the version in server.json and in the server info together, or you will be confused later about what is deployed.

If you are sitting on a markdown knowledge base, you probably don't need a vector database to make it useful to assistants. A build-time JSON snapshot, a 20-line function and honest metadata go a long way.

The site and the connector docs: Guía Extranjeros MCP connector.

Top comments (2)

Collapse
 
aistackguide profile image
AI Stack Guide •

The env.ASSETS.fetch detail is the one I would highlight hardest: on Pages, assets do not count against Function invocations, and most people reach for KV or R2 before testing whether the asset binding is enough. For a 1.3 MB JSON snapshot read through an in-memory cache, it clearly is.

Three things I would add, from shipping a similar read-only server:

  1. _middleware.js at the root also runs on /mcp. Your note about bots eating the quota is right, and the cheapest fix is scoping the middleware to the routes that need it (or putting it in a subfolder) so an unauthenticated public POST never touches your site-wide logic.

  2. Return the freshness as a number, not only a boolean. stale: true tells the model something is old; age_days: 137 lets it say "checked 137 days ago" and lets a client sort. Same for the score in search_guides: exposing what the keyword match scored makes "why did that rank first" answerable without redeploying.

  3. Keep the tool descriptions boring is exactly right, and worth extending to error strings. A tool error that says "try search_guides with the official name" is also injected text. Errors should say what failed (snapshot en: HTTP 404) and nothing about what to do next. That is what instructions is for.

The immutability of registry versions is the other one that bites silently: two places to bump, and the client shows the old description until someone clears the cache.

Collapse
 
guiaextranjeros profile image
Valentin •

Thanks, this is a useful list. I checked each point against the code:

  1. Right, the root _middleware.js also runs on /mcp. Today it only does host redirects and a slug lookup, so it is cheap, but it is still site logic sitting in front of an anonymous POST. Scoping it is a fair fix.
  2. We return verified_at next to stale, so the date is there, but age_days is easier for a model to quote as-is. Exposing the match score is a good idea too: right now "why did this rank first" means reading the code.
  3. Good catch on error strings. The "data unavailable" error still tells the model to try again later or open the site, and the no-match result suggests Spanish search terms. The second one is closer to a hint than an error, but the first should just say what failed and leave guidance to instructions.

Noted on registry versions as well. Thanks for taking the time.