Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,10 @@ The core innovation: instead of 2,500 MCP tools (~244K tokens), two tools handle
- `src/events/callback.ts` opens the sealed destination secret ANS presents, checks the KV subscription record and synchronously signs the MCP callback, with no Cloudflare API call. ANS owns retries.
- `npm run test:events` runs local workerd coverage with simulated external HTTP endpoints. See `docs/mcp-events.md` for live tests and lifecycle constraints.

### Asset upload tokens

`GlobalOutbound` checks the configured API origin and base path before selecting credentials for any `execute` request. The four asset upload POSTs (`/pages/assets/check-missing`, `/pages/assets/upload`, `/pages/assets/upsert-hashes`, `/accounts/{account_id}/workers/assets/upload`) require the upload JWT rather than the MCP session token. `src/asset-upload-token.ts` checks shape and expiry; the upload API owns signature and upload-scope validation. The proxy rejects missing or unusable JWTs without sending the request, does not follow redirects or retry network failures, and skips MCP scope refusal review for these requests. All other requests keep session authentication and policy checks.

### Worker Loader API

Code execution uses Cloudflare's Worker Loader API to dynamically create isolated worker instances. The API token is passed via props (never enters user code isolate). A `globalOutbound` service restricts network access.
Expand All @@ -189,7 +193,7 @@ The consent page offers minimal, read-only and full-access templates. Minimal is
- Forge merges operations that exist under both accounts and zones into `/{account_or_zone}/{account_or_zone_id}/…`; `processSpec` splits each back into its `/accounts/{account_id}/…` and `/zones/{zone_id}/…` paths, so Code Mode sees paths it can call as written and `execute` finds an endpoint's permissions by the path it calls. Since cloudflare/forge#59 (`openapi@fdbc7d9`), the document gives `account_or_zone` its `accounts`/`zones` enum; `cf` fills it from `--zone`
- All `$ref` references resolved inline before storage
- `openapi.forge.json` describes each response body as the API sends it: in Cloudflare's envelope (`{ success, errors, messages, result }`, plus `result_info` on lists), or bare for the few APIs without one. Releases before `openapi@d8e3026` (30 October 2026) left the envelope out of most success schemas; nothing here supports them any more. Nothing rewrites a response or its schema: `spec.json` keeps each schema as it is, `cloudflare.request()` returns the body as it is (JSON parsed, text as a string, binary as a `Uint8Array`, GraphQL as `{ data, errors? }`) and throws for a failed request, and the direct tools check and return the body as it is (see Envelope under Response schema checks)
- `cloudflare.request()` takes what an operation declares the way `fetch` does: `{ method, path, query, headers, body }`. `headers` carries the spec's header parameters (`cf-r2-jurisdiction`, `If-Match`), and `GlobalOutbound` always replaces `Authorization` with the session's token. The body's JavaScript type alone decides how it is sent: a string, bytes, `Blob`, `FormData`, `URLSearchParams` or stream as it is, anything else as JSON. `Content-Type` defaults to `application/json` for JSON and strings, and `FormData` always gets `fetch`'s own. Nothing sniffs a string: Zaraz publish, the one endpoint whose JSON body is a string, needs `JSON.stringify`. `contentType` and `rawBody` are honoured but no longer documented. `tests/execute-requests.test.ts` sends every header parameter and request media type the spec declares
- `cloudflare.request()` takes what an operation declares the way `fetch` does: `{ method, path, query, headers, body }`. `headers` carries the spec's header parameters (`cf-r2-jurisdiction`, `If-Match`), and `GlobalOutbound` selects credentials as described under Asset upload tokens. The body's JavaScript type alone decides how it is sent: a string, bytes, `Blob`, `FormData`, `URLSearchParams` or stream as it is, anything else as JSON. `Content-Type` defaults to `application/json` for JSON and strings, and `FormData` always gets `fetch`'s own. Nothing sniffs a string: Zaraz publish, the one endpoint whose JSON body is a string, needs `JSON.stringify`. `contentType` and `rawBody` are honoured but no longer documented. `tests/execute-requests.test.ts` sends every header parameter and request media type the spec declares
- Products and minimal operation metadata extracted
- Three artifacts: `spec.json`, `products.json`, and `permissions.json`, each operation's `x-api-token-group` by path and method, which `execute` uses to explain a refused request
- A lone 2025-era `tools/list` for the direct tools is answered by `src/tools/tool-list-response.ts` from the listing encoded once per isolate, before the SDK sees it: the SDK's per-request `JSON.stringify` of the multi-MB listing was ~23% of the Worker's production CPU. Cursors, 2026-07-28 requests and anything unusual still go to the SDK, and `tests/tool-list-response.test.ts` checks both answers are identical
Expand Down
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,17 @@ execute({
});
```

### Static asset uploads

In Code Mode, mint the upload JWT with the MCP connection's credentials, then pass it as `Authorization: Bearer <jwt>` only on the asset POSTs. The outbound proxy applies the same authentication rules to `cloudflare.request()` and `fetch()`.

| Product | Get an upload JWT | Send assets with the JWT | Finish with MCP connection credentials |
| --- | --- | --- | --- |
| Pages | `GET /accounts/{id}/pages/projects/{project}/upload-token` | `POST /pages/assets/check-missing`, `/pages/assets/upload`, and `/pages/assets/upsert-hashes` | Create the Pages deployment with the multipart manifest. |
| Workers | `POST /accounts/{id}/workers/scripts/{script}/assets-upload-session` | `POST /accounts/{id}/workers/assets/upload?base64=true` with base64 file bytes in multipart `FormData` | Create the Worker version with the completion JWT in multipart metadata at `assets.jwt`. |

The proxy does not substitute the MCP credential for a missing or unusable upload JWT, follow upload redirects, or retry ambiguous network failures. Cloudflare validates the JWT and its upload scope. An upload authentication error does not prompt an MCP OAuth reconnect; use a fresh JWT for the intended project or Worker instead. Do not return JWTs in tool output or logs.

### GraphQL Analytics API

The server automatically detects and handles Cloudflare's GraphQL Analytics API endpoints. GraphQL queries work seamlessly through the same `execute` tool:
Expand Down
62 changes: 62 additions & 0 deletions src/asset-upload-token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { z } from 'zod'

const ASSET_UPLOAD_PATHS = new Set([
'/pages/assets/check-missing',
'/pages/assets/upload',
'/pages/assets/upsert-hashes'
])

const WORKERS_ASSET_UPLOAD_PATH = /^\/accounts\/[0-9a-f]{32}\/workers\/assets\/upload$/

const JWT_SEGMENT = /^[A-Za-z0-9_-]+$/

const CLOCK_SKEW_SECONDS = 60

const WORKERS_UPLOAD_TOKEN_PREFIX = 'cfwau_'

export function isAssetUploadPath(path: string): boolean {
return ASSET_UPLOAD_PATHS.has(path) || WORKERS_ASSET_UPLOAD_PATH.test(path)
}

const JwtObject = z.looseObject({})

const JwtClaims = z.looseObject({ exp: z.number() })

function decodeSegment(segment: string): string {
const base64 = segment.replaceAll('-', '+').replaceAll('_', '/')
return atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4))
}

function isUnexpiredJwt(token: string, nowSeconds: number): boolean {
const jwt = token.startsWith(WORKERS_UPLOAD_TOKEN_PREFIX)
? token.slice(WORKERS_UPLOAD_TOKEN_PREFIX.length)
: token
const segments = jwt.split('.')
if (segments.length !== 3 || !segments.every((segment) => JWT_SEGMENT.test(segment))) {
return false
}
try {
const header = JwtObject.safeParse(JSON.parse(decodeSegment(segments[0])))
const claims = JwtClaims.safeParse(JSON.parse(decodeSegment(segments[1])))
if (!header.success || !claims.success) {
return false
}
return claims.data.exp + CLOCK_SKEW_SECONDS > nowSeconds
} catch {
return false
}
}

export function assetUploadAuthorization(
request: Request,
path: string,
sessionToken: string,
nowSeconds: number = Date.now() / 1000
): { token?: string } | undefined {
if (request.method !== 'POST' || !isAssetUploadPath(path)) {
return undefined
}
const match = /^Bearer (\S+)$/.exec(request.headers.get('authorization') ?? '')
const token = match?.[1]
return token && token !== sessionToken && isUnexpiredJwt(token, nowSeconds) ? { token } : {}
}
56 changes: 42 additions & 14 deletions src/tools/execute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { authorize, explainRefusal, isCatalogScope } from '../api-permissions'
import { MISSING_SCOPE_HEADER, REFUSAL_HINT_HEADER, reviewResponse } from '../api-refusals'
import { policyRefusalHint, sameSubscription, subscriptionCreate } from '../policy-guards'
import type { SubscriptionKey } from '../policy-guards'
import { assetUploadAuthorization } from '../asset-upload-token'
import {
DECLINED_HINT,
NEEDS_CONFIRMATION_HEADER,
Expand Down Expand Up @@ -99,10 +100,17 @@ type GlobalOutboundProps = {
*/
export class GlobalOutbound extends WorkerEntrypoint<Env, GlobalOutboundProps> {
async fetch(request: Request): Promise<Response> {
const allowed = new URL(this.env.CLOUDFLARE_API_BASE).hostname
const requested = new URL(request.url).hostname
if (requested !== allowed) {
return new Response(`Forbidden: requests to ${requested} are not allowed`, { status: 403 })
const apiBase = new URL(this.env.CLOUDFLARE_API_BASE)
const requested = new URL(request.url)
const basePath = apiBase.pathname.replace(/\/$/, '')
if (
requested.origin !== apiBase.origin ||
(requested.pathname !== basePath && !requested.pathname.startsWith(`${basePath}/`))
) {
return new Response('Forbidden: request is outside the Cloudflare API base URL.', {
status: 403,
headers: { [NOT_SENT_HEADER]: '1' }
})
}
const policyHint = await policyRefusalHint(request, this.ctx.props.confirmedSubscription)
if (policyHint) {
Expand All @@ -122,28 +130,46 @@ export class GlobalOutbound extends WorkerEntrypoint<Env, GlobalOutboundProps> {
}
)
}
// Inject auth header — token comes from props, never enters user code isolate.
// It replaces any Authorization the code sent: appended, the two would be
// joined into one value the API can't read. The headers are rebuilt from
// their entries: in workerd, a copy made with new Headers(request.headers)
const path = requested.pathname.slice(basePath.length)
const { apiToken } = this.ctx.props
const upload = assetUploadAuthorization(request, path, apiToken)
if (upload && !upload.token) {
return new Response(
'This endpoint requires an upload JWT. Get one from the Pages upload-token or Workers assets-upload-session endpoint, then pass it as Authorization: Bearer <upload JWT>.',
{ status: 401, headers: { [NOT_SENT_HEADER]: '1' } }
)
}

// Appending Authorization would join two bearers into one unusable value.
// Rebuild from entries: in workerd, a copy made with new Headers(request.headers)
// lost every header but Authorization when fetchWithRetry copied it again.
const headers = new Headers([
...[...request.headers].filter(([name]) => name.toLowerCase() !== 'authorization'),
['Authorization', `Bearer ${this.ctx.props.apiToken}`]
['Authorization', `Bearer ${upload?.token ?? apiToken}`]
])
const authedRequest = new Request(request, { headers })
const authedRequest = new Request(request, {
headers,
redirect: upload ? 'manual' : request.redirect
})
// No 429 is retried here: the sandbox waits out rate limits, where the wait
// holds back the run's other requests and counts against its wait budget.
const response = await fetchWithRetry(authedRequest, undefined, {
caller: this.ctx.props.fetchWithRetryCaller,
retryRateLimited: false
retryRateLimited: false,
...(upload && { maxRetries: 0 })
})
if (upload && [301, 302, 303, 307, 308].includes(response.status)) {
const redirectHeaders = new Headers(response.headers)
redirectHeaders.delete('Location')
return new Response(response.body, { status: response.status, headers: redirectHeaders })
}

const basePath = new URL(this.env.CLOUDFLARE_API_BASE).pathname.replace(/\/$/, '')
const path = new URL(request.url).pathname.slice(basePath.length)
// What the response's rate limits ask of the run: the sandbox holds its
// next requests back for it, and tells the agent about a 429.
const noticed = await withRateLimitNotice(response, request.method, path)
if (upload) {
return noticed
}

// Cloudflare's 401/403 bodies don't say why, and some lists come back empty
// instead of refused. Report both as refusals with an explanation the
Expand Down Expand Up @@ -677,7 +703,9 @@ When the session has access to multiple accounts, pass account_id. ${ACCOUNT_DIS
To turn on a product for an account, such as R2, create an account subscription: POST /accounts/{account_id}/subscriptions with body { rate_plan: { id } }. Rate plan IDs include r2_paid (R2 Storage) and teams_free (Zero Trust). Only plans with no base charge can be created. The server asks the user to confirm first.

Your code must be an async arrow function that returns the result.
A failed request throws an Error naming the method, path, HTTP status and Cloudflare's errors. For HTTP 401/403 it also says which permission the endpoint needs and whether reconnecting will help. Requests slow down by themselves near a rate limit. For HTTP 429 the error says how long Cloudflare asks to wait; until then, requests under the same limit are not sent and throw too, so stop instead of catching and continuing.
A failed request throws an Error naming the method, path, HTTP status and Cloudflare's errors. For HTTP 401/403 on a request using the MCP connection, it also says which permission the endpoint needs and whether reconnecting will help. Requests slow down by themselves near a rate limit. For HTTP 429 the error says how long Cloudflare asks to wait; until then, requests under the same limit are not sent and throw too, so stop instead of catching and continuing.

For static assets, first get a JWT using the Pages project's GET upload-token or the Worker's POST assets-upload-session endpoint. Pass that JWT as Authorization: Bearer <upload JWT> only to the Pages asset POSTs (check-missing, upload, upsert-hashes) or the Workers assets/upload POST (multipart FormData with query: { base64: true }). Do not pass the JWT as authorization when creating a deployment or Worker version; the Workers upload completion JWT goes in version metadata at assets.jwt. An upload JWT refusal is not an MCP OAuth scope challenge.

Example: Worker with bindings (a multipart/form-data upload):
async () => {
Expand Down
122 changes: 122 additions & 0 deletions tests/asset-upload-token.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { describe, expect, it } from 'vitest'
import { assetUploadAuthorization, isAssetUploadPath } from '../src/asset-upload-token'

const NOW = 1_800_000_000
const SESSION = 'session-token'
const ACCOUNT = '0123456789abcdef0123456789abcdef'

function base64Url(value: object): string {
return btoa(JSON.stringify(value)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}

function jwt(claims: object): string {
return `${base64Url({ alg: 'HS256', typ: 'JWT' })}.${base64Url(claims)}.${base64Url({ test: true })}`
}

function post(token: string | undefined, method = 'POST'): Request {
return new Request('https://api.cloudflare.com/client/v4/pages/assets/upload', {
method,
headers: token === undefined ? {} : { authorization: `Bearer ${token}` }
})
}

describe('isAssetUploadPath', () => {
it.each([
'/pages/assets/check-missing',
'/pages/assets/upload',
'/pages/assets/upsert-hashes',
`/accounts/${ACCOUNT}/workers/assets/upload`
])('accepts %s', (path) => {
expect(isAssetUploadPath(path)).toBe(true)
})

it.each([
'/pages/assets/upload/extra',
'/pages/assets',
`/accounts/${ACCOUNT}/workers/scripts/app/assets-upload-session`,
`/accounts/${ACCOUNT}/pages/projects/site/upload-token`,
'/accounts/not-an-id/workers/assets/upload',
'/user/tokens'
])('refuses %s', (path) => {
expect(isAssetUploadPath(path)).toBe(false)
})
})

describe('assetUploadAuthorization', () => {
const valid = jwt({ exp: NOW + 300 })

it('keeps an unexpired upload JWT on an asset upload path', () => {
expect(assetUploadAuthorization(post(valid), '/pages/assets/upload', SESSION, NOW)).toEqual({
token: valid
})
})

it('keeps a cfwau_ Workers upload JWT with its prefix', () => {
const workers = `cfwau_${valid}`
expect(
assetUploadAuthorization(
post(workers),
`/accounts/${ACCOUNT}/workers/assets/upload`,
SESSION,
NOW
)
).toEqual({ token: workers })
})

it('ignores an expired cfwau_ JWT', () => {
expect(
assetUploadAuthorization(
post(`cfwau_${jwt({ exp: NOW - 120 })}`),
'/pages/assets/upload',
SESSION,
NOW
)
).toEqual({})
})

it('ignores the bearer on any other path', () => {
expect(
assetUploadAuthorization(post(valid), `/accounts/${ACCOUNT}/workers/scripts`, SESSION, NOW)
).toBeUndefined()
})

it('ignores the bearer on a GET', () => {
expect(
assetUploadAuthorization(post(valid, 'GET'), '/pages/assets/upload', SESSION, NOW)
).toBeUndefined()
})

it('ignores an expired JWT', () => {
expect(
assetUploadAuthorization(post(jwt({ exp: NOW - 120 })), '/pages/assets/upload', SESSION, NOW)
).toEqual({})
})

it('ignores a JWT without an expiry', () => {
expect(
assetUploadAuthorization(post(jwt({ sub: 'x' })), '/pages/assets/upload', SESSION, NOW)
).toEqual({})
})

it('ignores a bearer that is not a JWT', () => {
expect(
assetUploadAuthorization(post('someone-else'), '/pages/assets/upload', SESSION, NOW)
).toEqual({})
expect(assetUploadAuthorization(post('a.b.c'), '/pages/assets/upload', SESSION, NOW)).toEqual(
{}
)
})

it('ignores the session token itself', () => {
const session = jwt({ exp: NOW + 300 })
expect(assetUploadAuthorization(post(session), '/pages/assets/upload', session, NOW)).toEqual(
{}
)
})

it('ignores a request without Authorization', () => {
expect(assetUploadAuthorization(post(undefined), '/pages/assets/upload', SESSION, NOW)).toEqual(
{}
)
})
})
Loading