Joel Stevick

MCP server · Your own host: agentic search · loop.ts · stage 2 of 2

The loop: Claude with the server's read-only tools

searchLoop() is the core of an MCP host: code that holds a connection to an MCP server and lets a model call its tools. It lists the server's tools and keeps those whose readOnlyHint annotation is true, which on the demo's server is search_documents alone. It sends Claude the question and those tools through the Messages API. When the reply stops with tool_use, it runs each requested call on the server with callTool, puts every result in a tool_result block, and sends the whole conversation back. When a reply has no tool call, its text is the answer. The model chooses each query, so it can search again with other words before it answers with the file and page of each fact.

Runs in: Your machine, the developer's machine: npm test (vitest, demo/tests/), npm run eval (Node and wrangler dev, evals/) and npm run search (Node, examples/). New to Cloudflare? How these fit together
examples/search-loop/loop.ts101 / 101 lines on this page explainedevery line of the file
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.

examples/search-loop/loop.ts The search loop: the model, the tool loop over the MCP client, and the Messages API call.

Module scope

module scope · lines 1–36View on GitHub

The licence, what the file is, the MCP SDK types it uses, the model, the turn limit, the system prompt and the types of the parts of a reply the loop reads.

// Copyright (c) 2026 Joel Stevick// SPDX-License-Identifier: MIT// Licensed under the MIT License: https://opensource.org/licenses/MIT

Licence Never runs

WhatThe copyright and the MIT licence, with an SPDX identifier.

WhyThe repository is public under MIT so the example can be copied into another project; licence scanners read the SPDX line.

// Agentic search over the demo's documents: Claude with tool use, reaching the documents only through the MCP// server's read-only tools. Claude decides what to search for, reads the passages, searches again with other// words if it needs to, and answers with the file and page of each fact. This file is the loop; main.ts connects// it to the deployed server with OAuth and runs it from the command line.

What the file is Never runs

WhatAgentic search over the demo's documents: Claude with tool use reaches the documents only through the MCP server's read-only tools, decides what to search for, searches again with other words if it needs to, and answers with the file and page of each fact. This file is the loop; main.ts connects it to the deployed server with OAuth and runs it from the command line.

WhyThe loop and the sign-in are kept apart so the loop can be reused with any connected client, and tested without a browser.

import type { CallToolResult, Client, Tool } from '@modelcontextprotocol/client'

The SDK's types Type only

WhatThree types from the official MCP client SDK, @modelcontextprotocol/client: Client, Tool and CallToolResult. It is import type, so the compiler erases it and loop.ts loads no SDK code itself.

WhyThe loop is handed a Client that is already connected, by main.ts or by the test, so it needs the SDK's types but none of its code.

@modelcontextprotocol/client 2.4.0 (package.json)

/** The model that searches and answers: the one the demo's own answers use (demo/src/models.ts, ANSWER_MODEL). */export const MODEL = 'claude-sonnet-5-5'

The model Module load

WhatMODEL is 'claude-sonnet-5-5'. The comment names its source: ANSWER_MODEL in demo/src/models.ts, the model that writes the demo page's answers.

WhyUsing the demo's own answer model makes the loop's answers comparable with the page's. The test checks that every request names MODEL.

MODEL = 'claude-sonnet-5-5'

/** At most this many model calls for one question, so a model that keeps searching is stopped. */export const MAX_TURNS = 8

The turn limit Module load

WhatMAX_TURNS is 8: the most Messages API calls the loop makes for one question.

WhyThe model decides when to stop searching. A limit in code bounds the cost and the time of one question whatever the model does.

MAX_TURNS = 8

const SYSTEM = [  "Answer the user's question from their uploaded documents only.",  'Use the tools to search them. Search again with different words when the first passages do not settle the question.',  'Then answer in a few sentences, giving the file and page for each fact.',  'If the documents do not say, say so; never answer from your own knowledge.',].join(' ')

The system prompt Module load

WhatFour sentences joined with spaces: answer from the uploaded documents only; search with the tools, and search again with different words when the first passages do not settle the question; answer in a few sentences with the file and page of each fact; if the documents do not say, say so and never answer from the model's own knowledge.

WhyThe second sentence is what makes the search agentic: the model is told to judge the passages it got and change the query. The last sentence is the refusal rule the demo's own answer follows. Unlike the page's ask, nothing here checks the answer's citations in code.

// The parts of a Messages API reply this loop reads.export interface ToolUse { type: 'tool_use'; id: string; name: string; input: Record<string, unknown> }export type Block = { type: 'text'; text: string } | ToolUse | { type: string }export interface Reply { content: Block[]; stop_reason: string | null }

The parts of a reply the loop reads Type only

WhatToolUse is a tool_use content block: id, name and input. Block is a text block, a ToolUse or a block of any other type. Reply is the content array and stop_reason of a Messages API response.

WhyThe loop types only what it reads, not the whole Messages API response, so it needs no Anthropic SDK.

/** One Messages API call. main.ts passes the real one (`anthropic`); a test passes a scripted one. */export type CallModel = (body: Record<string, unknown>) => Promise<Reply>

