search_documents runs the pipeline's own retrieval (ASK 3–4, BM25 and vector search fused by reciprocal rank) on a query and returns the top passages with their file and page. It does no reranking and writes no answer. A search spends none of the ten questions of the caller's demo account (the visitor's row in the demos table). Results come one page at a time. The MCP server stores nothing between calls; a cursor tied to the account and the query tells the next call where to start.
demo/src/mcp.ts82 / 82 lines on this page explainedlines 34-36,148-171,247-301 of 516; the rest are on other stage pages
In the browser
runs in the visitor's browser, on the demo page
Ingestion
runs when a PDF's text is uploaded
Query time
runs when the Worker answers a question or a search_documents call from the MCP server, and in the request handling every route shares, in the Worker and in the site's functions, which uploads and removals pass through too
MCP request
runs on a request to the MCP server or its OAuth endpoints
Site request
runs on a site request that is not a question, an upload, an MCP call or the cron: a page load, a session read, the demo page's /api/grants calls, an admin read, a file's removal
Scheduled
runs in the Worker's daily cron job
Eval run
runs when the eval harness runs on a developer's machine
MCP host
runs in an MCP host outside the Worker: the search loop example, on a developer's machine (npm run search) or in its test
Module load
runs once, when the module is loaded
Type only
erased by the TypeScript compiler; never runs
Never runs
a comment, a licence or markup with no behaviour of its own
The most passages one search call returns, and how many it returns when the caller names no limit.
/** The most passages one search call returns, and how many it returns when the caller names no limit. */exportconstMAX_PASSAGES = 10exportconstDEFAULT_PASSAGES = 5
Passages per call Module load
WhatMAX_PASSAGES (10) is the input schema's maximum for limit, and DEFAULT_PASSAGES (5) applies when limit is omitted. The limit parameter's description quotes both numbers, so the model reads the real values.
Whyretrieval() returns up to 48 chunks (POOL), far more than a model needs in one tool result. A page of 5 keeps the result small, and the cursor reaches the rest, so at most five calls of 10 cover the whole pool.
MAX_PASSAGES = 10DEFAULT_PASSAGES = 5pool: at most 48 (POOL in app.ts)
/** A tool's answer when it could not do what was asked, in a sentence the model can act on. */constfailed = (text: string) => ({ content: [{ type: 'text'asconst, text }], isError: true })
A tool execution error MCP request
WhatReturns a CallToolResult with one text item and isError: true. Every tool returns it for an expected refusal, such as an account with no files, a spent allowance or an unknown file.
WhyThe MCP tools specification separates protocol errors, which are JSON-RPC errors for a malformed request, from tool execution errors, which are normal results with isError set. A host puts a tool execution error in front of the model so that the model can correct itself or tell the user. The SDK skips output-schema validation when isError is true, so these results need no structuredContent.
/** A search cursor: where the next page starts, tied to the demo and the query it came from. */asyncfunctioncursorFor(demo: Demo, query: string, offset: number): Promise<string> {returnbtoa(JSON.stringify({ o: offset, t: (awaitsha256(`${demo.id}\n${query}`)).slice(0, 16) }))}
An offset with a tag MCP request
WhatThe cursor is the base64 encoding of the JSON { o: offset, t: tag }. The tag is the first 16 hex characters of the SHA-256 of the account's id, a line break and the exact query string.
WhyThe MCP server stores nothing between calls. The next call runs retrieval again and skips to offset o. The tag binds the cursor to one account and one query, so the cursor is useless with any other account or query. The tag is not a secret. A forged cursor can only choose an offset into the caller's own ranking, so the cursor needs no HMAC. The MCP specification defines opaque cursors only for its list methods (tools/list, resources/list and the others), and this tool copies that pattern in its own cursor argument and nextCursor field.
cursor = base64(JSON { o, t })t = sha256(demo.id + "\n" + query), first 16 hex characters
/** The offset a cursor names, or an invalid-params error (inside the tool, the SDK returns it as an isError result). */asyncfunctionoffsetOf(demo: Demo, query: string, cursor: string | undefined): Promise<number> {
Signature MCP request
WhatTakes the account's row (demo), the query and the optional cursor from the tool's arguments, and resolves to a non-negative integer offset into the ranked passages.
WhyThe tool calls offsetOf before it counts the daily allowance (line 268), so a bad cursor costs no search.
// Decode the cursor if it can be decoded.letparsed: { o?: unknown; t?: unknown } = {}try { parsed = JSON.parse(atob(cursor)) astypeof parsed } catch { /* not ours: refused below */ }
Decode, tolerating invalid input MCP request
WhatRuns atob and then JSON.parse. If either throws, parsed stays an empty object.
WhyA string that is not base64 or not JSON is not rejected at this point. The empty object fails the check below, so every bad cursor takes the same path and gets the same message.
// It must hold a valid offset and the tag for this demo and query.const tag = (awaitsha256(`${demo.id}\n${query}`)).slice(0, 16)if (!Number.isInteger(parsed.o) || (parsed.oasnumber) < 0 || parsed.t !== tag) thrownewProtocolError(ProtocolErrorCode.InvalidParams, 'That cursor is not from this search.')
Check the offset and the tag MCP request
WhatRecomputes the tag from this account and this query. If o is not a non-negative integer, or t does not match the tag, the function throws a ProtocolError with code InvalidParams and the message "That cursor is not from this search.".
WhyThe SDK's tools/call handler catches an exception thrown inside a tool handler and returns it as an isError result whose text is the message. The model therefore sees the sentence instead of a JSON-RPC -32602 error. A change of one character in the query invalidates the cursor.
// TOOL 1 · search: the pipeline's own retrieval, with no model answer. server.registerTool('search_documents', {
Register the tool MCP request
Whatserver.registerTool registers the tool under the name search_documents.
Whybuild() runs for every MCP request, so the tool is registered again each time, on a new server for the caller's demo account. The handler closes over env, run and demo, which is why a search can reach only the account the token names.
The same idea, explained in general terms: What an MCP tool is: name, description, input schema From MCP deep dive, Ep 1: MCP Explained: Interview Questions and Answers (Model Context Protocol Deep Dive)
title: 'Search your documents',description: 'Finds the passages of the uploaded PDFs that best match a query, by meaning and by keyword. Returns each passage with its file and page. Use it to read what the documents say; it writes no answer and spends no question.',
Title and description MCP request
WhatThe host's UI displays the title. The model reads the description in tools/list when it decides whether to call the tool, and the description says that the tool returns passages with file and page, writes no answer and spends no question.
WhySaying that the tool spends no question steers the model to search_documents for reading, and to ask_documents only when it wants an answer.
The same idea, explained in general terms: A tool definition written for a model, and read-only or destructive From MCP deep dive, Ep 1: MCP Explained: Interview Questions and Answers (Model Context Protocol Deep Dive)
inputSchema: {query: z.string().min(1).max(500).describe('What to look for, in plain words.'),limit: z.number().int().min(1).max(MAX_PASSAGES).optional().describe(`How many passages to return (default ${DEFAULT_PASSAGES}, at most ${MAX_PASSAGES}).`),cursor: z.string().optional().describe('The nextCursor of an earlier call with the same query, for the passages after it.'), },
The input schema MCP request
WhatA Zod raw shape. query is a string of 1–500 characters, limit an optional integer from 1 to 10, and cursor an optional string. The SDK wraps the shape in z.object, publishes it as JSON Schema in tools/list (each describe() text becomes a property description), and validates every call's arguments against it before the handler runs.
WhyArguments that fail validation never reach the handler. The SDK returns an isError result that begins "Input validation error". The 500-character cap matches the ask's own MAX_QUESTION.
query: 1–500 characterslimit: optional integer 1–10 (the handler uses 5 when omitted)cursor: optional string
WhatDeclares the shape of structuredContent: passages, an array of { file, page, text, uri }, and an optional nextCursor. The SDK lists it as the tool's outputSchema and validates the structuredContent of every result that is not an error against it.
WhyStructured content lets a client or a program read the passages as JSON without parsing text. If a handler returned a shape that did not match, the SDK would replace the result with an output validation error before sending it.
WhatreadOnlyHint: true says the tool changes nothing in the user's environment. openWorldHint: false says it works on a closed set of data, the account's documents. The handler receives the validated query, limit and cursor.
WhyAnnotations are hints. A host may use them, for example to call a read-only tool without asking the user first, and the specification says a client must not trust them from an untrusted server. openWorldHint defaults to true, so the tool sets it explicitly. The mcp_hits counter that the handler writes is bookkeeping and does not change the documents.
// No point searching an empty demo.const files = awaitfilesOf(env, demo)if (files.length === 0) returnfailed('There are no documents in this demo yet. Upload a PDF at https://joelstevick.com/demo first.')
Refuse an account with no files MCP request
WhatfilesOf reads the account's files. If there are none, the tool returns an isError result telling the user to upload a PDF on the demo page.
WhyThe check runs before the cursor and the allowance, so a search of an account with no files costs nothing. The handler also needs the file list later, to map each passage to its file id.
// Work out where to start, then check the daily search allowance.const offset = awaitoffsetOf(demo, query, cursor)if (!(awaithit(env, `search:${demo.id}`, day(), SEARCHES_PER_DAY))) returnfailed(`This demo has made its ${SEARCHES_PER_DAY} searches for today. Try again tomorrow.`)
Cursor, then the daily allowance MCP request
WhatoffsetOf resolves the cursor or throws. hit then counts one use of the key search:<demo id> in today's UTC slot in mcp_hits, and past 100 the tool returns an isError result.
WhyEvery search embeds the query on Workers AI and reads all of the account's chunks from D1, so searches are capped per account per day. This cap is separate from the per-minute limit that serveMcp has already applied. A request for a later page runs a full search, so it counts too.
// Run the retrieval and match each passage back to its file.const { retrieved } = awaitretrieval(query, env, run.models, demo)const byName = newMap(files.map((file) => [file.name, file]))
The pipeline's retrieval MCP request
WhatCalls retrieval() from app.ts, the same function the ask runs at ASK 3–4. It scores every chunk from D1 with BM25, takes the query's nearest vectors in this account's Vectorize namespace (the account's own partition of the vector index, named by the account's id), and fuses the two rankings by reciprocal rank into at most 48 chunks. byName maps each file name to its files row.
WhyThe tool returns the pipeline's own ranking without the Claude rerank of ASK 5 and without writing an answer, so it spends no question and makes no Claude call. If vector search fails, retrieval() falls back to BM25 alone, as it does for the ask. Chunks carry a file name and no file id, which is why byName is needed.
// Passages in rank order from the cursor, until the limit or the size cap; the first always fits.for (const chunk of retrieved.slice(offset)) {const file = byName.get(chunk.file)if (passages.length >= (limit ?? DEFAULT_PASSAGES) || (passages.length > 0 && chars + chunk.text.length > MAX_RESULT_CHARS)) break next++if (file === undefined) continue passages.push({ file: clean(file.name), page: chunk.page, text: chunk.text.slice(0, MAX_RESULT_CHARS), uri: pageUri(file, chunk.page) }) chars += chunk.text.length }
Cut a page from the ranking MCP request
WhatThe loop walks the ranking from the offset. Each chunk first meets the stop test: the limit is reached, or the next passage would take the total past MAX_RESULT_CHARS, a test that never stops the first passage. A chunk that passes the test advances next, and if its file is not in byName it is then skipped. Each passage gets its cleaned file name, its page, its text cut to 20,000 characters and its page's resource URI.
WhyA chunk missing from byName belongs to a file uploaded between the file query (line 263) and retrieval's chunk read. upload() inserts the files row before the chunks, so new chunks can be ranked while the earlier file list lacks their file. A removal cannot cause this, because remove() deletes the chunks and the files row in one D1 batch. Skipping such a chunk keeps every passage linked to a resource. With CHUNK_CHARS = 900 and at most 10 passages, one result holds at most about 9,000 characters, so the 20,000 cap is a guard that bounds the result whatever the chunker produces. The file name is cleaned because the uploader chose it.
// A cursor for the next call, if there are more passages.const nextCursor = next < retrieved.length ? awaitcursorFor(demo, query, next) : undefined
The next cursor MCP request
WhatIf next is short of the end of the ranking, the tool issues a cursor for next. Otherwise there is none.
WhyThe next call runs retrieval again. If the documents change in between, or vector search fails on one call and not on the other, the ranking differs, and a page can repeat or miss a passage. The design accepts that so that the MCP server keeps no state.
The same idea, explained in general terms: Paging a large tool result with a cursor From MCP deep dive, Ep 1: MCP Explained: Interview Questions and Answers (Model Context Protocol Deep Dive)
return {// Each passage is its own item, labelled with where it is from, then a link to its whole page.content: passages.length === 0 ? [{ type: 'text'asconst, text: 'No more passages match that query.' }] : passages.flatMap((p) => [ { type: 'text'asconst, text: `[${p.file}, page ${p.page}]\n${p.text}` }, { type: 'resource_link'asconst, uri: p.uri, name: `${p.file}, page ${p.page}`, mimeType: 'text/plain' }, ]),
Unstructured content MCP request
WhatEach passage becomes two content items: a text item headed [file, page N] with the passage below it, and a resource_link to that page's demo:// URI, with a name and mimeType text/plain. With no passages, one text item says that no more passages match.
WhyMost hosts put the text items in front of the model. The resource_link, a content type since the 2025-06-18 revision, lets the client read the whole page through resources/read. clean() keeps the header on one line, so a file name cannot start a line of its own that reads like an instruction.
A search_documents call from Claude Code. The tool returns ranked passages, each with its file and page, and writes no answer. Claude Code summarises the passages itself. 2026-11-29, Terminal on macOS, Claude Code 2.1.332, against the live MCP server, which is newer than the pinned commit
WhatstructuredContent carries the same passages as JSON, with nextCursor only when there is one. The SDK checks it against the output schema before sending it.
WhyThe text form is for the model and the JSON form for code. The cursor appears only in structuredContent, so a host that gives the model only the content items never shows it the cursor. The specification recommends also returning the serialized JSON in a text item for such hosts, and this tool does not do that.