Use Cloudflare Code Mode with Browser Run’s Chrome DevTools Protocol (CDP) connector when an AI model must inspect or operate a remote web page. Code Mode lets the model write one JavaScript program that calls typed MCP methods, loops over results, branches on page state and returns only the useful output. Browser Run supplies the remote browser session. They solve different parts of the problem: MCP exposes capabilities, Code Mode composes them, and CDP carries the browser interaction.
This guide also distinguishes that setup from @cloudflare/codemode/browser, which runs model-written code against tools inside a user’s own browser page and does not provide remote-browser control.
What Code Mode, MCP and Browser Run each do
Model Context Protocol (MCP)
MCP is the tool boundary. An MCP server publishes typed operations and schemas that a model can call. Your server or host remains responsible for authentication and authorization.
Code Mode
Without Code Mode, a model normally makes a tool call, receives the complete intermediate result, decides what to do next, and repeats. With Code Mode, it writes a small program against typed methods. The program can compose dependent calls, filter large responses, retry a safe read, loop through elements and return a compact result in one sandbox execution.
Recommended Free Tools
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Direct calls are still preferable for one simple action or a small, fixed tool set. Code Mode is most useful when the workflow has branching, iteration, progressive discovery or reusable logic.
Browser Run and CDP
Cloudflare describes Browser Run as a beta integration for inspecting and interacting with live pages through Chrome DevTools Protocol. Generated Code Mode executes against the browser session through the cdp connector. Browser Run is therefore the remote-browser path; Code Mode is the orchestration layer.
Choose an MCP design before writing code
| Design | Use it when | Trade-off |
|---|---|---|
One code tool |
Your existing MCP server has a manageable catalog. | Simple integration, but the model still needs a useful view of that catalog. |
search plus execute |
The API has many operations and schemas. | Progressive discovery reduces context size, at the cost of an additional discovery step. |
| Direct tool calls | One deterministic action or a few fixed calls. | Every intermediate result is exposed to the model. |
Cloudflare uses its large API MCP server as an example of the search-and-execute pattern. In a published comparison, Cloudflare reported 2,594 API tools requiring about 1,000 tokens with Code Mode, versus about 1,170,000 tokens for native full schemas and about 244,000 tokens for required parameters. Those are Cloudflare’s catalog figures, not a general benchmark.
Set up a remote browser workflow
- Create the Worker project and enable the current Code Mode runtime. Follow the current Cloudflare Code Mode and Browser Run documentation for package versions. The Browser Run examples configure a Browser binding and Worker Loader. The runtime must expose
CodemodeRuntime; the Vite plugin can generate that export automatically. - Attach Browser Run’s CDP connector. Your Code Mode host should make a typed
cdpclient available to generated code. Keep the browser session handle in the host, not in a prompt or tool result. - Choose session lifetime. A one-shot session is appropriate for an isolated inspection. Use a retained or durable session when a workflow must preserve login state, cookies or navigation between executions. Confirm the currently supported lifecycle in the Browser Run documentation because this beta surface can change.
- Expose only the operations the task needs. Typical methods include navigation, DOM inspection, element interaction, screenshots and evaluation of page state. Give each method a strict input schema and bounded output.
- Put authorization before side effects. Sandboxed code execution does not grant permission. Check the caller, target origin and requested action in the upstream handler or host callback before navigation, form submission, purchases, account changes or other external effects.
A Code Mode execution pattern
The following Worker-shaped example shows the control flow to implement with the current Cloudflare SDK. Method names and imports are intentionally kept at the connector boundary because Cloudflare marks Code Mode experimental and Browser Run beta; verify them against the versions you install.
export default {
async fetch(request, env) {
// Authenticate the caller before creating a browser session.
const input = await request.json();
if (input.origin !== "https://example.com") {
return new Response("origin not allowed", { status: 403 });
}
// The host creates a Browser Run session and exposes its typed CDP client.
const session = await env.BROWSER.createSession({
purpose: "read-only product check"
});
const cdp = session.cdp;
// This is the program Code Mode gives to the sandboxed runtime.
const result = await session.runCode(async (tools) => {
await tools.cdp.navigate({ url: input.url });
await tools.cdp.waitForNetworkIdle({ timeoutMs: 10000 });
const title = await tools.cdp.evaluate({
expression: "document.title"
});
const links = await tools.cdp.evaluate({
expression: "[...document.querySelectorAll('a')].slice(0, 20).map(a => ({text:a.innerText, href:a.href}))"
});
return {
title,
links: links.filter(link => link.text && link.href)
};
});
await session.close();
return Response.json(result);
}
};
In production, replace the illustrative session methods with the current Browser Run connector API, validate input.url against an allowlist, cap navigation and evaluation time, and limit returned text. Never return cookies, authorization headers, page credentials or unrestricted DOM dumps to the model.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Wrapping your own MCP server
For a small, existing tool catalog, Cloudflare’s single-tool pattern uses codeMcpServer(). The current guide says this returns an SDK v1 server and should be served with the explicit legacy createLegacyMcpHandler API. Treat both details as version-sensitive: pin compatible packages and re-check the guide before deployment.
// Illustrative structure; use the imports and adapter versions in the current guide.
const server = codeMcpServer({
tools: {
getPageText: async ({ url }) => {
await assertAllowedOrigin(url);
return browser.getPageText({ url });
},
clickAndRead: async ({ selector }) => {
await assertUserApproval("click", selector);
return browser.clickAndRead({ selector });
}
}
});
// Serve with the explicit legacy adapter required by the current SDK guide.
export default createLegacyMcpHandler(server);
The important boundary is not the wrapper itself: every handler must enforce authorization, validate arguments and remove secrets from schemas and results.
Using search and execute for a large catalog
- Have the model search for the narrow capability it needs, such as browser navigation or accessibility-tree inspection.
- Return only matching operation names, descriptions and required arguments.
- Let Code Mode call those typed methods, compose their results and shape a small response.
- Reject unknown operations and enforce per-operation permissions in the executor.
This approach prevents a full API schema from consuming the model’s context and makes it easier to deny dangerous operations centrally.
Do not confuse remote automation with browser-owned tools
@cloudflare/codemode/browser is for tools owned by the visitor’s browser page. You define browser tools with schemas and implementations, construct createBrowserCodeTool() with an IframeSandboxExecutor, and execute the descriptor in the client. This is suitable for reading a page selection or local application state. It runs in a sandboxed iframe and does not control a remote browser.
Choose Browser Run when the target page must be opened and operated remotely. Choose the browser-owned integration when the capability or state already lives in the user’s own tab.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Portal configuration
Cloudflare MCP portals can expose Code Mode through search and execution tools running in an isolated Dynamic Worker. The portal documentation describes the default policy as Opt-in; administrators can also disable the feature or enable it by default. For an opt-in portal, the documented connection form adds ?codemode=search_and_execute to the portal URL. Authentication and policy settings are administrator-specific, so inspect the account’s current configuration rather than assuming the default.
Security checklist for browser agents
- Authenticate the MCP caller before opening a session.
- Allowlist destination origins and block private-network targets unless explicitly required.
- Keep credentials in host bindings or secret storage; never place them in generated code, schemas or model-visible results.
- Require approval for writes, downloads, purchases, account changes and form submissions.
- Limit navigation count, script runtime, response size and screenshot dimensions.
- Redact cookies, tokens, passwords and personal data from logs.
- Close one-shot sessions and expire retained sessions deliberately.
- Pin package versions and test after Cloudflare updates because Code Mode is experimental and may introduce breaking changes.
Troubleshooting
The model can call tools but the page never changes
Check that the workflow uses Browser Run’s CDP connector, not @cloudflare/codemode/browser. Confirm a live browser session exists and that navigation is awaited before the next operation.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →CodemodeRuntime is missing
Export it from the Worker runtime or enable the Vite plugin that supplies the export. Then rebuild and redeploy the Worker.
The adapter reports an SDK mismatch
codeMcpServer() currently returns an SDK v1 server in Cloudflare’s guide. Serve it with the documented createLegacyMcpHandler adapter and pin compatible package versions.
Results are too large or the model times out
Move loops and filtering into Code Mode, return only selected fields, cap DOM text and use search-before-execute for large catalogs. Set explicit navigation, network-idle and evaluation timeouts.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
A dangerous action was executed
Do not rely on the sandbox for permission. Add authorization and approval in the host callback or upstream tool handler, and remove side-effecting methods from read-only roles.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteA retained session lost its state
Check whether the run created a fresh one-shot session. Use the currently supported durable or retained lifecycle, persist the session identifier securely and handle expiry by re-authenticating.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
If your goal is a clean screenshot rather than interactive browser control, ScreenshotNeo provides a single HTTP request. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups and chat widgets. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing result. It also offers an MCP server with take_screenshot, get_page_info and capture_pdf for Claude, Cursor and other MCP clients.
See the ScreenshotNeo API documentation for all options, including full-page and element capture, device presets, dark mode, retina scale, PDF controls, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, geolocation, caching, signed links, asynchronous webhooks, bulk capture and usage reporting.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
The Free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 shots; every feature is on every plan. Create a free ScreenshotNeo account.
Free tools Windows power users keep installed
One-click scans. No signup required.
Frequently Asked Questions
Is Code Mode a browser automation library?
No. It is a model-to-tool execution pattern. Browser Run and its CDP connector provide the remote browser capabilities.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
When should I keep direct MCP calls?
Use direct calls for a simple, fixed operation where exposing the intermediate result is acceptable; use Code Mode for composition, loops, branching or discovery.
Can browser-owned Code Mode tools log in to a remote site?
No. The browser-owned integration runs inside the user’s page. Remote inspection and automation require Browser Run.
Is Cloudflare Code Mode production-stable?
Cloudflare labels Code Mode experimental and Browser Run beta. Verify current APIs and test upgrades before relying on them in production.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
The Bottom Line
For remote browser automation, combine Code Mode with Browser Run’s CDP connector, enforce authorization outside generated code, and select a one-shot or retained session deliberately. Use the browser-owned integration only for tools inside the visitor’s own page.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