CallModel: one Messages API call Type only

WhatCallModel takes a request body and resolves to a Reply. main.ts passes anthropic(), the real call; the test passes a scripted function that returns fixed replies and keeps every request it was sent.

WhyPassing the model call in is what lets the test run the real loop against the real MCP server with no API key and no spend.

/** One step the loop took, for the caller to show as it happens. */export interface Step { tool: string; input: Record<string, unknown>; isError: boolean }export interface Answer { answer: string; steps: Step[]; turns: number }

Step and Answer Type only

WhatA Step is one tool call the loop made: the tool's name, its input and whether it failed. An Answer is the final text, every step, and the number of model calls made.

WhyThe caller can show each search as it happens (main.ts prints one line per step) and report how many model calls the question took.

searchLoop()

async function · lines 37–72View on GitHub

Asks one question of the documents behind a connected MCP client, letting the model call the server's read-only tools until it answers or MAX_TURNS model calls have been made.

Called by main() Signing in: the SDK's OAuth clientCalls resultText() textOf()

/** Asks `question` of the documents behind `mcp`, letting the model call the server's read-only tools. */export async function searchLoop(question: string, mcp: Client, callModel: CallModel, onStep: (step: Step) => void = () => {}): Promise<Answer> {

The signature MCP host

WhatsearchLoop takes the question, a connected MCP Client, a CallModel and an optional onStep callback, and resolves to an Answer.

WhyThe MCP connection and the model call are both parameters, so the same loop runs against the deployed server in main.ts and against the server in the Worker in the test.

  // Offer the model only the tools the server marks read-only: it may search, never remove.  const { tools } = await mcp.listTools()  const readOnly = tools.filter((tool) => tool.annotations?.readOnlyHint === true)  const allowed = new Set(readOnly.map((tool) => tool.name))

Offer only the read-only tools MCP host

Whatmcp.listTools() sends tools/list to the server. The loop keeps the tools whose annotations.readOnlyHint is exactly true, and puts their names in the set allowed. On the demo's server that is search_documents alone: ask_documents has readOnlyHint false, because it spends one of the demo's ten questions and records it, and remove_file has readOnlyHint false and destructiveHint true.

WhyThe model gets definitions only for the tools in this list, so ask_documents and remove_file are never offered to it. The MCP specification calls annotations hints, which a client should not trust from a server it does not trust; here the loop is written for its own project's server, and the server's scope check still applies. The loop reads one page of tools/list and ignores nextCursor, which is enough for a server with three tools.

search_documents: readOnlyHint trueask_documents: readOnlyHint falseremove_file: readOnlyHint false, destructiveHint trueLIMITS.asks = 10 (demo/src/app.ts)

  const messages: { role: 'user' | 'assistant'; content: unknown }[] = [{ role: 'user', content: question }]  const steps: Step[] = []

The conversation and the steps MCP host

Whatmessages starts with one user message, the question. steps collects every tool call made.

WhyThe Messages API keeps no state between calls: each call sends the whole conversation so far, so the loop keeps it and appends to it on every turn.

  for (let turn = 1; turn <= MAX_TURNS; turn++) {    const reply = await callModel({ model: MODEL, max_tokens: 2048, system: SYSTEM, tools: readOnly.map(asModelTool), messages })    messages.push({ role: 'assistant', content: reply.content })

One turn: call the model MCP host

WhatUp to MAX_TURNS times, the loop calls the model with the model id, max_tokens 2048, the system prompt, the read-only tools converted by asModelTool() and the conversation, then appends the reply's content to the conversation as an assistant message.

WhyThe reply is appended whole, tool_use blocks included, because the API requires each tool_result in the next user message to answer a tool_use block of the assistant message just before it.

max_tokens: 2048

    // No tool call: the model has answered.    const calls = reply.content.filter((block): block is ToolUse => block.type === 'tool_use')    if (reply.stop_reason !== 'tool_use' || calls.length === 0) return { answer: textOf(reply.content), steps, turns: turn }

No tool call: the answer MCP host

WhatThe loop picks out the reply's tool_use blocks. If stop_reason is not tool_use, or there are none, the model has answered: the loop returns the reply's text, the steps, and the number of the current turn as turns.

Whystop_reason is tool_use when the model stopped so that a tool could be run. Any other stop, such as end_turn or max_tokens, ends the loop with whatever text the reply holds.

    // Run each tool call on the MCP server, and hand every result back in one user message.    const results = []    for (const call of calls) {      const result: CallToolResult = allowed.has(call.name)        ? (await mcp.callTool({ name: call.name, arguments: call.input })) as CallToolResult        : { content: [{ type: 'text', text: `${call.name} is not offered to this loop.` }], isError: true }

Run each call on the MCP server, or refuse it MCP host

WhatFor each tool_use block, a tool in the allowed set is run on the server with mcp.callTool, which sends tools/call with the tool's name and the model's input as its arguments. A tool the loop did not offer is not sent to the server: the loop makes an error result itself, with the text "<name> is not offered to this loop." and isError true.

WhyA model can still name a tool it was not given, for example when a document's text asks it to. Refusing in code means the call never reaches the server. The demo's server would also refuse remove_file unless the visitor ticked Remove a file (docs:write) on the consent page; the loop's refusal does not depend on what was granted. The refusal is a result, not an exception, so the model reads it and can go on. The test has a scripted model ask for remove_file and checks that the file is still there. A protocol error from callTool, a JSON-RPC error rather than an isError result, is thrown and ends the run.

      const step = { tool: call.name, input: call.input, isError: result.isError === true }      steps.push(step)      onStep(step)      results.push({ type: 'tool_result', tool_use_id: call.id, content: resultText(result), is_error: step.isError })    }

Record the step and build its tool_result MCP host

WhatEach call becomes a Step (tool, input, isError) that is pushed to steps and passed to onStep. Its result becomes a tool_result block with the call's tool_use_id, the result as text from resultText(), and is_error.

Whytool_use_id ties each result to the call it answers, which matters when one reply asks for several tools. is_error tells the model that the content is an error message, not passages.

    messages.push({ role: 'user', content: results })  }

