Skip to content

Commit 893f62c

Browse files
committed
Add Browser Rendering mcp server
1 parent d0866b1 commit 893f62c

14 files changed

Lines changed: 6376 additions & 1 deletion
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
CLOUDFLARE_CLIENT_ID=
2+
CLOUDFLARE_CLIENT_SECRET=
3+
DEV_DISABLE_OAUTH=
4+
DEV_CLOUDFLARE_API_TOKEN=
5+
DEV_CLOUDFLARE_EMAIL=
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
/** @type {import("eslint").Linter.Config} */
2+
module.exports = {
3+
root: true,
4+
extends: ['@repo/eslint-config/default.cjs'],
5+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# Setup
2+
3+
If you'd like to iterate and test your MCP server, you can do so in local development.
4+
5+
## Local Development
6+
7+
1. Create a `.dev.vars` file in your project root:
8+
9+
If you're a Cloudflare employee:
10+
11+
```
12+
CLOUDFLARE_CLIENT_ID=your_development_cloudflare_client_id
13+
CLOUDFLARE_CLIENT_SECRET=your_development_cloudflare_client_secret
14+
```
15+
16+
If you're an external contributor, you can provide a development API token:
17+
18+
```
19+
DEV_DISABLE_OAUTH=true
20+
# This is your global api token
21+
DEV_CLOUDFLARE_API_TOKEN=your_development_api_token
22+
```
23+
24+
2. Start the local development server:
25+
26+
```bash
27+
npx wrangler dev
28+
```
29+
30+
3. To test locally, open Inspector, and connect to `http://localhost:8976/sse`.
31+
Once you follow the prompts, you'll be able to "List Tools". You can also connect with any MCP client.
32+
33+
## Deploying the Worker ( Cloudflare employees only )
34+
35+
Set secrets via Wrangler:
36+
37+
```bash
38+
npx wrangler secret put CLOUDFLARE_CLIENT_ID -e <ENVIRONMENT>
39+
npx wrangler secret put CLOUDFLARE_CLIENT_SECRET -e <ENVIRONMENT>
40+
```
41+
42+
## Set up a KV namespace
43+
44+
Create the KV namespace:
45+
46+
```bash
47+
npx wrangler kv namespace create "OAUTH_KV"
48+
```
49+
50+
Then, update the Wrangler file with the generated KV namespace ID.
51+
52+
## Deploy & Test
53+
54+
Deploy the MCP server to make it available on your workers.dev domain:
55+
56+
```bash
57+
npx wrangler deploy -e <ENVIRONMENT>
58+
```
59+
60+
Test the remote server using [Inspector](https://modelcontextprotocol.io/docs/tools/inspector):
61+
62+
```bash
63+
npx @modelcontextprotocol/inspector@latest
64+
```

apps/browser-rendering/README.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Cloudflare Browser Rendering MCP Server 📡
2+
3+
This is a [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction) server that supports remote MCP
4+
connections, with Cloudflare OAuth built-in.
5+
6+
It integrates tools powered by the [Cloudflare Browser Rendering API](https://developers.cloudflare.com/browser-rendering/) to provide global
7+
Internet traffic insights, trends and other utilities.
8+
9+
## 🔨 Available Tools
10+
11+
Currently available tools:
12+
13+
| **Tool** | **Description** |
14+
| ---------------------- | ---------------------------------------------------------------------------- |
15+
| `get_url_html_content` | Retrieves the HTML content of the specified URL. |
16+
| `get_url_markdown` | Fetches the webpage content and converts it into Markdown format. |
17+
| `get_url_screenshot` | Captures a screenshot of the webpage. Optionally, specify the viewport size. |
18+
19+
**Note:** To use these tools, ensure you have an active account set. If not, use `accounts_list` to list your accounts and `set_active_account` to set one as active.
20+
21+
This MCP server is still a work in progress, and we plan to add more tools in the future.
22+
23+
### Prompt Examples
24+
25+
- `Get the HTML content of https://example.com.`
26+
- `Convert https://example.com to Markdown.`
27+
- `Take a screenshot of https://example.com.`
28+
29+
## Access the remote MCP server from from any MCP Client
30+
31+
If your MCP client has first class support for remote MCP servers, the client will provide a way to accept the server URL (`https://browser.mcp.cloudflare.com`) directly within its interface (for example in[Cloudflare AI Playground](https://playground.ai.cloudflare.com/)).
32+
33+
If your client does not yet support remote MCP servers, you will need to set up its resepective configuration file using mcp-remote (https://www.npmjs.com/package/mcp-remote) to specify which servers your client can access.
34+
35+
Replace the content with the following configuration:
36+
37+
```json
38+
{
39+
"mcpServers": {
40+
"cloudflare": {
41+
"command": "npx",
42+
"args": ["mcp-remote", "https://browser.mcp.cloudflare.com/sse"]
43+
}
44+
}
45+
}
46+
```
47+
48+
Once you've set up your configuration file, restart MCP client and a browser window will open showing your OAuth login page. Proceed through the authentication flow to grant the client access to your MCP server. After you grant access, the tools will become available for you to use.
49+
50+
Interested in contributing, and running this server locally? See [CONTRIBUTING.md](CONTRIBUTING.md) to get started.
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
{
2+
"name": "cloudflare-browser-mcp-server",
3+
"version": "0.0.1",
4+
"private": true,
5+
"scripts": {
6+
"check:lint": "run-eslint-workers",
7+
"check:types": "run-tsc",
8+
"deploy": "run-wrangler-deploy",
9+
"dev": "wrangler dev",
10+
"start": "wrangler dev",
11+
"types": "wrangler types --include-env=false",
12+
"test": "vitest run"
13+
},
14+
"dependencies": {
15+
"@cloudflare/workers-oauth-provider": "0.0.3",
16+
"@hono/zod-validator": "0.4.3",
17+
"@modelcontextprotocol/sdk": "1.10.2",
18+
"@repo/mcp-common": "workspace:*",
19+
"@repo/mcp-observability": "workspace:*",
20+
"agents": "0.0.67",
21+
"cloudflare": "4.2.0",
22+
"hono": "4.7.6",
23+
"zod": "3.24.2"
24+
},
25+
"devDependencies": {
26+
"@cloudflare/vitest-pool-workers": "0.8.14",
27+
"@types/node": "22.14.1",
28+
"prettier": "3.5.3",
29+
"typescript": "5.5.4",
30+
"vitest": "3.0.9",
31+
"wrangler": "4.10.0"
32+
}
33+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import type { UserDetails } from '@repo/mcp-common/src/durable-objects/user_details'
2+
import type { BrowserMCP } from './index'
3+
4+
export interface Env {
5+
OAUTH_KV: KVNamespace
6+
ENVIRONMENT: 'development' | 'staging' | 'production'
7+
MCP_SERVER_NAME: string
8+
MCP_SERVER_VERSION: string
9+
CLOUDFLARE_CLIENT_ID: string
10+
CLOUDFLARE_CLIENT_SECRET: string
11+
MCP_OBJECT: DurableObjectNamespace<BrowserMCP>
12+
USER_DETAILS: DurableObjectNamespace<UserDetails>
13+
MCP_METRICS: AnalyticsEngineDataset
14+
DEV_DISABLE_OAUTH: string
15+
DEV_CLOUDFLARE_API_TOKEN: string
16+
DEV_CLOUDFLARE_EMAIL: string
17+
}
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
import OAuthProvider from '@cloudflare/workers-oauth-provider'
2+
import { McpAgent } from 'agents/mcp'
3+
4+
import { createApiHandler } from '@repo/mcp-common/src/api-handler'
5+
import {
6+
createAuthHandlers,
7+
handleTokenExchangeCallback,
8+
} from '@repo/mcp-common/src/cloudflare-oauth-handler'
9+
import { handleDevMode } from '@repo/mcp-common/src/dev-mode'
10+
import { getUserDetails, UserDetails } from '@repo/mcp-common/src/durable-objects/user_details'
11+
import { getEnv } from '@repo/mcp-common/src/env'
12+
import { RequiredScopes } from '@repo/mcp-common/src/scopes'
13+
import { CloudflareMCPServer } from '@repo/mcp-common/src/server'
14+
import { registerAccountTools } from '@repo/mcp-common/src/tools/account'
15+
16+
import { MetricsTracker } from '../../../packages/mcp-observability/src'
17+
import { registerBrowserTools } from './tools/browser'
18+
19+
import type { AuthProps } from '@repo/mcp-common/src/cloudflare-oauth-handler'
20+
import type { Env } from './context'
21+
22+
const env = getEnv<Env>()
23+
24+
export { UserDetails }
25+
26+
const metrics = new MetricsTracker(env.MCP_METRICS, {
27+
name: env.MCP_SERVER_NAME,
28+
version: env.MCP_SERVER_VERSION,
29+
})
30+
31+
// Context from the auth process, encrypted & stored in the auth token
32+
// and provided to the DurableMCP as this.props
33+
type Props = AuthProps
34+
type State = { activeAccountId: string | null }
35+
36+
export class BrowserMCP extends McpAgent<Env, State, Props> {
37+
_server: CloudflareMCPServer | undefined
38+
set server(server: CloudflareMCPServer) {
39+
this._server = server
40+
}
41+
get server(): CloudflareMCPServer {
42+
if (!this._server) {
43+
throw new Error('Tried to access server before it was initialized')
44+
}
45+
46+
return this._server
47+
}
48+
49+
constructor(ctx: DurableObjectState, env: Env) {
50+
super(ctx, env)
51+
}
52+
53+
async init() {
54+
this.server = new CloudflareMCPServer({
55+
userId: this.props.user.id,
56+
wae: this.env.MCP_METRICS,
57+
serverInfo: {
58+
name: this.env.MCP_SERVER_NAME,
59+
version: this.env.MCP_SERVER_VERSION,
60+
},
61+
})
62+
63+
registerAccountTools(this)
64+
65+
// Register Cloudflare Log Push tools
66+
registerBrowserTools(this)
67+
}
68+
69+
async getActiveAccountId() {
70+
try {
71+
// Get UserDetails Durable Object based off the userId and retrieve the activeAccountId from it
72+
// we do this so we can persist activeAccountId across sessions
73+
const userDetails = getUserDetails(env, this.props.user.id)
74+
return await userDetails.getActiveAccountId()
75+
} catch (e) {
76+
this.server.recordError(e)
77+
return null
78+
}
79+
}
80+
81+
async setActiveAccountId(accountId: string) {
82+
try {
83+
const userDetails = getUserDetails(env, this.props.user.id)
84+
await userDetails.setActiveAccountId(accountId)
85+
} catch (e) {
86+
this.server.recordError(e)
87+
}
88+
}
89+
}
90+
91+
const BrowserScopes = {
92+
...RequiredScopes,
93+
'account:read': 'See your account info such as account details, analytics, and memberships.',
94+
'browser:write': 'Grants write level access to Browser Rendering.',
95+
} as const
96+
97+
export default {
98+
fetch: async (req: Request, env: Env, ctx: ExecutionContext) => {
99+
if (env.ENVIRONMENT === 'development' && env.DEV_DISABLE_OAUTH === 'true') {
100+
return await handleDevMode(BrowserMCP, req, env, ctx)
101+
}
102+
103+
return new OAuthProvider({
104+
apiRoute: ['/mcp', '/sse'],
105+
apiHandler: createApiHandler(BrowserMCP),
106+
// @ts-ignore
107+
defaultHandler: createAuthHandlers({ scopes: BrowserScopes, metrics }),
108+
authorizeEndpoint: '/oauth/authorize',
109+
tokenEndpoint: '/token',
110+
tokenExchangeCallback: (options) =>
111+
handleTokenExchangeCallback(
112+
options,
113+
env.CLOUDFLARE_CLIENT_ID,
114+
env.CLOUDFLARE_CLIENT_SECRET
115+
),
116+
// Cloudflare access token TTL
117+
accessTokenTTL: 3600,
118+
clientRegistrationEndpoint: '/register',
119+
}).fetch(req, env, ctx)
120+
},
121+
}

0 commit comments

Comments
 (0)