build(): TOOL 3
segment · lines 353–375View on GitHubRegisters remove_file, with its scope challenge, on the McpServer built for each request, and implements it.
Calls clean() Files and pages failed() search_documents filesOf() Files and pages remove() Removing a file
// TOOL 3 · remove: the one write. The SDK answers a token without the scope with the step-up challenge. server.registerTool('remove_file', {Register the only write MCP request
Whatserver.registerTool registers the tool under the name remove_file. The comment says that the SDK answers a token that lacks the scope, so this code does not have to.
WhyEvery other tool and resource needs only docs:read, which every grant includes. Deleting a document is the one operation the visitor must tick separately on the consent page.
title: 'Remove a file', description: 'Removes one uploaded PDF from the demo, with its text and its place in the search index. It cannot be undone. Needs the "Remove a file" permission: without it the person is asked to allow it.', inputSchema: { file: z.string().min(1).max(200).describe("The file's name, as search_documents or the resource list gives it.") },Title, description and input MCP request
WhatThe description says that the removal deletes the file's text and its search-index entries, cannot be undone, and needs the "Remove a file" permission, which the person is asked to allow if it is missing if it is missing. The input is file, the name as search_documents or the resource list gives it, 1–200 characters.
WhyTelling the model the removal is irreversible lets it confirm with the user before it calls the tool. The 200-character cap matches the cap upload() puts on a file name. On the consent page the checkbox for docs:write reads "Remove a file from your demo" (oauth.ts).
file: 1–200 characters
outputSchema: { removed: z.string() }, annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },Output schema and annotations MCP request
WhatstructuredContent is { removed: string }. The annotations are readOnlyHint: false, destructiveHint: true, idempotentHint: true and openWorldHint: false.
WhydestructiveHint: true tells a host that the call deletes data, and hosts typically ask for the user's approval before such a call. idempotentHint: true holds when no other file has the same cleaned name, because a second call then finds nothing and returns an isError result. If another file does have that cleaned name, the second call removes that file.
scopeChallenge: requireScopes(READ, WRITE),The scope challenge MCP request
WhatrequireScopes(READ, WRITE) returns a resolver that the SDK runs on every tools/call for this tool before dispatching it. If the verified token (authInfo, which serveMcp passes in) lacks docs:read or docs:write, the SDK answers the HTTP request itself with 403 and WWW-Authenticate: Bearer error="insufficient_scope", scope="docs:read docs:write", and resource_metadata set to the protected resource metadata URL.
WhyThis is the scope challenge of the MCP authorization specification. The client reads the required scopes from the header and runs the authorization flow again, asking for them. The consent page always shows the docs:write box unticked, and the new token carries docs:write only if the visitor ticks it; otherwise the token is read-only again. The handler never sees a call without the scope, so the MCP server has no scope check of its own to get wrong. The tool still appears in tools/list for a read-only token, so the model can call it and trigger the step-up.
scopes required: docs:read docs:writestatus: 403 insufficient_scope
Lines 360 on GitHubMCP specification: scope challenge handlingRFC 6750 §3.1: insufficient_scope
}, async ({ file }) => { // Find the file by its cleaned name or its exact name. const wanted = clean(file) const found = (await filesOf(env, demo)).find((row) => clean(row.name) === wanted || row.name === file) if (found === undefined) return failed(`${wanted} is not in this demo.`)Find the file MCP request
WhatThe handler cleans the given name and picks, by rowid, the first file of the caller's demo account (their row in the demos table) whose cleaned name equals it. The second test, a stored name exactly equal to the input, never adds a match, because equal names have equal cleaned forms and the first test has already matched. With no match, an isError result says the cleaned name is not among this account's files.
WhyThe MCP server shows only cleaned names, so a model passes a cleaned name back. Comparing cleaned forms makes that work for a stored name that has control characters or is over 120 characters long. The cost is that stored names that differ only in spacing or control characters clean to the same text (upload() only trims a name and cuts it to 200 characters), and the earlier file wins even when the input names the later one exactly. The search covers only this account's files, so no input can reach another visitor's documents.
// The page's own Remove, called in process. const response = await remove(new Request('https://demo/api/files', { method: 'DELETE', body: JSON.stringify({ name: found.name }) }), env, run.models, demo)The page's own remove, in process MCP request
WhatCalls remove() from app.ts with a DELETE Request whose body names the file by its stored name, which can differ from the cleaned name.
Whyremove() first deletes the file's vectors from Vectorize, 500 ids a call. A failure there leaves every D1 row in place; vectors deleted by earlier calls may already be gone, and a retry deletes the rest. Then one D1 batch deletes the file's chunks, archived pages and files row, and returns one file, the file's pages and its characters to the account's allowance. The batch gives them back only while the files row still exists, so two concurrent removes give them back once. Because MCP and the page call the same function, they cannot drift apart in what a removal deletes.
// Tell the model if the removal failed. if (!response.ok) return failed(`${wanted} could not be removed. Please try again.`)A failed removal MCP request
WhatIf remove() did not answer with a 2xx status, an isError result asks the model to try again.
Whyremove() answers 500 when a vector deletion fails, before it touches any D1 row, and 404 when the file was removed in the meantime, by the page for example. In both cases no D1 row has changed, so a retry is safe. An exception from the D1 batch is thrown, and the SDK turns it into an isError result with the exception's message.
return { content: [{ type: 'text' as const, text: `Removed ${wanted}.` }], structuredContent: { removed: wanted } } })Report the removal MCP request
WhatReturns the text "Removed <name>." and structuredContent { removed: <name> }, both with the cleaned name.
WhyThe model has seen the cleaned name elsewhere, and the cleaned name is safe to put in front of a model.