[{"data":1,"prerenderedAt":1011},["ShallowReactive",2],{"series-\u002Fseries\u002Fbuilding-code-mode-for-apis-with-mcp-and-isolated-workers\u002Flet-the-model-orchestrate-tools-with-a-local-code-runtime":3,"series-context-\u002Fseries\u002Fbuilding-code-mode-for-apis-with-mcp-and-isolated-workers":820},{"id":4,"title":5,"body":6,"contentId":805,"date":806,"description":807,"extension":808,"github":809,"meetTheInstructor":811,"meta":812,"navigation":142,"part":139,"path":813,"rawbody":814,"robots":811,"schemaOrg":811,"seo":815,"seriesSlug":816,"sitemap":817,"stem":818,"subtitle":811,"topics":811,"__hash__":819},"series\u002Fseries\u002Fbuilding-code-mode-for-apis-with-mcp-and-isolated-workers\u002Flet-the-model-orchestrate-tools-with-a-local-code-runtime.md","Let the Model Orchestrate Tools with a Local Code Runtime",{"type":7,"value":8,"toc":797},"minimark",[9,21,36,41,49,60,69,72,83,87,90,100,103,107,110,329,332,340,343,347,350,360,366,369,406,409,620,630,636,730,743,746,755,759,762,776,780,786,793],[10,11,12,13,20],"p",{},"Code Mode was popularized by Cloudflare in September 2025 with an article titled ",[14,15,19],"a",{"href":16,"rel":17},"https:\u002F\u002Fblog.cloudflare.com\u002Fcode-mode\u002F",[18],"nofollow","Code Mode: the better way to use MCP",". The article is well worth reading, but it can be a little overwhelming at first. It took me several months to fully understand the concept and how to use it correctly.",[10,22,23,24,27,28,31,32,35],{},"In this part, we will replace the two direct Drive tools with one generic ",[25,26,25],"code",{}," tool. We will expose a typed ",[25,29,30],{},"Drive"," facade and use a trusted local evaluator based on the ",[25,33,34],{},"Function"," constructor as a development shortcut before isolating it in Part 5.",[37,38,40],"h2",{"id":39},"from-a-multi-turn-mode","From a multi-turn mode",[10,42,43,44,48],{},"In ",[14,45,47],{"href":46},"\u002Fseries\u002Fbuilding-code-mode-for-apis-with-mcp-and-isolated-workers\u002Fbeyond-one-tool-call-at-a-time-introducing-code-mode","the previous article",", we saw the following example: creating a file that contains all the titles of one Markdown file within a Drive.",[10,50,51,52,55,56,59],{},"To do that, we built an MCP server with two tools: ",[25,53,54],{},"readFile"," and ",[25,57,58],{},"writeFile",", and predicted the model's behavior.",[10,61,62,63,65,66,68],{},"First, the model must read the file with ",[25,64,54],{},", loading the entire file content into its context. Then, it must extract the titles from the content and call ",[25,67,58],{}," to write the titles into a new file.",[10,70,71],{},"From a network perspective, the messages exchanged between the model and the MCP server will look like this:",[73,74,81],"pre",{"className":75,"code":77,"filename":78,"language":79,"meta":80},[76],"language-text","LLM -> MCP: readFile(path=\"myfile.md\")\nMCP -> LLM: { content: \"...\" }  \u002F\u002F entire file content\nLLM -> MCP: writeFile(path=\"myfile_titles.md\", content=\"...\")\nMCP -> LLM: { content: \"{ success: true }\" }\n","Example","text","",[25,82,77],{"__ignoreMap":80},[37,84,86],{"id":85},"to-a-single-turn-mode","To a single-turn mode",[10,88,89],{},"While the previous approach works fine, we can see some flaws in it.",[91,92,93,97],"ol",{},[94,95,96],"li",{},"For our goal, the write step is intrinsically linked to the read step. We know, from the start, that both steps are required to achieve our goal so, in theory, a single turn should be enough to achieve it.",[94,98,99],{},"The model has to load the entire file content into its context which consumes both processing time, tokens, and context space for something the model doesn't need to know.",[10,101,102],{},"That is precisely why Code Mode shines.",[37,104,106],{"id":105},"as-if-it-was-an-api","As if it was an API",[10,108,109],{},"If, instead of being an MCP, the drive were exposed as a package API, what would our code look like?",[73,111,115],{"className":112,"code":113,"filename":78,"language":114,"meta":80,"style":80},"language-ts shiki shiki-themes github-light github-light github-dark","import { readFile, writeFile } from 'drive'\n\nasync function createFileWithTitles(inputPath: string, outputPath: string) {\n  const content = await readFile(inputPath)\n  const titles = content.match(\u002F^# (.*)$\u002Fgm)?.map(title => title.replace(\u002F^# \u002F, '')) ?? []\n  await writeFile(outputPath, titles.join('\\n'))\n}\n","ts",[25,116,117,137,144,184,205,295,323],{"__ignoreMap":80},[118,119,122,126,130,133],"span",{"class":120,"line":121},"line",1,[118,123,125],{"class":124},"s8jYJ","import",[118,127,129],{"class":128},"sxrX7"," { readFile, writeFile } ",[118,131,132],{"class":124},"from",[118,134,136],{"class":135},"sIIMD"," 'drive'\n",[118,138,140],{"class":120,"line":139},2,[118,141,143],{"emptyLinePlaceholder":142},true,"\n",[118,145,147,150,153,157,160,164,167,171,174,177,179,181],{"class":120,"line":146},3,[118,148,149],{"class":124},"async",[118,151,152],{"class":124}," function",[118,154,156],{"class":155},"snPdu"," createFileWithTitles",[118,158,159],{"class":128},"(",[118,161,163],{"class":162},"sP4rz","inputPath",[118,165,166],{"class":124},":",[118,168,170],{"class":169},"sBjJW"," string",[118,172,173],{"class":128},", ",[118,175,176],{"class":162},"outputPath",[118,178,166],{"class":124},[118,180,170],{"class":169},[118,182,183],{"class":128},") {\n",[118,185,187,190,193,196,199,202],{"class":120,"line":186},4,[118,188,189],{"class":124},"  const",[118,191,192],{"class":169}," content",[118,194,195],{"class":124}," =",[118,197,198],{"class":124}," await",[118,200,201],{"class":155}," readFile",[118,203,204],{"class":128},"(inputPath)\n",[118,206,208,210,213,215,218,221,223,226,229,233,236,239,242,245,247,250,253,256,258,261,264,267,270,272,274,276,279,281,283,286,289,292],{"class":120,"line":207},5,[118,209,189],{"class":124},[118,211,212],{"class":169}," titles",[118,214,195],{"class":124},[118,216,217],{"class":128}," content.",[118,219,220],{"class":155},"match",[118,222,159],{"class":128},[118,224,225],{"class":135},"\u002F",[118,227,228],{"class":124},"^",[118,230,232],{"class":231},"s3JiQ","# (",[118,234,235],{"class":169},".",[118,237,238],{"class":124},"*",[118,240,241],{"class":231},")",[118,243,244],{"class":124},"$",[118,246,225],{"class":135},[118,248,249],{"class":124},"gm",[118,251,252],{"class":128},")?.",[118,254,255],{"class":155},"map",[118,257,159],{"class":128},[118,259,260],{"class":162},"title",[118,262,263],{"class":124}," =>",[118,265,266],{"class":128}," title.",[118,268,269],{"class":155},"replace",[118,271,159],{"class":128},[118,273,225],{"class":135},[118,275,228],{"class":124},[118,277,278],{"class":231},"# ",[118,280,225],{"class":135},[118,282,173],{"class":128},[118,284,285],{"class":135},"''",[118,287,288],{"class":128},")) ",[118,290,291],{"class":124},"??",[118,293,294],{"class":128}," []\n",[118,296,298,301,304,307,310,312,315,318,320],{"class":120,"line":297},6,[118,299,300],{"class":124},"  await",[118,302,303],{"class":155}," writeFile",[118,305,306],{"class":128},"(outputPath, titles.",[118,308,309],{"class":155},"join",[118,311,159],{"class":128},[118,313,314],{"class":135},"'",[118,316,317],{"class":169},"\\n",[118,319,314],{"class":135},[118,321,322],{"class":128},"))\n",[118,324,326],{"class":120,"line":325},7,[118,327,328],{"class":128},"}\n",[10,330,331],{},"It could look like that.",[10,333,334,335,55,337,339],{},"Instead of exposing ",[25,336,54],{},[25,338,58],{}," as individual tool calls, we expose them as functions. Behind the scenes, the implementation could be the same; only the facade changes, and the expected behavior remains the same.",[10,341,342],{},"Now, instead of asking the model to orchestrate the tools, we could ask it to orchestrate the functions by writing the code for us.",[37,344,346],{"id":345},"llms-know-code-better-than-we-do","LLMs know code better than we do",[10,348,349],{},"LLMs are often more reliable at writing familiar code patterns than at selecting from a complex tool surface. Code Mode takes advantage of that strength without giving generated code unrestricted access to the host.",[10,351,352,353,355,356,359],{},"So, instead of providing tools to the model, we can provide a single ",[25,354,25],{}," tool. To let the model know what to do and which functions are available, we can provide a typed interface in the tool description, exactly like in TypeScript ",[25,357,358],{},".d.ts"," files.",[73,361,364],{"className":362,"code":363,"filename":358,"language":79,"meta":80},[76],"Run one small JavaScript program against the local Drive capability.\n\nThe generated code is an async arrow function. It receives only the named capabilities below and should return the compact result needed by the next decision.\n\ninterface Drive {\n  readFile: (path: string) => Promise\u003Cstring>;\n  writeFile: (path: string, content: string) => Promise\u003Cvoid>;\n}\n\ndeclare const drive: Drive;\n\nExample:\nasync () => {\n  const content = await drive.readFile('article.md');\n  const headings = content\n    .split('\\\\n')\n    .filter((line) => \u002F^#{1,6}\\\\s\u002F.test(line))\n    .map((line) => line.replace(\u002F^#+\\\\s*\u002F, ''));\n\n  await drive.writeFile('titles.md', headings.join('\\\\n'));\n  return { headingCount: headings.length };\n}\n",[25,365,363],{"__ignoreMap":80},[10,367,368],{},"Within this description, we provide the model with multiple pieces of information:",[370,371,372,375,378,384,400],"ul",{},[94,373,374],{},"A short description of what the code should do.",[94,376,377],{},"An explanation of the expected code format, which is an async arrow function that receives only the named capabilities and should return a compact result.",[94,379,380,381,383],{},"The ",[25,382,30],{}," interface describes the available functions and their types.",[94,385,380,386,389,390,392,393,55,396,399],{},[25,387,388],{},"drive"," constant is the instance of the ",[25,391,30],{}," interface that the model can use. It tells the model that it can use ",[25,394,395],{},"drive.readFile",[25,397,398],{},"drive.writeFile"," to read and write files as a global variable.",[94,401,402,403,405],{},"The example shows how to use the ",[25,404,388],{}," constant. This is a good practice: it provides the model with a clear example of how to use the available functions. This makes it more reliable and reduces the risk of the model generating code that does not work.",[10,407,408],{},"And the tool could look like this:",[73,410,412],{"className":112,"code":411,"filename":78,"language":114,"meta":80,"style":80},"server.registerTool(\n  'code',\n  {\n    title: 'Drive Code Mode',\n    description: '...', \u002F\u002F Description from the previous code block\n    inputSchema: z.object({\n      code: z\n        .string()\n        .describe('An async arrow function that uses the typed Drive capability')\n    }),\n    annotations: {\n      title: 'Drive Code Mode'\n    }\n  },\n  async ({ code }) => {\n    const result = await evaluateCode(code)\n    const text = formatCodeResult(result)\n    return { content: [{ type: 'text', text }] }\n  }\n)\n",[25,413,414,425,433,438,448,462,473,478,490,506,512,518,527,533,539,559,578,594,609,615],{"__ignoreMap":80},[118,415,416,419,422],{"class":120,"line":121},[118,417,418],{"class":128},"server.",[118,420,421],{"class":155},"registerTool",[118,423,424],{"class":128},"(\n",[118,426,427,430],{"class":120,"line":139},[118,428,429],{"class":135},"  'code'",[118,431,432],{"class":128},",\n",[118,434,435],{"class":120,"line":146},[118,436,437],{"class":128},"  {\n",[118,439,440,443,446],{"class":120,"line":186},[118,441,442],{"class":128},"    title: ",[118,444,445],{"class":135},"'Drive Code Mode'",[118,447,432],{"class":128},[118,449,450,453,456,458],{"class":120,"line":207},[118,451,452],{"class":128},"    description: ",[118,454,455],{"class":135},"'...'",[118,457,173],{"class":128},[118,459,461],{"class":460},"sCsY4","\u002F\u002F Description from the previous code block\n",[118,463,464,467,470],{"class":120,"line":297},[118,465,466],{"class":128},"    inputSchema: z.",[118,468,469],{"class":155},"object",[118,471,472],{"class":128},"({\n",[118,474,475],{"class":120,"line":325},[118,476,477],{"class":128},"      code: z\n",[118,479,481,484,487],{"class":120,"line":480},8,[118,482,483],{"class":128},"        .",[118,485,486],{"class":155},"string",[118,488,489],{"class":128},"()\n",[118,491,493,495,498,500,503],{"class":120,"line":492},9,[118,494,483],{"class":128},[118,496,497],{"class":155},"describe",[118,499,159],{"class":128},[118,501,502],{"class":135},"'An async arrow function that uses the typed Drive capability'",[118,504,505],{"class":128},")\n",[118,507,509],{"class":120,"line":508},10,[118,510,511],{"class":128},"    }),\n",[118,513,515],{"class":120,"line":514},11,[118,516,517],{"class":128},"    annotations: {\n",[118,519,521,524],{"class":120,"line":520},12,[118,522,523],{"class":128},"      title: ",[118,525,526],{"class":135},"'Drive Code Mode'\n",[118,528,530],{"class":120,"line":529},13,[118,531,532],{"class":128},"    }\n",[118,534,536],{"class":120,"line":535},14,[118,537,538],{"class":128},"  },\n",[118,540,542,545,548,550,553,556],{"class":120,"line":541},15,[118,543,544],{"class":124},"  async",[118,546,547],{"class":128}," ({ ",[118,549,25],{"class":162},[118,551,552],{"class":128}," }) ",[118,554,555],{"class":124},"=>",[118,557,558],{"class":128}," {\n",[118,560,562,565,568,570,572,575],{"class":120,"line":561},16,[118,563,564],{"class":124},"    const",[118,566,567],{"class":169}," result",[118,569,195],{"class":124},[118,571,198],{"class":124},[118,573,574],{"class":155}," evaluateCode",[118,576,577],{"class":128},"(code)\n",[118,579,581,583,586,588,591],{"class":120,"line":580},17,[118,582,564],{"class":124},[118,584,585],{"class":169}," text",[118,587,195],{"class":124},[118,589,590],{"class":155}," formatCodeResult",[118,592,593],{"class":128},"(result)\n",[118,595,597,600,603,606],{"class":120,"line":596},18,[118,598,599],{"class":124},"    return",[118,601,602],{"class":128}," { content: [{ type: ",[118,604,605],{"class":135},"'text'",[118,607,608],{"class":128},", text }] }\n",[118,610,612],{"class":120,"line":611},19,[118,613,614],{"class":128},"  }\n",[118,616,618],{"class":120,"line":617},20,[118,619,505],{"class":128},[10,621,622,623,625,626,629],{},"As you can see, the ",[25,624,25],{}," tool is pretty generic. The power happens in the ",[25,627,628],{},"evaluateCode"," function, which will execute the code, preferably in a sandboxed environment.",[10,631,632,633,635],{},"However, for our example, we'll use a trusted local evaluator based on the ",[25,634,34],{}," constructor. It is not safe for production, but it is enough for this development checkpoint.",[73,637,639],{"className":112,"code":638,"filename":78,"language":114,"meta":80,"style":80},"\u002F\u002F eslint-disable-next-line no-new-func\nconst orchestrate = new Function(\n  ...Object.keys(capabilities),\n  `\"use strict\"; return (${code.trim()});`\n)(...Object.values(capabilities))\n\nconst result = await orchestrate()\n",[25,640,641,646,664,678,696,712,716],{"__ignoreMap":80},[118,642,643],{"class":120,"line":121},[118,644,645],{"class":460},"\u002F\u002F eslint-disable-next-line no-new-func\n",[118,647,648,651,654,656,659,662],{"class":120,"line":139},[118,649,650],{"class":124},"const",[118,652,653],{"class":169}," orchestrate",[118,655,195],{"class":124},[118,657,658],{"class":124}," new",[118,660,661],{"class":155}," Function",[118,663,424],{"class":128},[118,665,666,669,672,675],{"class":120,"line":146},[118,667,668],{"class":124},"  ...",[118,670,671],{"class":128},"Object.",[118,673,674],{"class":155},"keys",[118,676,677],{"class":128},"(capabilities),\n",[118,679,680,683,685,687,690,693],{"class":120,"line":186},[118,681,682],{"class":135},"  `\"use strict\"; return (${",[118,684,25],{"class":128},[118,686,235],{"class":135},[118,688,689],{"class":155},"trim",[118,691,692],{"class":135},"()",[118,694,695],{"class":135},"});`\n",[118,697,698,701,704,706,709],{"class":120,"line":207},[118,699,700],{"class":128},")(",[118,702,703],{"class":124},"...",[118,705,671],{"class":128},[118,707,708],{"class":155},"values",[118,710,711],{"class":128},"(capabilities))\n",[118,713,714],{"class":120,"line":297},[118,715,143],{"emptyLinePlaceholder":142},[118,717,718,720,722,724,726,728],{"class":120,"line":325},[118,719,650],{"class":124},[118,721,567],{"class":169},[118,723,195],{"class":124},[118,725,198],{"class":124},[118,727,653],{"class":155},[118,729,489],{"class":128},[731,732,735],"callout",{"color":733,"icon":734},"primary","i-ph-info-duotone",[10,736,737,738,742],{},"For production environments, you have to use a sandboxed evaluator. See ",[14,739,741],{"href":740},".\u002Freplacing-local-eval-with-isolated-cloudflare-workers","Replacing Local Eval with Isolated Cloudflare Workers"," for more information.",[10,744,745],{},"If you've never used this constructor, that's normal. It is unsafe and should not run untrusted code, including LLM-generated code, outside this trusted development checkpoint.",[10,747,748,749,751,752,754],{},"To quickly explain the ",[25,750,34],{}," constructor, it creates a new function from the provided code string. The first arguments are the parameter names, and the last argument is the function body. In our case, we pass the ",[25,753,388],{}," capability as a parameter and return the async arrow function generated by the model.",[37,756,758],{"id":757},"code-mode-into-libraries","Code Mode into libraries",[10,760,761],{},"Code Mode can be painful to implement because you have to keep the types in the tool description in sync with the actual implementation.",[10,763,764,765,55,770,775],{},"Fortunately, libraries like ",[14,766,769],{"href":767,"rel":768},"https:\u002F\u002Fdevelopers.cloudflare.com\u002Fagents\u002Ftools\u002Fcodemode\u002F",[18],"Cloudflare Code Mode",[14,771,774],{"href":772,"rel":773},"https:\u002F\u002Ftanstack.com\u002Fblog\u002Ftanstack-ai-code-mode",[18],"TanStack Code Mode"," provide an easy way to implement Code Mode with the same tool definition as an MCP.",[37,777,779],{"id":778},"what-we-have-built","What we have built",[10,781,782,783,785],{},"We have replaced two dependent tool calls with one generated program that uses a typed ",[25,784,30],{}," facade and returns only the result needed for the next decision. The executor boundary is deliberately narrow: the next articles keep the same pattern while changing the capability from a local Drive to a much larger OpenAPI specification.",[10,787,43,788,792],{},[14,789,791],{"href":790},"\u002Fseries\u002Fbuilding-code-mode-for-apis-with-mcp-and-isolated-workers\u002Fsearching-openapi-specification-without-filling-the-context","Part 3",", we will use that boundary to search an OpenAPI document without placing the whole specification in the model's context.",[794,795,796],"style",{},"html pre.shiki code .s8jYJ, html code.shiki .s8jYJ{--shiki-light:#D73A49;--shiki-default:#D73A49;--shiki-dark:#F97583}html pre.shiki code .sxrX7, html code.shiki .sxrX7{--shiki-light:#24292E;--shiki-default:#24292E;--shiki-dark:#E1E4E8}html pre.shiki code .sIIMD, html code.shiki .sIIMD{--shiki-light:#032F62;--shiki-default:#032F62;--shiki-dark:#9ECBFF}html pre.shiki code .snPdu, html code.shiki .snPdu{--shiki-light:#6F42C1;--shiki-default:#6F42C1;--shiki-dark:#B392F0}html pre.shiki code .sP4rz, html code.shiki .sP4rz{--shiki-light:#E36209;--shiki-default:#E36209;--shiki-dark:#FFAB70}html pre.shiki code .sBjJW, html code.shiki .sBjJW{--shiki-light:#005CC5;--shiki-default:#005CC5;--shiki-dark:#79B8FF}html pre.shiki code .s3JiQ, html code.shiki .s3JiQ{--shiki-light:#032F62;--shiki-default:#032F62;--shiki-dark:#DBEDFF}html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .sCsY4, html code.shiki .sCsY4{--shiki-light:#6A737D;--shiki-default:#6A737D;--shiki-dark:#6A737D}",{"title":80,"searchDepth":139,"depth":139,"links":798},[799,800,801,802,803,804],{"id":39,"depth":139,"text":40},{"id":85,"depth":139,"text":86},{"id":105,"depth":139,"text":106},{"id":345,"depth":139,"text":346},{"id":757,"depth":139,"text":758},{"id":778,"depth":139,"text":779},"2a9e7d4c-1f6b-4c83-9d52-7e0a6b3f4189","2026-07-12","Build a minimal trusted local Code Mode runtime with a typed Drive facade and an executor seam ready for isolation.","md",{"branch":810},"part-2-generic-code-mode",null,{},"\u002Fseries\u002Fbuilding-code-mode-for-apis-with-mcp-and-isolated-workers\u002Flet-the-model-orchestrate-tools-with-a-local-code-runtime","---\ncontentId: 2a9e7d4c-1f6b-4c83-9d52-7e0a6b3f4189\npart: 2\ntitle: Let the Model Orchestrate Tools with a Local Code Runtime\ndescription: Build a minimal trusted local Code Mode runtime with a typed Drive facade and an executor seam ready for isolation.\ngithub:\n  branch: part-2-generic-code-mode\ndate: 2026-07-12\nseriesSlug: building-code-mode-for-apis-with-mcp-and-isolated-workers\n---\n\nCode Mode was popularized by Cloudflare in September 2025 with an article titled [Code Mode: the better way to use MCP](https:\u002F\u002Fblog.cloudflare.com\u002Fcode-mode\u002F). The article is well worth reading, but it can be a little overwhelming at first. It took me several months to fully understand the concept and how to use it correctly.\n\nIn this part, we will replace the two direct Drive tools with one generic `code` tool. We will expose a typed `Drive` facade and use a trusted local evaluator based on the `Function` constructor as a development shortcut before isolating it in Part 5.\n\n## From a multi-turn mode\n\nIn [the previous article](\u002Fseries\u002Fbuilding-code-mode-for-apis-with-mcp-and-isolated-workers\u002Fbeyond-one-tool-call-at-a-time-introducing-code-mode), we saw the following example: creating a file that contains all the titles of one Markdown file within a Drive.\n\nTo do that, we built an MCP server with two tools: `readFile` and `writeFile`, and predicted the model's behavior.\n\nFirst, the model must read the file with `readFile`, loading the entire file content into its context. Then, it must extract the titles from the content and call `writeFile` to write the titles into a new file.\n\nFrom a network perspective, the messages exchanged between the model and the MCP server will look like this:\n\n```text [Example]\nLLM -> MCP: readFile(path=\"myfile.md\")\nMCP -> LLM: { content: \"...\" }  \u002F\u002F entire file content\nLLM -> MCP: writeFile(path=\"myfile_titles.md\", content=\"...\")\nMCP -> LLM: { content: \"{ success: true }\" }\n```\n\n## To a single-turn mode\n\nWhile the previous approach works fine, we can see some flaws in it.\n\n1. For our goal, the write step is intrinsically linked to the read step. We know, from the start, that both steps are required to achieve our goal so, in theory, a single turn should be enough to achieve it.\n2. The model has to load the entire file content into its context which consumes both processing time, tokens, and context space for something the model doesn't need to know.\n\nThat is precisely why Code Mode shines.\n\n## As if it was an API\n\nIf, instead of being an MCP, the drive were exposed as a package API, what would our code look like?\n\n```ts [Example]\nimport { readFile, writeFile } from 'drive'\n\nasync function createFileWithTitles(inputPath: string, outputPath: string) {\n  const content = await readFile(inputPath)\n  const titles = content.match(\u002F^# (.*)$\u002Fgm)?.map(title => title.replace(\u002F^# \u002F, '')) ?? []\n  await writeFile(outputPath, titles.join('\\n'))\n}\n```\n\nIt could look like that.\n\nInstead of exposing `readFile` and `writeFile` as individual tool calls, we expose them as functions. Behind the scenes, the implementation could be the same; only the facade changes, and the expected behavior remains the same.\n\nNow, instead of asking the model to orchestrate the tools, we could ask it to orchestrate the functions by writing the code for us.\n\n## LLMs know code better than we do\n\nLLMs are often more reliable at writing familiar code patterns than at selecting from a complex tool surface. Code Mode takes advantage of that strength without giving generated code unrestricted access to the host.\n\nSo, instead of providing tools to the model, we can provide a single `code` tool. To let the model know what to do and which functions are available, we can provide a typed interface in the tool description, exactly like in TypeScript `.d.ts` files.\n\n```text [.d.ts]\nRun one small JavaScript program against the local Drive capability.\n\nThe generated code is an async arrow function. It receives only the named capabilities below and should return the compact result needed by the next decision.\n\ninterface Drive {\n  readFile: (path: string) => Promise\u003Cstring>;\n  writeFile: (path: string, content: string) => Promise\u003Cvoid>;\n}\n\ndeclare const drive: Drive;\n\nExample:\nasync () => {\n  const content = await drive.readFile('article.md');\n  const headings = content\n    .split('\\\\n')\n    .filter((line) => \u002F^#{1,6}\\\\s\u002F.test(line))\n    .map((line) => line.replace(\u002F^#+\\\\s*\u002F, ''));\n\n  await drive.writeFile('titles.md', headings.join('\\\\n'));\n  return { headingCount: headings.length };\n}\n```\n\nWithin this description, we provide the model with multiple pieces of information:\n\n- A short description of what the code should do.\n- An explanation of the expected code format, which is an async arrow function that receives only the named capabilities and should return a compact result.\n- The `Drive` interface describes the available functions and their types.\n- The `drive` constant is the instance of the `Drive` interface that the model can use. It tells the model that it can use `drive.readFile` and `drive.writeFile` to read and write files as a global variable.\n- The example shows how to use the `drive` constant. This is a good practice: it provides the model with a clear example of how to use the available functions. This makes it more reliable and reduces the risk of the model generating code that does not work.\n\nAnd the tool could look like this:\n\n```ts [Example]\nserver.registerTool(\n  'code',\n  {\n    title: 'Drive Code Mode',\n    description: '...', \u002F\u002F Description from the previous code block\n    inputSchema: z.object({\n      code: z\n        .string()\n        .describe('An async arrow function that uses the typed Drive capability')\n    }),\n    annotations: {\n      title: 'Drive Code Mode'\n    }\n  },\n  async ({ code }) => {\n    const result = await evaluateCode(code)\n    const text = formatCodeResult(result)\n    return { content: [{ type: 'text', text }] }\n  }\n)\n```\n\nAs you can see, the `code` tool is pretty generic. The power happens in the `evaluateCode` function, which will execute the code, preferably in a sandboxed environment.\n\nHowever, for our example, we'll use a trusted local evaluator based on the `Function` constructor. It is not safe for production, but it is enough for this development checkpoint.\n\n```ts [Example]\n\u002F\u002F eslint-disable-next-line no-new-func\nconst orchestrate = new Function(\n  ...Object.keys(capabilities),\n  `\"use strict\"; return (${code.trim()});`\n)(...Object.values(capabilities))\n\nconst result = await orchestrate()\n```\n\n::callout{icon=\"i-ph-info-duotone\" color=\"primary\"}\nFor production environments, you have to use a sandboxed evaluator. See [Replacing Local Eval with Isolated Cloudflare Workers](.\u002Freplacing-local-eval-with-isolated-cloudflare-workers.md) for more information.\n::\n\nIf you've never used this constructor, that's normal. It is unsafe and should not run untrusted code, including LLM-generated code, outside this trusted development checkpoint.\n\nTo quickly explain the `Function` constructor, it creates a new function from the provided code string. The first arguments are the parameter names, and the last argument is the function body. In our case, we pass the `drive` capability as a parameter and return the async arrow function generated by the model.\n\n## Code Mode into libraries\n\nCode Mode can be painful to implement because you have to keep the types in the tool description in sync with the actual implementation.\n\nFortunately, libraries like [Cloudflare Code Mode](https:\u002F\u002Fdevelopers.cloudflare.com\u002Fagents\u002Ftools\u002Fcodemode\u002F) and [TanStack Code Mode](https:\u002F\u002Ftanstack.com\u002Fblog\u002Ftanstack-ai-code-mode) provide an easy way to implement Code Mode with the same tool definition as an MCP.\n\n## What we have built\n\nWe have replaced two dependent tool calls with one generated program that uses a typed `Drive` facade and returns only the result needed for the next decision. The executor boundary is deliberately narrow: the next articles keep the same pattern while changing the capability from a local Drive to a much larger OpenAPI specification.\n\nIn [Part 3](\u002Fseries\u002Fbuilding-code-mode-for-apis-with-mcp-and-isolated-workers\u002Fsearching-openapi-specification-without-filling-the-context), we will use that boundary to search an OpenAPI document without placing the whole specification in the model's context.\n",{"title":5,"description":807},"building-code-mode-for-apis-with-mcp-and-isolated-workers",{"loc":813},"series\u002Fbuilding-code-mode-for-apis-with-mcp-and-isolated-workers\u002Flet-the-model-orchestrate-tools-with-a-local-code-runtime","pjoYRGoLA__hkv0esbaqDw11XixnfSvo1nnyICwTfFs",{"overview":821,"chapters":986},{"id":822,"title":823,"body":824,"contentId":965,"date":806,"description":966,"extension":808,"github":967,"meetTheInstructor":969,"meta":970,"navigation":142,"part":811,"path":971,"rawbody":972,"robots":811,"schemaOrg":811,"seo":973,"seriesSlug":816,"sitemap":974,"stem":975,"subtitle":976,"topics":977,"__hash__":985},"series\u002Fseries\u002Fbuilding-code-mode-for-apis-with-mcp-and-isolated-workers.md","Building Code Mode for APIs with MCP and Isolated Workers",{"type":7,"value":825,"toc":962},[826,829,837,843,855,871,874,877,880,935,943,952,956],[10,827,828],{},"Hello and welcome! 👋",[10,830,831,832,836],{},"This series is a practical follow-up to ",[14,833,835],{"href":834},"\u002Fposts\u002Fcode-mode-two-tools-and-an-mcp-can-save-your-llm-context","Code Mode, Two Tools, and an MCP Can Save Your LLM Context",". That article introduced the idea: instead of making a model orchestrate every dependent tool call, let it write the orchestration as code and return only the result needed for its next decision.",[10,838,839,840,842],{},"Here, we will build that idea step by step. We will start with a small local file transformation, move to an OpenAPI-described API, and then replace the trusted local evaluator based on the ",[25,841,34],{}," constructor with an isolated runtime. The final result will be a locally runnable MCP server that can search an API specification and execute a narrow request against the API.",[10,844,845,846,850,851,235],{},"MCP fundamentals are outside the scope of this series. If you need an introduction to the protocol or to the basic relationship between an AI agent and an MCP server, begin with ",[14,847,849],{"href":848},"\u002Fseries\u002Fai-agents-and-mcp-server-teaming-up-for-the-agentic-web","AI Agents and MCP Server: Teaming Up for the Agentic Web",", especially ",[14,852,854],{"href":853},"\u002Fseries\u002Fai-agents-and-mcp-server-teaming-up-for-the-agentic-web\u002Fmcp-to-provide-additional-capabilities-to-the-ai-agent","its MCP server article",[10,856,857,858,862,863,866,867,870],{},"Throughout the series, the ",[859,860,861],"strong",{},"model"," generates tool calls or code, the ",[859,864,865],{},"MCP client"," (or agent) runs the model loop, and the ",[859,868,869],{},"MCP server"," provides the capabilities. Keeping these roles separate is important: the host, not generated code, defines which capabilities are available.",[10,872,873],{},"The central idea is simple: with direct MCP tools, the model must call one tool, receive the complete intermediate result, and then use that result to decide how to call the next tool. With Code Mode, the model writes the orchestration as code, the code accesses the capabilities it needs inside the execution environment, and the model receives only the desired final result to continue.",[10,875,876],{},"Code Mode is not automatically the right choice. Direct MCP tools remain simpler for small, obvious actions. The extra runtime is worthwhile when a task contains dependent calls, requires local data processing, or needs to navigate a large and evolving API surface, like an OpenAPI specification that can be larger than the model's context window.",[10,878,879],{},"Throughout this journey, we will:",[91,881,882,891,905,915,929],{},[94,883,884,887,888,890],{},[859,885,886],{},"Beyond One Tool Call at a Time: Introducing Code Mode",": Build two direct ",[25,889,30],{}," tools over a Markdown fixture and observe how the complete file content travels through the model's context before the next tool call.",[94,892,893,895,896,898,899,901,902,904],{},[859,894,5],{},": Replace the two direct tools with one generic ",[25,897,25],{}," tool, expose a typed ",[25,900,30],{}," facade, and introduce the executor interface that later parts will replace. The local evaluator based on the ",[25,903,34],{}," constructor is intentionally a trusted development shortcut, not a production sandbox.",[94,906,907,910,911,914],{},[859,908,909],{},"Searching OpenAPI Specifications Without Filling Context",": Keep the OpenAPI document inside the server, resolve its local ",[25,912,913],{},"$ref"," values, and let generated code search a compact type facade instead of returning the complete specification to the model.",[94,916,917,920,921,924,925,928],{},[859,918,919],{},"Calling APIs with Code Mode and Returning Only What Matters",": Add a separate ",[25,922,923],{},"execute"," tool with a host-owned ",[25,926,927],{},"api.request()"," helper. We will validate request options, call the local MarketHub fixture, and return a narrow projection rather than the complete API response.",[94,930,931,934],{},[859,932,933],{},"Replacing the Evaluator with Isolated Cloudflare Workers",": Swap only the executor boundary for fresh Dynamic Workers. Search will run without outbound access, execute will use an allowlisted gateway, and credentials will remain outside generated code. We will also cover result bounds, resource limits, and host deadlines.",[10,936,937,938,942],{},"The companion repository, ",[939,940],"git-hub-link",{"repo":941},"barbapapazes\u002Fcode-mode",", is an executable textbook for the series. Each article has a complete checkpoint branch, a small evaluation, and a focused diff from the previous step. I recommend that you check out a branch and inspect the implementation for a better understanding of the concepts, as the articles will not cover every detail.",[731,944,946],{"color":945,"icon":734},"info",[10,947,948,949,951],{},"This series assumes familiarity with TypeScript, JavaScript promises, HTTP APIs, and basic MCP concepts. The local checkpoints contain no credentials. Parts 2 through 4 use a trusted local evaluator based on the ",[25,950,34],{}," constructor for development, while Part 5 provides a Cloudflare deployment scaffold and structural security evaluation.",[37,953,955],{"id":954},"chapters","Chapters",[957,958],"series-chapters-list",{"className":959},[960,961],"mx-auto","max-w-5xl",{"title":80,"searchDepth":139,"depth":139,"links":963},[964],{"id":954,"depth":139,"text":955},"8f6d8d8d-9cc8-4ed3-9f2d-4e3d0b7a4d91","Build an MCP server for an OpenAPI-described API, then replace a trusted local evaluator with isolated Cloudflare Dynamic Workers.",{"name":968,"repository":941},"Code Mode","I created this series to turn the Code Mode idea into a practical implementation. We will start with two ordinary MCP tools, move the orchestration into generated code, and finish by replacing a trusted local evaluator based on the Function constructor with isolated Cloudflare Dynamic Workers.",{},"\u002Fseries\u002Fbuilding-code-mode-for-apis-with-mcp-and-isolated-workers","---\ncontentId: 8f6d8d8d-9cc8-4ed3-9f2d-4e3d0b7a4d91\ntitle: Building Code Mode for APIs with MCP and Isolated Workers\nsubtitle: Build a context-efficient MCP server for OpenAPI-described APIs\ndescription: Build an MCP server for an OpenAPI-described API, then replace a trusted local evaluator with isolated Cloudflare Dynamic Workers.\ndate: 2026-07-12\ntopics:\n  - ai\n  - ai-agents\n  - mcp\n  - code-mode\n  - openapi\n  - cloudflare\n  - typescript\ngithub:\n  name: Code Mode\n  repository: barbapapazes\u002Fcode-mode\nmeetTheInstructor: I created this series to turn the Code Mode idea into a practical implementation. We will start with two ordinary MCP tools, move the orchestration into generated code, and finish by replacing a trusted local evaluator based on the Function constructor with isolated Cloudflare Dynamic Workers.\nseriesSlug: building-code-mode-for-apis-with-mcp-and-isolated-workers\n---\n\nHello and welcome! 👋\n\nThis series is a practical follow-up to [Code Mode, Two Tools, and an MCP Can Save Your LLM Context](\u002Fposts\u002Fcode-mode-two-tools-and-an-mcp-can-save-your-llm-context). That article introduced the idea: instead of making a model orchestrate every dependent tool call, let it write the orchestration as code and return only the result needed for its next decision.\n\nHere, we will build that idea step by step. We will start with a small local file transformation, move to an OpenAPI-described API, and then replace the trusted local evaluator based on the `Function` constructor with an isolated runtime. The final result will be a locally runnable MCP server that can search an API specification and execute a narrow request against the API.\n\nMCP fundamentals are outside the scope of this series. If you need an introduction to the protocol or to the basic relationship between an AI agent and an MCP server, begin with [AI Agents and MCP Server: Teaming Up for the Agentic Web](\u002Fseries\u002Fai-agents-and-mcp-server-teaming-up-for-the-agentic-web), especially [its MCP server article](\u002Fseries\u002Fai-agents-and-mcp-server-teaming-up-for-the-agentic-web\u002Fmcp-to-provide-additional-capabilities-to-the-ai-agent).\n\nThroughout the series, the **model** generates tool calls or code, the **MCP client** (or agent) runs the model loop, and the **MCP server** provides the capabilities. Keeping these roles separate is important: the host, not generated code, defines which capabilities are available.\n\nThe central idea is simple: with direct MCP tools, the model must call one tool, receive the complete intermediate result, and then use that result to decide how to call the next tool. With Code Mode, the model writes the orchestration as code, the code accesses the capabilities it needs inside the execution environment, and the model receives only the desired final result to continue.\n\nCode Mode is not automatically the right choice. Direct MCP tools remain simpler for small, obvious actions. The extra runtime is worthwhile when a task contains dependent calls, requires local data processing, or needs to navigate a large and evolving API surface, like an OpenAPI specification that can be larger than the model's context window.\n\nThroughout this journey, we will:\n\n1. **Beyond One Tool Call at a Time: Introducing Code Mode**: Build two direct `Drive` tools over a Markdown fixture and observe how the complete file content travels through the model's context before the next tool call.\n2. **Let the Model Orchestrate Tools with a Local Code Runtime**: Replace the two direct tools with one generic `code` tool, expose a typed `Drive` facade, and introduce the executor interface that later parts will replace. The local evaluator based on the `Function` constructor is intentionally a trusted development shortcut, not a production sandbox.\n3. **Searching OpenAPI Specifications Without Filling Context**: Keep the OpenAPI document inside the server, resolve its local `$ref` values, and let generated code search a compact type facade instead of returning the complete specification to the model.\n4. **Calling APIs with Code Mode and Returning Only What Matters**: Add a separate `execute` tool with a host-owned `api.request()` helper. We will validate request options, call the local MarketHub fixture, and return a narrow projection rather than the complete API response.\n5. **Replacing the Evaluator with Isolated Cloudflare Workers**: Swap only the executor boundary for fresh Dynamic Workers. Search will run without outbound access, execute will use an allowlisted gateway, and credentials will remain outside generated code. We will also cover result bounds, resource limits, and host deadlines.\n\nThe companion repository, \u003CGitHubLink repo=\"barbapapazes\u002Fcode-mode\" \u002F>, is an executable textbook for the series. Each article has a complete checkpoint branch, a small evaluation, and a focused diff from the previous step. I recommend that you check out a branch and inspect the implementation for a better understanding of the concepts, as the articles will not cover every detail.\n\n::callout{icon=\"i-ph-info-duotone\" color=\"info\"}\nThis series assumes familiarity with TypeScript, JavaScript promises, HTTP APIs, and basic MCP concepts. The local checkpoints contain no credentials. Parts 2 through 4 use a trusted local evaluator based on the `Function` constructor for development, while Part 5 provides a Cloudflare deployment scaffold and structural security evaluation.\n::\n\n## Chapters\n\n::series-chapters-list\n---\nclass: mx-auto max-w-5xl\n---\n::\n",{"title":823,"description":966},{"loc":971},"series\u002Fbuilding-code-mode-for-apis-with-mcp-and-isolated-workers","Build a context-efficient MCP server for OpenAPI-described APIs",[978,979,980,981,982,983,984],"ai","ai-agents","mcp","code-mode","openapi","cloudflare","typescript","WgDRYOu5CDIYY78O1GSEOv6BKbIsrTVwVf8cTOkdsOA",[987,992,994,999,1005],{"contentId":988,"title":886,"description":989,"path":46,"part":121,"github":990,"topics":811},"6f0c6f18-8d31-4b4d-aea6-9b2df779a0d1","See why dependent direct MCP tool calls make intermediate content part of model context, and how Code Mode moves orchestration into generated code.",{"branch":991},"part-1-direct-tools",{"contentId":805,"title":5,"description":807,"path":813,"part":139,"github":993,"topics":811},{"branch":810},{"contentId":995,"title":909,"description":996,"path":790,"part":146,"github":997,"topics":811},"8c4a1e72-bf39-4d65-a08e-2c7f91b6d543","Keep an OpenAPI specification server-side and search a compact typed facade without returning the complete document.",{"branch":998},"part-3-search",{"contentId":1000,"title":919,"description":1001,"path":1002,"part":186,"github":1003,"topics":811},"1d7b5e93-6a24-4f80-bc19-3e8d0a572f16","Use a host-owned API request helper to validate and execute a narrow API call, then return only the useful projection.","\u002Fseries\u002Fbuilding-code-mode-for-apis-with-mcp-and-isolated-workers\u002Fcalling-apis-with-code-mode-and-returning-only-what-matters",{"branch":1004},"part-4-local-execute",{"contentId":1006,"title":933,"description":1007,"path":1008,"part":207,"github":1009,"topics":811},"5e3a9c71-2b48-4d06-8f95-c7a1e0b6342d","Replace a trusted local Function evaluator with isolated Cloudflare Dynamic Workers, controlled outbound access, and bounded execution results.","\u002Fseries\u002Fbuilding-code-mode-for-apis-with-mcp-and-isolated-workers\u002Freplacing-local-eval-with-isolated-cloudflare-workers",{"branch":1010},"part-5-dynamic-workers",1795016691380]