Send the results back, then the next turn MCP host

WhatAll the tool_result blocks of the turn go back in one user message, and the loop starts its next turn.

WhyThe API expects the results of all of one assistant message's tool calls in the single user message that follows it.

  return { answer: `Stopped after ${MAX_TURNS} model calls without an answer.`, steps, turns: MAX_TURNS }}

Stopped at the limit MCP host

WhatIf MAX_TURNS model calls end without an answer, the loop returns "Stopped after 8 model calls without an answer.", the steps, and MAX_TURNS as turns.

WhyA model that keeps searching gets no answer rather than an unbounded run. The test scripts eight tool_use replies in a row and checks this message and that exactly eight requests were sent.

asModelTool()

function · lines 73–77View on GitHub

Converts an MCP tool into a tool definition for the Messages API.

/** An MCP tool as the Messages API takes it: the same name, description and JSON Schema. */function asModelTool(tool: Tool) {  return { name: tool.name, description: tool.description ?? '', input_schema: tool.inputSchema }}

An MCP tool as a Messages API tool MCP host

WhatReturns the tool's name, its description (an empty string when it has none) and its inputSchema as input_schema.

WhyAn MCP tool's inputSchema and a Messages API tool's input_schema are both JSON Schema objects, so the definition passes through unchanged, and the model sees the server's own description and argument limits, such as query's 1 to 500 characters.

search_documents query: z.string().min(1).max(500) (demo/src/mcp.ts)

resultText()

function · lines 78–85View on GitHub

Turns a tools/call result into the text of a tool_result block.

Called by searchLoop()

/** A tool result as text for the model: each passage, and the address of each linked page. */function resultText(result: CallToolResult): string {  return result.content    .map((item) => (item.type === 'text' ? item.text : item.type === 'resource_link' ? `(${item.name}: ${item.uri})` : ''))    .filter(Boolean)    .join('\n\n')}

A tool result as text MCP host

WhatEach text item is kept as it is. Each resource_link item becomes "(<name>: <uri>)". Items of any other type are dropped. The parts are joined with blank lines.

Whysearch_documents returns, for each passage, a text item that starts with [file, page N] and a resource_link to that page's demo:// URI, so the model gets every passage with its file and page and the address of the whole page. The result's structuredContent, which holds the same passages again, is not sent. The test checks that the first tool_result carries "[warranty.pdf, page 1]".

textOf()

function · lines 86–89View on GitHub

The text of a reply.

Called by searchLoop()

function textOf(content: Block[]): string {  return content.map((block) => (block.type === 'text' ? (block as { text: string }).text : '')).join('').trim()}

The text of a reply MCP host

WhatJoins the text of every text block in the reply, in order, and trims it.

WhyA reply can hold several text blocks; the answer is all of them.

anthropic()

function · lines 90–101View on GitHub

The real CallModel: one POST to the Messages API with the caller's API key.

Called by main() Signing in: the SDK's OAuth client

/** The real Messages API call. */export function anthropic(apiKey: string): CallModel {  return async (body) => {    const response = await fetch('https://api.anthropic.com/v1/messages', {      method: 'POST',      headers: { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' },      body: JSON.stringify(body),    })

POST /v1/messages MCP host

WhatReturns a CallModel that POSTs the body as JSON to https://api.anthropic.com/v1/messages with the headers x-api-key, anthropic-version 2023-06-01 and content-type application/json.

WhyA plain fetch keeps the example free of the Anthropic SDK; the body the loop builds is already in the Messages API's format. The key comes from main.ts, which reads it from ANTHROPIC_API_KEY.

anthropic-version: 2023-06-01

    if (!response.ok) throw new Error(`Anthropic API ${response.status}: ${await response.text()}`)    return (await response.json()) as Reply  }}

An error, or the reply MCP host

WhatA response that is not 2xx throws an Error with the status and the response body. Otherwise the JSON body is returned as a Reply.

WhyA rate limit or a bad key stops the run with the API's own message, which main.ts prints before it exits.