Joel Stevick

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

Signing in: the SDK's OAuth client

main.ts runs the search loop from the command line against the deployed MCP server, signed in the way Claude Code signs in. Its first connection gets 401. The official MCP client SDK then reads the server's discovery documents, registers this program as a client, makes a PKCE verifier and opens the consent page in the browser through redirectToAuthorization(). The visitor signs in to their demo account and allows reading. The browser is redirected to a small HTTP server on 127.0.0.1:53112, which hands the redirect's whole query, the code and the issuer (iss), to finishAuth(). The SDK checks the issuer against the one it recorded (RFC 9207) and trades the code at the token endpoint. A new client then connects with the access token, and searchLoop() runs with the real Messages API call. Everything the SDK needs to keep, from the registration to the tokens, is kept in memory for one run.

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/main.ts121 / 121 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/main.ts The command line: the OAuth client provider, the loopback redirect, the connection and main().

Module scope

module scope · lines 1–25View on GitHub

The licence, how the program is run and signs in, its imports, the server's address and the redirect URI.

// 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.

// Runs the search loop (loop.ts) against the demo's deployed MCP server from the command line:////   ANTHROPIC_API_KEY=... npm run search -- "What does the warranty cover?"//// The server needs OAuth, so the first call is answered 401. The SDK's client then does what Claude Code does:// it reads the server's metadata documents, registers this program as a client, and sends you to the consent// page in your browser, where you sign in to your demo and allow reading. The browser comes back to a small// server on this machine (127.0.0.1) with a code, the SDK trades it for a token, and the loop starts.// Tokens are kept in memory only, so each run asks again.

How it runs, and how it signs in Never runs

WhatThe command is ANTHROPIC_API_KEY=... npm run search -- "<question>"; package.json maps npm run search to tsx examples/search-loop/main.ts. The comment gives the sign-in in order: the first call is answered 401; the SDK's client reads the server's metadata documents, registers the program as a client and sends the visitor to the consent page; the visitor signs in to their demo and allows reading; the browser comes back to a server on 127.0.0.1 with a code, which the SDK trades for a token. Tokens are kept in memory, so every run asks again.

WhyThis server requires OAuth 2.1, MCP's authorization for HTTP transports, so a host of one's own must do the same flow Claude Code does. The SDK does the protocol; the program supplies storage, a way to open the browser and a way to receive the redirect.

npm run search: tsx examples/search-loop/main.ts (package.json)

import { spawn } from 'node:child_process'import { createServer } from 'node:http'import {  Client, StreamableHTTPClientTransport, UnauthorizedError,  type OAuthClientMetadata, type OAuthClientProvider, type OAuthDiscoveryState, type StoredOAuthClientInformation, type StoredOAuthTokens,} from '@modelcontextprotocol/client'import { anthropic, searchLoop } from './loop'

Imports Module load

Whatspawn from node:child_process opens the browser; createServer from node:http receives the redirect. From the MCP client SDK: Client, StreamableHTTPClientTransport, UnauthorizedError and the types of the OAuth provider and what it stores. From loop.ts: anthropic() and searchLoop().

WhyStreamableHTTPClientTransport is the SDK's client for MCP's Streamable HTTP transport, the one a remote server such as /mcp/demo speaks. Given an authProvider, it runs the OAuth flow itself when the server answers 401.

@modelcontextprotocol/client 2.4.0 (package.json)

const SERVER = process.env.MCP_URL ?? 'https://joelstevick.com/mcp/demo'const PORT = 53112const REDIRECT = `http://127.0.0.1:${PORT}/callback`

The server, the port and the redirect URI Module load

WhatSERVER is the MCP_URL environment variable or https://joelstevick.com/mcp/demo. PORT is 53112, and REDIRECT is http://127.0.0.1:53112/callback.

WhyA program on a person's machine has no public address, so the authorization server redirects the browser to a loopback address on that machine, which RFC 8252 describes for native apps. The IP literal 127.0.0.1 is used rather than localhost, which RFC 8252 (section 8.3) advises against because a name may not resolve to the loopback interface. A fixed port keeps the example simple; if 53112 is in use, the program cannot receive the redirect.

