Joel Stevick

MCP server · Tools · TOOL 2 · stage 2 of 3

ask_documents

ask_documents calls the demo page's own ask in process and asks for its server-sent-events form. That ask reserves one of the ten questions of the caller's demo account (the visitor's row in the demos table), retrieves and reranks passages, checks the answer sentence by sentence, and records the question in the questions table with via = 'mcp'. answerFrom reads the event stream to its end. answerFrom forwards each stage and each checked sentence to the client as a progress notification. It keeps the final event, and the tool returns the answer as text and as structured content, with the file and page of each source.

Runs in: Demo Worker, the private Worker behind the DEMO service binding, demo/src/. New to Cloudflare? How these fit together
demo/src/mcp.ts119 / 119 lines on this page explainedlines 172-239,302-352 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

Pinned to joelstevick-demo-rag-pipeline at 6a9c6c7.

demo/src/mcp.ts The MCP server.

Answered

type · lines 172–174View on GitHub

What answerFrom keeps from the end of the stream.

/** What the ask's stream ends with: the whole answer (or the fallback line), or the error that gave the question back. */type Answered = { answer: string; items?: string[]; sources?: { file: string; page: number }[]; found: boolean; left: number } | { error: string }

The closing event Type only

WhatEither an answer (answer, optional items, sources as file and page, found, left) or { error }.

WhyThe type follows the ask's three closing events. done and fallback both produce the first shape, with found true or false, and error produces the second. Every ask ends with exactly one of them (AskEvent in app.ts).

STAGES

constant · lines 175–177View on GitHub

The wording of each stage event as a progress message.

/** The words a client is shown while the answer is under way, one per stage of the ask. */const STAGES: Record<string, string> = { retrieving: 'Searching the documents', reranking: 'Choosing the passages', writing: 'Writing the answer' }

Stage names to words Module load

WhatMaps the ask's stage values retrieving, reranking and writing to "Searching the documents", "Choosing the passages" and "Writing the answer".

WhyThe ask yields one stage event before ASK 3–4, one before ASK 5 and one before ASK 6–7. These words are the MCP counterpart of the stage line the demo page shows.

retrieving → Searching the documentsreranking → Choosing the passageswriting → Writing the answer

answerFrom()

async function · lines 178–239View on GitHub

Reads the ask's server-sent-events stream to its end, relays progress, and returns the final event.

Called by build(): TOOL 2

/** * Reads the ask's event stream to its end and returns its last word, the same fields the route's JSON body * carries. When the client asked for progress (a progress token on the request), each stage and each checked * sentence is sent to it as a progress notification as it happens. If the client goes away (the request is * aborted), the stream is cancelled rather than left unread: the ask's pump then stops writing and runs on to * record the question, instead of stalling on a stream nobody reads. Returns null when cancelled. */

The contract Never runs

WhatThe doc comment. The function returns the same fields as the route's JSON body. When the request carried a progress token, it sends each stage and each checked sentence as a progress notification. When the request is aborted, it cancels the stream and returns null.

WhyCancelling the stream matters because the ask's pump awaits each write into a TransformStream. If nobody reads the other side, a write never completes, and the generator, which advances only as the pump writes, stalls before it records the question.

async function answerFrom(response: Response, ctx: { mcpReq: { _meta?: { progressToken?: string | number }; signal: AbortSignal; notify: (n: { method: string; params?: Record<string, unknown> }) => Promise<void> } }): Promise<Answered | null> {

Signature MCP request

WhatTakes the ask's Response and the tool handler's context. The context is typed structurally with only the three fields the function uses: mcpReq._meta.progressToken, mcpReq.signal and mcpReq.notify.

WhyThe SDK passes this context as the handler's second argument. notify sends a notification tied to this request. signal aborts when the transport of this HTTP exchange closes, which happens when the request's own signal aborts or the client cancels the response stream; Protocol's close handler then aborts every handler still running. The MCP server is stateless, one instance per POST, so a notifications/cancelled sent in a separate POST reaches another instance and aborts nothing here.

  // The client's progress token, if it wants progress updates.  const token = ctx.mcpReq._meta?.progressToken

The progress token MCP request

WhatReads progressToken from the request's _meta. The client chooses it, a string or a number.

WhyIn MCP a client asks for progress by putting a progressToken in a request's _meta, and the MCP server may then send notifications/progress carrying that token. Without a token, the function sends no notifications.

  // Read the stream ourselves, and cancel it if the client goes away.  const reader = (response.body as ReadableStream<Uint8Array>).getReader()  const cancel = () => { reader.cancel().catch(() => {}) }  if (ctx.mcpReq.signal.aborted) cancel()  ctx.mcpReq.signal.addEventListener('abort', cancel, { once: true })

Cancel the stream if the client goes MCP request

WhatGets a reader on the response body. cancel() cancels the reader and ignores any rejection. If the signal has already aborted, the function cancels at once; otherwise a one-time abort listener cancels later.

WhyCancelling the readable side makes the pump's next writer.write reject. The pump then sets open = false and runs the generator to its end without writing (ASK 8, a fallback or an error), so the question is recorded as it would be for a visitor who closed the tab. ask() keeps the pump alive with waitUntil, so the Worker does not stop it when this request ends.

  // What is needed to split the stream into events and keep its last word.  const decoder = new TextDecoder()  let buffer = ''  let progress = 0  let last: Answered | null = null

Parser state MCP request

WhatA TextDecoder, the buffer of text not yet split into events, the progress counter, and the last closing event seen.

WhyBytes arrive in arbitrary pieces. Decoding with stream: true keeps a multi-byte UTF-8 character intact when it is split across two pieces, and the buffer holds an event that is split across two reads.

  try {    for (;;) {      // Read the next piece, stopping when the stream ends.      const { done, value } = await reader.read()      if (done) break

Read until the stream ends MCP request

WhatLoops on reader.read() and leaves the loop when done is true.

Whydone comes either when the pump closes the writer after the last event, or at once after cancel(), which resolves a pending read as done.

      // Add it to the buffer, then handle every complete event in it (each ends with a blank line).      buffer += decoder.decode(value, { stream: true })      let end: number      while ((end = buffer.indexOf('\n\n')) >= 0) {        // Take one event off the front of the buffer.        const frame = buffer.slice(0, end)        buffer = buffer.slice(end + 2)

Split off complete events MCP request

WhatAppends the decoded text to the buffer. Then, while the buffer contains a blank line (\n\n), it takes everything before the blank line as one frame and keeps the rest.

WhyIn the text/event-stream format an event ends with a blank line, and ask() writes each event as "event: <type>\ndata: <json>\n\n", so this split recovers exactly the events written. An incomplete frame stays in the buffer until the next read.

        // Pull out its type and its JSON data.        const type = /^event: (.*)$/m.exec(frame)?.[1]        const data = JSON.parse(/^data: (.*)$/m.exec(frame)?.[1] ?? '{}') as Record<string, unknown>

Read the event's type and data MCP request

WhatThe type is the rest of the line that starts with "event: ". The data is the line that starts with "data: ", parsed as JSON, or {} when there is no such line.

WhyThis is not a general server-sent-events parser. It does not parse multi-line data, comments, ids or \r\n line ends, and it reads only ask()'s own output, where JSON.stringify escapes \n and \r so that each event has one data line. There is one gap. The regular expression's . and $ also treat U+2028 and U+2029 as line ends, and JSON.stringify leaves those characters raw. If a passage contains one (the done event carries verbatim PDF text), the data line is cut short, JSON.parse throws, and the tool reports the answer as cancelled although the question was spent and recorded.

        // A final answer, a fallback or an error is kept as the last word; stages and sentences become progress updates.        if (type === 'done') last = { answer: String(data.answer ?? ''), items: data.items as string[] | undefined, sources: data.sources as { file: string; page: number }[], found: true, left: Number(data.left ?? 0) }        else if (type === 'fallback') last = { answer: String(data.answer ?? ''), sources: [], found: false, left: Number(data.left ?? 0) }        else if (type === 'error') last = { error: String(data.error ?? 'The demo could not answer that right now.') }

Keep the closing event MCP request

WhatA done event becomes an answer with found: true (answer, items, sources, left). A fallback event becomes an answer with found: false and no sources. An error event becomes { error }, with a default message if the event has none.

WhyThe stopped event, which the ask sends when a later sentence fails its check, matches none of these branches and is ignored. An answer that stopped partway is therefore returned as found, with the sentences that passed and without the page's stop line. The done event's sources also carry each passage's id and text, and the tool uses only file and page.

        else if (token !== undefined && (type === 'stage' || type === 'unit')) {          const message = type === 'stage' ? STAGES[String(data.stage)] ?? String(data.stage) : String(data.text)          await ctx.mcpReq.notify({ method: 'notifications/progress', params: { progressToken: token, progress: ++progress, message } }).catch(() => {})        }      }

Relay stages and sentences as progress MCP request

WhatIf the client sent a token, each stage event and each unit event (one checked sentence or list item) becomes a notifications/progress notification. The notification carries the token, a progress value that rises by 1 each time, and a message, which is the stage's words or the sentence. A failed notification is ignored.

WhyThe specification requires progress to increase with each notification. total is optional and omitted, because the number of sentences in the answer is not known in advance. On the 2026-07-28 revision, with the SDK's default response mode, the first notification turns this POST's HTTP response into a server-sent-events stream. On the 2025 revisions, which use the SDK's legacy stateless path, the response is an event stream from the start. In both cases the tool result follows as the last event, so the client sees each checked sentence while the model is still writing.

progress: 1, 2, 3, … (no total)

    }  } catch {    // A failed read or an unparsable frame counts as cancelled (a cancelled read ends the loop without throwing).    return null  } finally {    ctx.mcpReq.signal.removeEventListener('abort', cancel)  }

A failed read, and cleanup MCP request

WhatAny exception in the loop, from a failed read or from JSON that does not parse, returns null. The finally block removes the abort listener in every case.

Whynull is the tool's "cancelled" outcome. As the comment says, a cancelled read does not throw, because cancel() resolves the pending read as done. This catch therefore catches only a failed read or a frame whose JSON does not parse. Removing the listener keeps a late abort from cancelling a reader that has already finished.

  // Nothing to return if the client left.  return ctx.mcpReq.signal.aborted ? null : last}

Nothing if the client left MCP request

WhatReturns null if the request was aborted, and otherwise the closing event it kept.

WhyAfter cancel() the loop ends normally on done, so the function checks the signal here. Once the signal has aborted, the SDK drops whatever the handler returns, and the client that left receives nothing. If a stream ended with no closing event, last is still null and the tool reports the answer as cancelled.

build(): TOOL 2

segment · lines 302–352View on GitHub

Registers ask_documents on the McpServer built for each request, and implements it.

Calls answerFrom() ask(): ASK 1–2, then JSON or server-sent events Worker router asText() Answer with sources clean() Files and pages failed() search_documents

  // TOOL 2 · ask: the whole pipeline, the same function the demo page's question runs.  server.registerTool('ask_documents', {

Register the tool MCP request

Whatserver.registerTool registers the tool under the name ask_documents.

WhyThe tool calls the same ask() as the demo page, so an answer an MCP host gets has passed the same check as an answer on the page.

    title: 'Ask your documents',    description: `Answers a question from the uploaded PDFs, every sentence checked against them, with the file and page of each source; says so when the documents do not hold the answer. Spends one of the demo's ${LIMITS.asks} questions.`,

Title and description MCP request

WhatThe description tells the model that every sentence of the answer is checked against the documents, that each source comes with its file and page, that the tool says so when the documents lack the answer, and that each call spends one of the account's LIMITS.asks (10) questions.

WhyThe description states the cost so that the model prefers search_documents for reading and calls ask_documents only when it needs an answer.

LIMITS.asks = 10

    inputSchema: { question: z.string().min(1).max(500).describe('The question, in plain words.') },

The input schema MCP request

WhatOne argument, question, a string of 1–500 characters.

Why500 equals the ask's MAX_QUESTION, so the SDK's validation refuses a question that is too long, as an isError result, before the route sees it.

question: 1–500 characters (MAX_QUESTION = 500)

    outputSchema: {      answer: z.string(),      found: z.boolean(),      sources: z.array(z.object({ file: z.string(), page: z.number() })),      left: z.number(),    },

The output schema MCP request

WhatstructuredContent has answer (a string), found (a boolean), sources (objects with file and page) and left (the questions remaining).

Whyfound lets a program tell an answer from the "couldn't find that" fallback without matching text, and left lets it see the allowance running out.

    annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },  }, async ({ question }, ctx) => {

Annotations, and the handler MCP request

WhatreadOnlyHint: false, destructiveHint: false, openWorldHint: false. The handler takes the question and the SDK's request context, ctx.

WhyThe tool is not read-only, because each call spends a question and writes a row in questions. It is not destructive, because it only adds data. idempotentHint keeps its default, false, since a repeated call spends another question. answerFrom needs ctx for progress and cancellation.

    // No point asking an empty demo.    if (demo.files === 0) return failed('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

WhatIf the account's file count is 0, the tool returns an isError result asking for an upload.

WhyThe check runs before ask(), so no question is reserved for an account with nothing to answer from. It reads demo.files, the counter on the demos row that serveMcp loaded for this request, so it needs no extra query.

    // The page's own route, called in process, in its streamed form: the reservation, the retrieval, the check    // and the record are its. The stream is what lets a long answer report its progress (below), and its pump    // runs under waitUntil, so the question is recorded even if this request is abandoned partway.    const response = await ask(new Request('https://demo/api/ask', {      method: 'POST',      headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream', 'X-Demo-Keep': keep, 'X-Demo-Via': 'mcp' },      body: JSON.stringify({ question }),    }), env, run.models, demo, run.options, run.ctx)

Call the page's ask, in process MCP request

WhatBuilds a POST Request with the question as JSON and the headers Accept: text/event-stream, X-Demo-Keep and X-Demo-Via: mcp, and calls ask() directly with the request's models, options and execution context. X-Demo-Keep is the site's consent flag, copied from the MCP request. The URL is a placeholder, because ask() reads only the body and the headers.

WhyAccept selects the streamed form of the ask, which is what makes progress notifications possible. X-Demo-Via makes the recorded row say via = 'mcp', and X-Demo-Keep decides whether the question outlives the 10-day purge. Passing run.ctx lets ask() keep its pump running with waitUntil.

An ask_documents call from Claude Code, and its result The tool call Claude Code made (tools/call, with the tool name and its arguments) and the structured result it received, both from Claude Code's own transcript of the session. The model requests behind the call are the demo page's own. ask_documents posts the question to the same ask route, in process, with Accept: text/event-stream, so it spends one of the demo account's questions, and the rerank and answer requests are built exactly as in The ask. The header X-Demo-Via: mcp only marks the recorded question as the MCP server's. The response is what differs. When the client sent a progress token, the stage and unit events (a unit is one checked sentence or list line released to the visitor) become progress notifications. The last event becomes this result: the answer as plain text, found, the questions left, and each source cut to its file and first page. The result drops the passage and the last page of a widened source, which is why the result's source reads page 1 although the rule it cites is on page 3 of that passage. Captured 2026-11-29 from Claude Code 2.1.332 against https://joelstevick.com/mcp/demo, with the sample observatory-handbook.pdf, claude-sonnet-5-5 (the answer, on the live demo app), at 84ebd1f.

The call: tools/call params

{
  "name": "ask_documents",
  "arguments": {
    "question": "What must happen after a closure for humidity before the dome is opened again?"
  }
}

The result: structuredContent

{
  "answer": "After a closure for humidity, wait 30 minutes with the humidity below 80 percent before opening the dome again.",
  "found": true,
  "sources": [
    {
      "file": "observatory-handbook.pdf",
      "page": 1
    }
  ],
  "left": 3
}
    if (!(response.headers.get('Content-Type') ?? '').startsWith('text/event-stream')) {      // Refused before anything was streamed (no question left; the schema already caps the length): the route's own words.      const refused = (await response.json().catch(() => ({}))) as { error?: string }      return failed(refused.error ?? 'The demo could not answer that right now.')    }

Refused before streaming MCP request

WhatIf the response is not text/event-stream, the ask refused the question at ASK 1 or ASK 2 with a JSON body, and the tool returns its error text as an isError result. If ask() throws instead, for example because D1 fails at the ASK 2 reservation, the exception leaves the handler, and the SDK's tools/call wrapper returns its message as an isError result.

Whyask() answers a validation failure and the question limit ("You've used your ten questions.") as JSON before it opens a stream. As the comment says, a question that is too long cannot reach it, because the input schema already caps the question at 500. What can reach ASK 1 is a question of only whitespace, which passes min(1) but trims to empty.

    // Read the stream to its end, sending progress along the way.    const body = await answerFrom(response, ctx)

Read the stream MCP request

WhatanswerFrom reads the stream to its end, relays progress, and returns the closing event or null.

WhyThe handler waits until the ask has finished, so the tool result holds the complete answer.

    // Report a cancelled answer or an error as a failure.    if (body === null) return failed('The answer was cancelled.')    if ('error' in body) return failed(body.error)

Cancelled or failed MCP request

Whatnull becomes the isError result "The answer was cancelled.", and an error event becomes an isError result with the event's text.

WhyThe client receives "The answer was cancelled." only after a failed read or parse, or a stream with no closing event, because after an abort the SDK sends no result. An error event comes either from the model failing before any sentence was shown, in which case the question is given back, or from an exception in the generator. A fallback is not an error. "Couldn't find that" is a valid answer and comes back as a normal result with found: false.

    // Turn the answer into plain text and clean the source file names.    const answer = asText(body.answer, body.items ?? [])    const sources = (body.sources ?? []).map((source) => ({ file: clean(source.file), page: source.page }))

One text, cleaned sources MCP request

WhatasText joins the prose and any list items, one "- " line each, into one text. Each source is reduced to its cleaned file name and its page.

WhyFor a found answer, asText gives the same text that the questions.answer column records. The uploader chose the file names, so they are cleaned before a model reads them. The tool does not return the passage text; search_documents returns passages with their page URIs.

    return {      content: [        { type: 'text' as const, text: answer },        ...(sources.length > 0 ? [{ type: 'text' as const, text: `Sources: ${sources.map((s) => `${s.file}, page ${s.page}`).join('; ')}` }] : []),      ],      structuredContent: { answer, found: body.found, sources, left: body.left },    }  })

The result MCP request

WhatThe content is the answer as text, followed, when there are sources, by a text item "Sources: file, page N; …". structuredContent carries answer, found, sources and left, and the SDK validates it against the output schema.

WhyThe model reads the text items. The structured form gives a program the same answer without parsing.

Claude Code asked to use ask_documents: "Called my-docs", the answer "After a closure for humidity, wait 30 minutes with the humidity below 80 percent before opening the dome again.", the source observatory-handbook.pdf, page 1, and that 3 questions are left.
An ask_documents call. The MCP server runs the demo page's own ask route, returns its checked answer and sources as the tool's result, and spends one of the visitor's demo account's ten questions. Each source carries only its first page. The cited passage was widened across pages 1 to 3, and the rule it states is on page 3. 2026-11-29, Terminal on macOS, Claude Code 2.1.332, against the live MCP server, which is newer than the pinned commit