SERVER = MCP_URL or https://joelstevick.com/mcp/demoREDIRECT = http://127.0.0.1:53112/callback

InMemoryOAuth

class · lines 26–60View on GitHub

The SDK's OAuthClientProvider: the hooks through which the SDK reads and keeps the client's registration, the PKCE verifier, the discovery state and the tokens, and opens the consent page.

Called by connect()

/** The SDK's OAuth hooks: where the client's registration, the PKCE verifier and the tokens are kept. */class InMemoryOAuth implements OAuthClientProvider {  private client?: StoredOAuthClientInformation  private saved?: StoredOAuthTokens  private verifier = ''  private discovery?: OAuthDiscoveryState

Where the sign-in's state is kept MCP host

WhatInMemoryOAuth implements the SDK's OAuthClientProvider interface with four private fields: the client information the authorization server returned at registration, the tokens, the PKCE code verifier and the discovery state.

WhyThe SDK runs the OAuth flow but stores nothing itself; it calls the provider. Fields on one object keep everything for one run of the program, so nothing is written to disk and nothing outlives the process.

  get redirectUrl() { return REDIRECT }

The redirect URI MCP host

WhatredirectUrl returns REDIRECT, http://127.0.0.1:53112/callback.

WhyThe SDK sends it as redirect_uri in the authorization request and again at the token endpoint, which checks the two match. A provider with a redirect URL tells the SDK that the flow is interactive, through a browser.

  // Read access only: the consent page offers "Remove a file" separately, and this program never asks for it.  get clientMetadata(): OAuthClientMetadata {    return {      client_name: 'Search loop example', redirect_uris: [REDIRECT], scope: 'docs:read',      grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none',    }  }

The client metadata MCP host

WhatclientMetadata is what the SDK registers: client_name 'Search loop example', redirect_uris [REDIRECT], scope 'docs:read', grant_types authorization_code and refresh_token, response_types code, and token_endpoint_auth_method 'none'. The comment says the program asks for read access only; the consent page offers removing a file (docs:write) separately.

WhyThe provider gives no client ID metadata document URL, so the SDK registers the client with this metadata by dynamic client registration (RFC 7591) at the server's /oauth/register. token_endpoint_auth_method 'none' makes it a public client with no secret: a program on a person's machine cannot keep one, and PKCE binds the code to this run instead. The SDK asks for the scope the server names in its 401 challenge (or else in its protected resource metadata), here docs:read, and uses the scope in this metadata only when the server names none. Because grant_types includes refresh_token and the authorization server lists offline_access, the SDK adds offline_access to the request; the OAuth library issues a refresh token on every code exchange in any case.

scope: docs:readtoken_endpoint_auth_method: none

  clientInformation() { return this.client }  saveClientInformation(info: StoredOAuthClientInformation) { this.client = info }  tokens() { return this.saved }  saveTokens(tokens: StoredOAuthTokens) { this.saved = tokens }  saveCodeVerifier(verifier: string) { this.verifier = verifier }  codeVerifier() { return this.verifier }

Registration, tokens and the PKCE verifier MCP host

WhatSix methods that save and return the client information, the tokens and the code verifier, each in its field.

WhyThe SDK calls saveClientInformation after registering and clientInformation before every step that needs the client ID. saveCodeVerifier is called before the browser opens, and codeVerifier when the code is traded, so the verifier must survive between the two; here they are calls on the same object in one process.

  // Which authorization server the code was asked of, so the SDK can check the one that answers is the same (RFC 9207).  saveDiscoveryState(state: OAuthDiscoveryState) { this.discovery = state }  discoveryState() { return this.discovery }

The discovery state MCP host

WhatsaveDiscoveryState and discoveryState keep the result of discovery: the authorization server and its metadata, and the protected resource metadata. The comment gives the reason: the SDK must know which authorization server the code was asked of, so it can check that the one that answers is the same (RFC 9207).

WhyThe SDK records the issuer in the discovery state before it sends the browser away. When finishAuth() receives the code, it compares the redirect's iss with that recorded issuer before it redeems the code, so a code that comes from a different authorization server, as in a mix-up attack, is refused. With the state kept, the SDK also does not repeat discovery after the redirect.

  /** Opens the consent page in the browser (and prints it, in case that fails). */  redirectToAuthorization(url: URL) {    console.log(`\nAllow access in your browser:\n${url.href}\n`)    const opener = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer' : 'xdg-open'    spawn(opener, [url.href], { stdio: 'ignore', detached: true }).on('error', () => {}).unref()  }}

Open the consent page MCP host

WhatredirectToAuthorization prints the authorization URL, then opens it with the platform's opener: open on macOS, explorer on Windows, xdg-open elsewhere. The child process is detached and unref'd, and a failure to start it is ignored.

WhyThe SDK calls this once it has registered the client and built the authorization URL with the code challenge. The URL is printed first so the visitor can open it by hand if no browser opens. Detaching the opener keeps the program free to wait for the redirect.

callbackFromBrowser()

function · lines 61–77View on GitHub

Waits for the browser to be redirected to 127.0.0.1:53112/callback and resolves to the redirect's whole query.

Called by connect()

/** Waits for the browser to come back to 127.0.0.1, and returns the redirect's whole query: the code and the issuer (`iss`). */function callbackFromBrowser(): Promise<URLSearchParams> {  return new Promise((resolve, reject) => {

What comes back MCP host

WhatcallbackFromBrowser returns a promise of URLSearchParams: the whole query of the redirect, which holds the code and the issuer, iss.

WhyThe authorization server sends iss and advertises that it does (authorization_response_iss_parameter_supported, RFC 9207), so the SDK refuses a code handed over without its iss; the whole query carries both. The program sends no state parameter, and the SDK does not check one: the PKCE verifier is what ties the code to this run.

    const server = createServer((request, response) => {      const url = new URL(request.url ?? '/', REDIRECT)      if (url.pathname !== '/callback') { response.writeHead(404).end(); return }

A one-route HTTP server MCP host

WhatInside the promise, createServer handles each request. The request's path is resolved against REDIRECT, and any path other than /callback gets 404.

WhyThe browser may ask for other paths, such as /favicon.ico, before or after the redirect; only /callback carries the authorization response.

      const code = url.searchParams.get('code')      response.writeHead(200, { 'Content-Type': 'text/plain' }).end(code ? 'Connected. You can close this tab.' : 'Access was not allowed.')      server.close()      if (code) resolve(url.searchParams)      else reject(new Error(url.searchParams.get('error') ?? 'No code came back.'))    })

Answer the browser, then settle MCP host

WhatThe handler reads code from the query and answers the browser in plain text: "Connected. You can close this tab." when there is a code, "Access was not allowed." when not. It closes the server, then resolves with the whole query, or rejects with the error parameter the authorization server sent, or "No code came back."

WhyWhen the visitor refuses consent, the authorization server redirects with error=access_denied and no code (RFC 6749, section 4.1.2.1), and the rejection ends the run with that error. The server serves one callback and closes.

    server.listen(PORT, '127.0.0.1')  })}

Listen on the loopback interface only MCP host

Whatserver.listen(PORT, '127.0.0.1') starts listening on port 53112 of the loopback interface.

WhyBound to 127.0.0.1, the server cannot be reached from another machine on the network. connect() calls this after the first connection's 401, when the browser has already opened; the visitor still has to sign in and allow access, so the server is listening by the time the redirect arrives.

connect()

async function · lines 78–97View on GitHub

Connects the SDK's client to the MCP server, going through the browser sign-in when the server asks for it.

Called by main()Calls callbackFromBrowser() InMemoryOAuth

/** Connects the SDK's client to the server, going through the browser sign-in when the server asks for it. */async function connect(): Promise<Client> {  const oauth = new InMemoryOAuth()  const client = new Client({ name: 'search-loop-example', version: '1.0.0' })  const transport = new StreamableHTTPClientTransport(new URL(SERVER), { authProvider: oauth })

The provider, the client and the transport MCP host

Whatconnect() makes one InMemoryOAuth, a Client named search-loop-example, version 1.0.0, and a StreamableHTTPClientTransport to SERVER with the provider as its authProvider.

WhyWith an authProvider, the transport adds the provider's access token to every request as a bearer token, and on a 401 it starts the OAuth flow.

  try {    await client.connect(transport)    return client  } catch (error) {    if (!(error instanceof UnauthorizedError)) throw error  }

First try MCP host

Whatclient.connect(transport) sends MCP's initialize request. With no token yet, the server answers 401; the transport discovers, registers and opens the consent page through the provider, then throws UnauthorizedError. Any other error is thrown on. If the connection succeeds, the client is returned.

WhyUnauthorizedError is how the SDK says the flow needs the browser to come back before it can go on. A connection that succeeds at once, for example to a server at MCP_URL that needs no sign-in, skips it.

  // The 401 sent the browser to the consent page; trade the code that comes back for a token, then connect again.  await transport.finishAuth(await callbackFromBrowser())  const signedIn = new Client({ name: 'search-loop-example', version: '1.0.0' })  await signedIn.connect(new StreamableHTTPClientTransport(new URL(SERVER), { authProvider: oauth }))  return signedIn}

Trade the code, then connect again MCP host

Whattransport.finishAuth() is given the query from callbackFromBrowser(). The SDK checks iss against the recorded issuer, then posts the code, the PKCE verifier and the redirect URI to the token endpoint and saves the tokens through the provider. A new Client and a new transport, with the same provider, then connect; this time the requests carry the access token, initialize succeeds, and the signed-in client is returned.

WhyPassing the whole query rather than the code alone is the SDK's preferred form: it reads code and iss itself, and on an issuer mismatch it throws without reading the rest. The new connection starts its initialize handshake from the beginning, with the same provider, so it uses the tokens just saved.

main()

async function · lines 98–117View on GitHub

Reads the question and the key, signs in, runs the loop with each step printed, and closes the connection.

Called by Entry pointCalls connect() anthropic() The loop: Claude with the server's read-only tools searchLoop() The loop: Claude with the server's read-only tools

async function main() {  const question = process.argv.slice(2).join(' ').trim()  const apiKey = process.env.ANTHROPIC_API_KEY  if (!question || !apiKey) {    console.error('Usage: ANTHROPIC_API_KEY=... npm run search -- "your question"')    process.exit(1)  }

The question and the key MCP host

WhatThe question is every command-line argument after the script, joined with spaces and trimmed. The key is ANTHROPIC_API_KEY. If either is missing, the program prints its usage and exits with code 1.

WhyThe key is read from the environment only, so it never appears in the command's arguments or in the code.

  const mcp = await connect()  try {    // Show each search as the model makes it, then the answer.    const { answer, turns } = await searchLoop(question, mcp, anthropic(apiKey), (step) => {      console.log(`→ ${step.tool} ${JSON.stringify(step.input)}${step.isError ? '  (failed)' : ''}`)    })    console.log(`\n${answer}\n\n(${turns} model calls)`)  } finally {    await mcp.close()  }}

Sign in, search, answer MCP host

Whatmain() connects, then calls searchLoop() with the question, the signed-in client, anthropic(apiKey) and an onStep that prints each tool call as → <tool> <input as JSON>, with (failed) after a failed one. It then prints the answer and the number of model calls. The connection is closed in a finally block, whether the loop succeeded or threw.

WhyPrinting each search as it happens shows the agentic part: the queries the model chose and how many it needed. Closing the client aborts its open HTTP streams, so the process can exit.

output line: → search_documents {"query":"…"}

Entry point

module scope · lines 118–121View on GitHub

Runs main() and turns any error into a message and exit code 1.

Calls main()

main().catch((error) => {  console.error(error instanceof Error ? error.message : error)  process.exit(1)})

Run, and fail with a message MCP host

Whatmain() runs when the file is executed. Any rejection prints the error's message (or the value, if it is not an Error) and exits with code 1.

WhyA refused consent, an issuer mismatch, a rate limit or a bad key each ends the run with one readable line instead of a stack trace.