RFC-0048: Signed upload links for agents
- Status: Accepted (2026-11-29, by Halil), with every open question’s recommended answer; see “Decisions (2026-11-29)”.
- Author: Halil (Madraka), drafted with Claude · Date: 2026-11-29
- Related:
- #250 is the issue. Its option 3 (
sha256onupload_asset) shipped in #299. This RFC is option 1, which the owner approved for an RFC on 2026-11-29. - RFC-0004 is assets and media: §5.2 the pipeline, §5.5 Studio’s upload tickets, §5.6 the agent tools, §6.3 policy. RFC-0005 is roles: I14, I15 and §10.1. RFC-0036 is the playground. RFC-0044 is MCP OAuth. RFC-0047 is self-host on workerd. RFC-0008 is runs, taint and budgets.
- ADR-0004 (MCP, layered approval), ADR-0011 (policy engine), ADR-0014 (out-of-band approvals), ADR-0015 (agent modes).
- #250 is the issue. Its option 3 (
- Code read:
packages/api/src/scopes.ts(ROUTE_SCOPES,routeGuard) andpackages/api/src/playground.ts(DENY,PLAYGROUND_ALLOW)packages/api/src/routes/assets.ts(POST /assets/uploads,PUT /assets/uploads/:uploadId,UPLOAD_LIMITS) andpackages/api/src/uploads.ts(signUploadTicket)packages/api/src/app.ts(whereuploadSecretcomes from)packages/mcp-server/src/asset-tools.ts(upload_asset,dailyLimit),field-hints.tsandcommon.ts(ToolErrorCode)packages/core-ts/src/media/types.ts(MEDIA_TYPES,MEDIA_LIMITS) andpackages/core-ts/src/assets.ts(media_uploads, leases,collectMediaGarbage)
- Sources (checked 2026-11-29). Each claim used below is cited where it is used.
- AWS S3:
- Cloudflare R2:
- Cloudflare Workers: limits.
- Cloudflare Images: direct creator upload.
- Sanity: HTTP Assets API.
- Contentful:
- Contracts: no JSON Schema in
packages/core-contractschanges. The new MCP tool schemas and the REST route are public interfaces, so they are specified here (§5).
Summary
An agent gets media into a site today in one of two ways. It can paste the file into upload_asset as base64, which cost about 32,000 characters for a 24 KB cover in #250. Or it can name a public https URL for fetch_asset_url. This RFC adds a third way:
create_uploaddeclares the file’s name, size, type and SHA-256 and returns a single-use PUT link that lasts 10 minutes.- The agent’s shell PUTs the bytes to that link. The bytes never pass through the model’s context.
complete_uploadturns the verified bytes into an asset, through the same pipeline, policy and audit asupload_asset.
The link is a narrow, deliberate exception to “agents are refused on REST” (RFC-0005 I15 and §10.1). It is safe because it is bound to one site, one upload, one method, one exact size, type and SHA-256. It can upload only the file the agent declared.
Motivation
- The problem.
- Base64 in a tool call is slow and costly. It also corrupts easily: one changed character still decodes. #299 turned silent corruption into a clear error, but the cost stays: every byte is model output, about 1.33 characters per byte.
upload_assetstops at 4 MB (MEDIA_LIMITS.uploadAsset). A short video or a podcast episode cannot go in that way.fetch_asset_urlneeds a public https URL, which an agent working on local files rarely has.
- Who is affected. Every agent that adds covers, figures, audio or datasets: Claude Code, Codex and Cursor with a shell, and automation runs whose worker has the files on disk.
- Why now. Studio has had this exact mechanism since RFC-0004 §5.5: signed, single-use tickets and a streamed PUT. Only the policy rule keeps agents out. Agent-written content is the platform’s core (RFC-0020), and media is where it is weakest.
Proposal
1. The flow
agent ──create_upload {siteId, filename, bytes, mediaType, sha256, alt…}──▶ /mcp ◀── {status:"upload", uploadId, url, method:"PUT", headers, expiresAt, curl}shell ──PUT url (Content-Type, Content-Length = bytes, raw body)──▶ admin Worker / Node API ◀── 200 {uploadId, state:"received", sha256, bytes, mediaType}agent ──complete_upload {siteId, uploadId}──▶ /mcp ◀── {asset, existing, url, usage, snapshot} (the shape upload_asset returns)- Dedupe. When the declared SHA-256 is already in the site’s library (
assetForUploadedContent, the check Studio runs),create_uploadanswers{status: "existing", asset}. No link is made and nothing is transferred. - What the PUT does. It verifies the bytes and stores them. It does not create the asset (§2.5).
- What
complete_uploaddoes. It re-checks policy, creates the asset node, takes the snapshot and writes the audit row, asupload_assetdoes today.
2. The link
2.1 Shape
PUT https://<admin origin>/api/sites/<siteId>/assets/agent-uploads/<uploadId>?sig=<43 base64url chars>Content-Type: <the declared mediaType>Content-Length: <the declared bytes><admin origin>is the deployment’s configured base URL when it has one: the admin Worker’s custom domain, or--base-url/CLOUDHAL_BASE_URL. Otherwise it is the origin of the/mcprequest that made the link. A client-sentHosttherefore only changes the link handed back to that same client.- The authority is the
media_uploadsrow. The upload id is not a secret. The signature makes a link whose parts were changed useless, and the row decides everything else: single use, expiry and actor.
2.2 Signing and key rotation
- The MAC. HMAC-SHA-256 with the construction of
uploads.ts: WebCrypto, base64url, constant-timeverify. The key is derived from the deployment’s upload secret by HMAC under the labelcloudhal agent upload v1. Studio’s tickets usecloudhal upload ticket v1, so neither kind of ticket verifies on the other’s route. - The signed payload is
purpose = "agent",uploadId,siteId,actor kind:id,method = "PUT",bytes,mediaType,sha256andexpiresAt, joined by\n. - The secret.
- Today
app.tsuses the first ofpreview.secretandmcp.stateKeythat has 32 bytes or more. - This RFC adds an optional
CLOUDHAL_UPLOAD_SECRETthat takes precedence, so the upload key can rotate without breaking preview links. - Without any shared secret the API signs with a random key of its own process. That is fine for one process, but on Cloudflare a link minted in one isolate could fail in another. So agent uploads are advertised only when a shared secret exists, or when the server is one process (
cloudhal studio) (“Capability flag” under Compatibility & migration).
- Today
- Rotation. Links live 10 minutes, so rotation needs no key ring. Change the secret, and the only casualty is links that have not been used yet: they answer
403 bad_signature, and the agent callscreate_uploadagain. Bytes that were already received are not affected, because completion checks the row, not the signature. The guide says so. Akidinsigis left for when links live longer (open question 9).
2.3 Scope: what one link can do
- One site:
siteIdis in the path, the payload and the row, and the handler compares all three. - One upload:
uploadId. - One method:
PUT. Every other method answers 405.GETnever reveals whether an upload exists. - One exact size.
Content-Lengthmust equalbytes. The body is read through the existinglimited(body, bytes)stream, and a short or long body is refused. - One type. The
Content-Typeheader must equal the declaredmediaType, ignoring parameters such ascharset. The stored and served type always comes from sniffing and theMEDIA_TYPEStable (RFC-0004 §5.2), never from the header. - One content. The SHA-256 of the received bytes must equal the declared
sha256. It is required for agents (open question 1). - One actor. The upload is credited to the key that created it, and the PUT never acts as anyone else. Cookies and credentials on the PUT are ignored, with one exception: when an agent key or OAuth token is present, it must be that same actor’s, or the PUT answers
403 not_your_upload.
2.4 Expiry and single use
- Expiry.
expiresAtis 10 minutes after creation. It is the deadline for starting the PUT, the same rule as Studio’s tickets, whereclaimUploadTicketruns before any byte is read. A large file on a slow link therefore does not fail halfway. - States. The row goes
open → receiving → received → completed. Each step is a CAS (UPDATE … WHERE state = ?). A second PUT while the row isreceiving,receivedorcompletedanswers410 upload_used. - Failed PUTs. When a PUT fails verification (size, type or checksum), the row goes back to
openwithattempts + 1, at most 3 attempts and only beforeexpiresAt. A dropped connection then does not cost a new approval inmanualmode. Only the declared bytes can ever succeed, so a retry gives nothing away. - Completion window. Received bytes wait for
complete_uploaduntil 60 minutes after creation (completeBy). After that the upload is abandoned (§3.3).
2.5 Where the bytes go, per host
The PUT is proxied through the API on every host: the admin Worker on Cloudflare, the admin Worker on workerd for self-host, and the Node API of cloudhal studio. One code path serves all three, and it is today’s Studio PUT handler with an agent ticket. “Alternatives considered” explains why direct presigned URLs are not in v1.
- What the PUT runs. It runs the RFC-0004 §5.2 pipeline up to the blob write.
- Images (at most 20 MB) are buffered, sniffed, size-checked, hashed and stripped of metadata.
- Other types stream through
putStreamwith the declared SHA-256 verified. - The blob is written under its content address with a lease until
completeBy. The row records the result: finalsha256,originalSha256,bytes, sniffedmediaTypeand warnings.
- What
complete_uploadadds. It inserts the node in one guardedbatch(). The batch asserts the blob row is stillstoredand leased by this upload (RFC-0004 invariant 3), so nothing is written twice and garbage collection can never take a blob that is being completed. - Cloudflare. The route lives on the admin Worker. Its request body limit depends on the zone’s plan: 100 MB on Free and Pro, 200 MB on Business, and up to 5 GB on Enterprise (Workers limits). An isolate has 128 MB of memory, so only images (20 MB or less) are ever buffered.
- Self-host on workerd. The same admin Worker writes through its
BLOBSbinding, which is R2 over the cluster’s S3 store (RFC-0047 §6). The S3 store stays private on the compose or cluster network and is never exposed to agents. The guide tells operators that a reverse proxy in front must allow bodies up to the agent cap, because proxies’ default limits are often below 25 MB. - Local.
cloudhal studio(Node, HTTP/mcp) serves the same route against thefsblob store.cloudhal mcp(stdio) has no HTTP listener, souploads.signedUrlisfalsethere (“Capability flag” under Compatibility & migration).cloudhal devis a preview server with no API, so nothing changes there.
3. Policy, audit and limits
3.1 Scope, modes, approvals and runs
- Scope.
create_uploadneedsasset:upload. The brief saysassets:write, but that scope does not exist.asset:uploadis RFC-0005’s scope for “upload assets and edit own uploads”, whichupload_assetandfetch_asset_urluse, and whichasset:manageimplies.complete_uploadneedsasset:uploadtoo, and only the key that created the upload may complete it.
- Modes (ADR-0015) apply to
create_uploadexactly as toupload_asset:plan: refused.manual: the call waits for a person (ADR-0014). The prompt names the file, size, type, the first 12 hex digits of the SHA-256 and the site: “Add media “Ferries at dawn” (ferries.webp, 24 KB, image/webp, sha256 3f2a…) to “Harbour News”? It becomes public only when the site is published.”edits,auto,bypass: free. Publishing still decides visibility (RFC-0004 §6.3).
- What an approval binds. The link is minted only by an allowed call, and its row carries every declared value. So an approval covers exactly that file.
complete_uploadasks for no second approval. - Re-checks at completion.
complete_uploadre-checks the key: it is still active, its effective scopes still holdasset:upload(RFC-0005 I5), and its mode is notplan. A key revoked or narrowed in between completes nothing. The leased blob is then collected like any abandoned upload. - Automation runs (RFC-0008 §11).
create_uploadhasupload_asset’s run class.- The declared bytes count against the run’s budget when the link is created.
- The taint rule applies to both tools as it applies to
upload_asset. complete_uploadoutside the run window that created the upload answersoutside_run.
3.2 Audit
- Tool calls. Both calls are audited by the tool layer as usual.
auditArgskeepsfilename,bytes,mediaType,sha256and the text fields. The audit row never holds the link orsig(the rule of RFC-0005 I14, applied to upload links). asset.upload-received, one row per accepted PUT. The actor is the upload’s agent andsite_idis the upload’s site.inputis{uploadId, bytes, sha256, mediaType, attempts, metadataStripped?}.- Refused PUTs are not audited, so a flood cannot fill the audit log. They count on the row (
attempts) and in the Worker log. The request log redacts thesigquery parameter on this route. complete_uploadwrites theeffect: {asset: {id, sha256, bytes, mediaType, source}}row of RFC-0004 §6.3, withsource.kind: "upload"andinput.via: "signed-upload".
3.3 Rate limits, quotas and cleanup
| Limit | Default | Where |
|---|---|---|
| Agent upload cap per file | 25 MB (media.agentUploadBytes, operator setting, ≤ 100 MB, ≤ the type’s MEDIA_TYPES cap) |
create_upload |
| Open uploads per agent key | 10 (open + receiving + received) |
create_upload, counted in the same insert guard as openUploadTickets |
| Open uploads per site, all actors | 50 | same guard |
| Per key per 24 h | dailyLimit: 100 files and 500 MB, now counting open uploads’ declared bytes too |
create_upload and complete_upload |
| Per site stored bytes | MEDIA_LIMITS.siteQuota (10 GB), declared bytes reserved by open uploads |
create_upload, re-checked at completion |
| Calls | the existing per-key MCP rate limit | /mcp |
- Expired rows. Rows past
expiresAtthat never received bytes are deleted by the existing sweep inopenUploadTickets(DELETE FROM media_uploads WHERE expires_at < ?), extended to agent rows. - Abandoned bytes. Rows that received bytes but were never completed lose their lease at
completeBy. Their blob then has no node and no lease, socollectMediaGarbagetakes it after the 24 h grace (RFC-0004 invariant 10). No new job is needed. The row goes toabandonedand is deleted with the next sweep.
4. Threat model
| Threat | Mitigation | Residual |
|---|---|---|
| A leaked link (chat transcript, shell history, CI log, proxy log) | Bound to the exact SHA-256, size, type, site and actor, single use, and 10 minutes to start. Anyone holding it can upload only the file the agent declared, and they would need its bytes to do so. Our own logs redact sig. |
Someone who sees the link before it is used can burn its attempts with wrong bytes. That is a denial of service on one upload, after which the agent calls create_upload again (in manual mode a person approves again). |
| Replay | Claimed by CAS before any byte is read. received and completed rows refuse further PUTs (410 upload_used). complete_upload is idempotent: a second call returns the same asset with existing: true and takes no second snapshot. A link replayed against another site or upload fails the signature and the row check. |
None known. |
| Content-type confusion | The declared type must be an agent type: MEDIA_TYPES without peopleOnly, so no SVG, and HTML is not in the table at all. Content-Type must match the declared type. The bytes are sniffed, and a mismatch between sniffed and declared type is refused (415 type_mismatch). The served type comes from the table, with RFC-0004’s nosniff, disposition and CSP headers. |
As today: a file can be valid as two formats (a polyglot). Serving from a separate media origin with nosniff contains it. |
| Oversize | Refused at create_upload above the cap. Content-Length must equal bytes, and the read is capped at bytes, so a chunked or lying body stops at the cap. On Cloudflare the edge also enforces the plan’s body limit. |
None. |
| Decompression bombs | The PUT never decodes: any Content-Encoding other than identity is refused (415 encoding_refused), and the byte count is of the bytes read. Images are checked for side and total pixels from the header before any work (MEDIA_LIMITS.maxImageSide, maxImagePixels). No accepted type is an archive that the server unpacks. |
Parquet and ZIP-based formats are stored, never unpacked, as today. |
| SSRF | None: the server never fetches anything on this path. The link points at the deployment’s own origin, and the client sends the bytes. | None. |
| Cross-site PUT from a browser | The route sends no CORS headers. A PUT with a non-simple Content-Type needs a preflight, which fails. Cookies are ignored. |
None. |
| The playground | /mcp is already refused in a playground ("mcp"), and the new route is added to DENY as "uploads". test/playground.test.ts walks every ROUTE_SCOPES entry, so an unclassified route fails CI. The playground principal does not hold asset:upload (RFC-0036 §5). |
None. |
| The agent-key holder | Gets nothing beyond upload_asset: the same scope, mode, approval, budget and quotas. Only the size grows, up to the operator’s cap. Sharing the link is equivalent to sharing a file the holder already has. |
A key holder can fill the site’s quota up to the daily and site limits, as with upload_asset and fetch_asset_url today. |
| Guessing or forging links | The 256-bit HMAC is checked in constant time, and the row must exist with matching fields. An unknown upload answers 404, the same as a wrong site, so the route cannot be used to probe for uploads. |
None. |
| Takedown bypass | create_upload refuses a purged SHA-256 (410 purged), and the PUT checks again after hashing. |
None. |
Edits to docs/security/threat-model.md come with the implementation. The Agent row in Principals changes from “MCP tools only” to “MCP tools only, plus one PUT per upload link those tools mint”. The threats above become an “Agent uploads (RFC-0048)” table.
5. Contracts
5.1 MCP tools
Both tools keep to the strict structured-output profile already used by fieldsSchemaStrict (RFC-0045): every property is listed in required, and an optional value is sent as null. Every object has additionalProperties: false, there is no oneOf, and every enum is a short string enum. A client in a provider’s strict mode can therefore send and parse them unchanged. Clients outside strict mode may leave the null keys out.
// create_upload: input{ "type": "object", "additionalProperties": false, "required": ["siteId","filename","bytes","mediaType","sha256","alt","decorative","title","caption","credit","license","slug"], "properties": { "siteId": { "type": "string" }, "filename": { "type": "string", "minLength": 1, "maxLength": 255, "pattern": "^[^/\\\\\\u0000-\\u001f\\u007f]+$" }, "bytes": { "type": "integer", "minimum": 1, "maximum": 104857600 }, // the server's cap may be lower "mediaType": { "type": "string", "enum": ["image/jpeg","image/png","image/webp","image/avif","image/gif","video/mp4", "…every agent type of MEDIA_TYPES"] }, "sha256": { "type": "string", "pattern": "^[0-9a-fA-F]{64}$" }, "alt": { "type": ["string","null"], "maxLength": 1000 }, "decorative": { "type": ["boolean","null"] }, "title": { "type": ["string","null"] }, "caption": { "type": ["string","null"] }, "credit": { "type": ["string","null"] }, "license": { "type": ["string","null"] }, // the values upload_asset takes "slug": { "type": ["string","null"], "pattern": "^[a-z0-9]+(?:-[a-z0-9]+)*$", "maxLength": 96 } }}// create_upload: output{ "type": "object", "additionalProperties": false, "required": ["status","uploadId","url","method","headers","expiresAt","completeBy","curl","asset"], "properties": { "status": { "type": "string", "enum": ["upload","existing"] }, "uploadId": { "type": ["string","null"] }, "url": { "type": ["string","null"] }, "method": { "type": ["string","null"], "enum": ["PUT", null] }, "headers": { "type": ["object","null"], "additionalProperties": false, "required": ["content-type"], "properties": { "content-type": { "type": "string" } } }, "expiresAt": { "type": ["string","null"], "format": "date-time" }, // start the PUT before this "completeBy":{ "type": ["string","null"], "format": "date-time" }, "curl": { "type": ["string","null"] }, // curl --fail-with-body -X PUT -H 'content-type: …' --upload-file <path> '<url>' "asset": { "type": ["object","null"] } // status "existing": the asset, as upload_asset returns it }}// complete_upload: input{ "type": "object", "additionalProperties": false, "required": ["siteId","uploadId"], "properties": { "siteId": { "type": "string" }, "uploadId": { "type": "string" } } }// complete_upload: output is upload_asset's ASSET_OUT unchanged: {asset, existing, url, usage, snapshot?}- Required versus null. An image needs
altordecorative: true, whichrequireAltchecks from the declared type atcreate_upload. A missingsha256is a schema error, never a silent skip. - The description of
create_uploadnames the hash commands, because they differ per OS:shasum -a 256 <file>on macOS,sha256sum <file>on Linux, andGet-FileHash -Algorithm SHA256 <file>in PowerShell. It also says to useupload_assetfor small files when the agent has no shell. - Annotations.
create_upload:readOnlyHint: false,openWorldHint: false,idempotentHint: false.complete_upload:idempotentHint: true.
- Listing and docs.
tools/liststays complete and deterministic (ADR-0004). The README tool table is regenerated withscripts/mcp-tools-doc.ts.
5.2 REST route
export type RouteRequirement = "public" | "deploy-token" | "signed-in" | "member" | "owner" | "upload-link" | Scope;// RFC-0048: an agent's upload link. The link is the credential; the handler verifies it against its row.["PUT", `${A}/agent-uploads/:uploadId`, "upload-link"],- The route guard.
routeGuardtreatsupload-linklikepublicfor authentication: it reads no session and refuses no agent. The handler is the only thing that authorizes. The route-enumeration test gains one assertion:upload-linkappears on this route and on no other. - Answers. Every answer is JSON in the
apiErrorshape{error, message, …details}:
| Status | error |
When |
|---|---|---|
| 200 | — | {uploadId, state: "received", sha256, bytes, mediaType, warnings} |
| 400 | size_mismatch |
Content-Length or the body differs from bytes |
| 400 | checksum_mismatch |
received SHA-256 ≠ declared (details: {expected, actual}) |
| 403 | bad_signature |
sig missing or wrong |
| 403 | not_your_upload |
a credential of another actor was sent |
| 404 | upload_not_found |
no such upload on this site |
| 405 | method_not_allowed |
anything but PUT |
| 409 | retry |
the blob is being collected (RFC-0004 §4.5), try again |
| 410 | upload_used / upload_expired / too_many_attempts |
single use, expiry, 3 failed attempts |
| 410 | purged |
the SHA-256 was taken down |
| 413 | too_large |
above the cap (also answered early from Content-Length) |
| 415 | type_mismatch / unsupported_type / encoding_refused |
header ≠ declared, sniffed ≠ declared or not an agent type, Content-Encoding |
5.3 MCP error codes and hints
The MCP side uses existing ToolErrorCodes with a details.reason. The hints sit next to field-hints.ts in a new upload-hints.ts, because of the size ratchet’s rule of one responsibility per module. mapError consults them the way it consults fieldHint.
Code / reason |
Tool | Hint (the agent’s next step) |
|---|---|---|
invalid / checksum_required |
create | “compute the file’s SHA-256 (shasum -a 256 / sha256sum / Get-FileHash) and pass it as sha256” |
too_large / upload_cap |
create | “this server takes agent uploads up to {cap}; ask a person to upload it in Studio, or use fetch_asset_url for a public file” |
invalid / unsupported_type |
create | “agents may upload {types}; SVG and HTML are refused” |
denied / too_many_uploads |
create | “finish or abandon open uploads first (at most 10 per key; they expire at {expiresAt})” |
denied / daily or quota |
create | the existing dailyLimit text |
invalid / signed_upload_unsupported |
create | “this server has no upload links (stdio, or no shared secret): use upload_asset with base64 (≤ 4 MB)” |
conflict / upload_pending |
complete | “PUT the file to the url from create_upload first (the curl line), then call complete_upload again; start before {expiresAt}” |
conflict / upload_failed |
complete | “the last PUT was refused ({putError}); PUT again before {expiresAt} ({attempts} of 3 used), or call create_upload again” |
not_found / upload_not_found |
complete | “no such upload for this key; call create_upload” |
invalid / upload_expired |
complete | “the upload expired before the bytes arrived (or were completed by {completeBy}); call create_upload again” |
5.4 upload_asset stays
upload_asset keeps its schema and its 4 MB limit, and sha256 stays optional there (#299). It remains the path for agents without a shell, for stdio, and for small files where one call is simpler. Its description gains one sentence: “For files you have on disk and a shell to PUT them, create_upload keeps the bytes out of the call.”
6. Storage of the upload row
The migration is additive. media_uploads gains the following columns, and Studio’s rows keep purpose = 'studio' with the new columns null.
ALTER TABLE media_uploads ADD COLUMN purpose TEXT NOT NULL DEFAULT 'studio'; -- 'studio' | 'agent'ALTER TABLE media_uploads ADD COLUMN attempts INTEGER NOT NULL DEFAULT 0;ALTER TABLE media_uploads ADD COLUMN complete_by TEXT; -- agent rowsALTER TABLE media_uploads ADD COLUMN received TEXT; -- JSON: final sha256, originalSha256, bytes, mediaType, warningsALTER TABLE media_uploads ADD COLUMN asset_id TEXT; -- set by complete_upload (idempotency)CREATE INDEX media_uploads_site_open ON media_uploads (site_id, state);state gains receiving, received, completed and abandoned, and Studio’s rows keep using open and used. Every transition is a CAS, and completion is one guarded batch() that inserts the node, sets asset_id and releases the lease, with no interactive transaction (hard rule 4).
Alternatives considered
| Option | Pros | Cons | Why not |
|---|---|---|---|
| Direct presigned PUT to R2 (S3 SigV4) | Bytes bypass the Worker, so there is no 100 MB plan limit and up to 7 days of validity (R2) | The Workers binding “cannot generate presigned URLs” (same page), so the admin Worker would hold S3 API credentials with bucket-wide write. S3 presigned URLs can be used “multiple times, up to the expiration” (S3), so they are not single use. R2 can sign Content-Type. Neither page states that Content-Length can be enforced, and R2’s PutObject row does not list x-amz-checksum-sha256 (R2 S3 API), so size and hash would be checked only afterwards. The link works only on <account>.r2.cloudflarestorage.com, never a custom domain, and browsers would need CORS. |
It loses single use and write-time binding, and adds a powerful secret. Kept as a later option for files over 100 MB (open question 4). |
| Presigned PUT to the self-host S3 store | Same as above | The store is private to the cluster (RFC-0047 §3), so presigning would expose it to agents. Store support for signed Content-Length and checksums varies and is unverified for SeaweedFS and RustFS. |
Proxying keeps the store private. |
Chunked base64 upload (#250 option 2: upload_asset_part + final sha256) |
Works without a shell. No REST exception. | Every byte is still model output, so it costs about the same as today. It adds more failure points: part order, missing parts, and state between calls. | It does not fix what #250 is about. |
fetch_asset_url from a local tunnel (cloudflared quick tunnel, ngrok) |
No new server code | It needs a third-party tool and an account or daemon. It exposes a local port publicly while open, and anyone can fetch it. The SSRF rules (public https host) pass. The 25 MB cap stays. | It is heavier and less safe than a link to our own origin. It stays possible today without any change. |
| The agent’s own key on the PUT (no capability link) | No exception to “agents refused on REST” by capability: the PUT authenticates like any request | The shell usually lacks the credential. OAuth clients (RFC-0044) keep their token inside the MCP client, and #250’s agent had none in its shell. | It would not work for the main case. A key, when sent, is still checked (§2.3 item 7). |
path input for stdio cloudhal mcp (#250 triage D) |
No HTTP at all. The file is read from the project. | Local only. It needs path sandboxing (project dir, no symlinks out). | It is a separate, optional follow-up, not part of this exception. |
| Cloudflare Images direct creator upload | One-time URL, no token for the client, 2 minutes to 6 hours expiry, draft status until uploaded (Images) |
Images only. Multipart form POST. A separate paid product whose storage sits outside our content-addressed blobs and snapshots. | It does not fit RFC-0004’s single store, and it does not exist on self-host. It is good prior art for the “draft until uploaded” shape (our received state). |
| Do nothing (base64 plus #299’s checksum) | Zero work | The cost and the 4 MB limit stay | #250 stays open. |
Prior art, briefly.
- S3 presigned PUTs are time-limited (up to 7 days with SigV4) but reusable. S3 validates a client-supplied
x-amz-checksum-sha256before storing (integrity). Whether a presigned URL can sign and so force that header is not stated on the pages read (unverified). - R2 presigned URLs support GET, HEAD, PUT and DELETE but not POST form uploads, and last 1 second to 7 days.
- Cloudflare Images hands out a “one-time upload URL”, 30 minutes by default. The page does not explicitly say it is single use (unverified).
- Sanity takes the raw body on
POST /assets/images|files/{dataset}, and “all requests must be authenticated”. Its docs name no signed upload links. - Contentful has a separate Upload API (
upload.contentful.com, rawapplication/octet-stream). The file expires if it is not associated and processed within 24 hours. The asset links it withuploadFromand is then processed (PUT …/files/{locale}/process). Up to 1000 MB, and not resumable. The create-upload page namesapi.contentful.comas the host, which contradicts the overview, and whether the upload host needs the CMA token is stated only on the create page (partly unverified). - Our design takes Contentful’s two-step “upload, then link and process” and Images’ tokenless one-time URL. It adds what none of them state: binding to the exact size and hash, single use, and the node created only through the governed call.
Compatibility & migration
-
Contracts and data. No
schemaVersionchanges. The migration is additive, and Studio’s tickets are untouched (purpose = 'studio'). -
Capability flag.
get_modegainsuploads: {signedUrl: boolean, maxBytes: number, linkSeconds: 600}. The server instructions mentioncreate_uploadonly whensignedUrlis true.signedUrlis false on stdio, on a Worker without a shared upload secret, and where an operator turns it off (media.agentUploads: false).- The tools are always listed (ADR-0004) and answer
signed_upload_unsupportedwhere the flag is false. - An older admin Worker simply has no such tools, and clients fall back to
upload_asset.
-
The CLI. There is no new
cloudhalcommand in v1. An MCP client without a shell cannot runcloudhaleither, and one with a shell hascurl, whichcreate_uploadspells out. The only portability gap is hashing, which the tool description covers per OS. If evals show agents failing at it,cloudhal media hash <file>(size, SHA-256, sniffed type) is the small helper to add (open question 6). -
Rollout. Small PRs, each green on its own:
- Docs. On acceptance: the ADR, the RFC-0005 I15 amendment (below), and the threat-model rows.
- Store. The migration, the agent ticket kind, the CAS transitions, the split of
stageUpload/completeUploadfromingestAsset/ingestAssetStream, and the lease tocompleteBy. Conformance on sqlite and Miniflare D1. - API. The
upload-linkrequirement and the route, the playgroundDENYrow, redaction ofsigin logs, and the errors of §5.2. - MCP.
create_upload,complete_upload,upload-hints.ts,get_mode.uploads, the quotas, the regenerated tool table, and a changeset. - Hosts.
CLOUDHAL_UPLOAD_SECRETincloudhal deployand self-host (_FILE), the base URL for links, and the self-host proxy body note. Then a guide page (docs/guides/agent-uploads.md) with the curl recipe.
-
Rollback. Set
media.agentUploads: false, or deploy the previous release. Open uploads expire within an hour. Blobs already received are either completed or collected. The new columns are harmless if left in place. -
The RFC-0005 I15 amendment (text for the ADR). The invariant keeps its letter and gains a sentence:
I15. REST is default-deny: every
/apiroute declares its requirement inROUTE_SCOPES, and a test fails for any undeclared route. One requirement,upload-link, is a capability rather than an actor: it is declared only onPUT …/assets/agent-uploads/:uploadId(RFC-0048), and the handler authorizes against a single-use row minted by a governed MCP call.§10.1’s “agents remain refused on REST” gains: “except that an upload link minted by
create_uploadcarries one file’s bytes (RFC-0048)”.
Security & policy impact
Why this is an exception to RFC-0005 I15, and why it stays safe.
- What RFC-0005 says. Invariant I15 reads: “REST is default-deny: every
/apiroute declares its requirement inROUTE_SCOPES, and a test fails for any undeclared route.” Beside it, §10.1 says “peopleOnlystays: agents remain refused on REST”, andscopes.tssays agents “work through MCP”. - What this RFC changes. The new route is declared, so I15’s letter holds. But it is the first route whose requirement is not checked against the caller’s own credential, and the first that an agent uses directly. The link itself is the credential. That is the exception, and it is why an RFC is needed.
- Why it stays safe:
- The decision stays in MCP. Scope, mode, approval, run, taint, budget and quota are all decided by
create_uploadand re-checked bycomplete_upload. The PUT decides nothing. It can only accept the bytes that were already approved. - The PUT carries data, not commands. It cannot create, change, publish or delete a node. The node is made only by the governed
complete_upload. - The link is bound to the exact content (§2.3). A leak can upload only the identical file once, and it cannot write anything else anywhere.
- The declaration is enforced. The enumeration test pins
upload-linkto one route, so the exception cannot spread silently. A second use needs another RFC.
- The decision stays in MCP. Scope, mode, approval, run, taint, budget and quota are all decided by
Other impacts.
- New scopes: none.
asset:uploadcovers both tools. - New approval points: none.
create_uploadis gated whereupload_assetis. - Tenant isolation. The site comes from the path, the signed payload and the row, and must agree everywhere. Quotas are per key and per site. In Cloud, the org binding of sites applies unchanged.
- Secrets. There is an optional new
CLOUDHAL_UPLOAD_SECRET(32 bytes or more). It goes in the 0600 secrets file on deploy and in_FILEon self-host, never in a config.
Test plan
Local runs stay light (structure and unit tests). The workerd and D1 suites run in CI.
- Signing (unit).
- Every payload field changed in turn gives
bad_signature. - A Studio ticket’s
sigfails on the agent route, and the agentsigfails on Studio’s route. - Rotating
CLOUDHAL_UPLOAD_SECRETvoids open links and leaves received ones completable.
- Every payload field changed in turn gives
- Store conformance (sqlite and Miniflare D1).
- Two concurrent PUTs: exactly one claims.
- Failed verification reopens the row, up to 3 attempts.
- Expiry ±1 ms.
completeByreleases the lease, and GC collects the blob after the grace period, never before.- Completion is idempotent, and completion is guarded on the lease.
- The quotas: per key, per site, daily, and the site quota with reservations.
- API (shared suite).
- The size checks: wrong
Content-Length, a short body, a long body, and a chunked body without a length. Content-Encoding: gzipis refused.- A declared PNG whose bytes are SVG gives 415.
- HTML and SVG are refused at create.
- A purged hash gives 410.
- A cookie or another key on the PUT: the cookie is ignored, the other key gets
not_your_upload. GETanswers 405 and reveals nothing.- The route-enumeration test pins
upload-linkto one route, andtest/playground.test.tsclassifies the new route.
- The size checks: wrong
- MCP.
- Mode
planrefuses, andmanualfiles an approval whose prompt shows the size and hash prefix. - A key revoked between create and complete completes nothing.
- A run budget is charged at create.
- Dedupe answers
status: "existing". - Output validates against the strict schemas, and every key is present.
- The hints are returned for each reason in §5.3.
- The audit rows are grepped for
sig=and must not contain it.
- Mode
- End to end.
- The CLI e2e spawns
cloudhal studio, and an agent key runs create, afetchPUT, then complete. - A workerd test (
createTestHarness) runs the admin Worker with a 25 MB stream in CI only. - The self-host smoke (
scripts/docker-smoke.ts) adds one upload over SeaweedFS.
- The CLI e2e spawns
- Eval. One build-eval task where the agent must add a 300 KB cover from disk: it succeeds without base64 in the transcript.
Open questions
All ten were decided on 2026-11-29 as recommended (see “Decisions (2026-11-29)”). An implementation PR that needs a different answer brings it back to the owner.
- Is
sha256required oncreate_upload? Decided (2026-11-29), as recommended: yes. With it, a leaked link can upload only the declared file. Without it, a leaked link lets anyone put any bytes of that size and type into the library as the agent. Agents that can PUT a file can also hash it. - What is the default per-file cap for agent uploads? Decided (2026-11-29), as recommended: 25 MB, the same as
fetch_asset_url, as an operator setting up to 100 MB. That is the Free and Pro body limit andMEDIA_LIMITS.upload. - How long do links last? Decided (2026-11-29), as recommended: 10 minutes to start the PUT, and 60 minutes to complete. That is shorter than Studio’s 15 minutes because the link is the whole credential. The link is minted right before use, and a large transfer is not cut off because the deadline is for starting.
- Direct R2 presigned URLs for files over 100 MB? Decided (2026-11-29), as recommended: not in v1. Revisit only if an owner needs agent uploads larger than the plan’s body limit. It would need a scoped R2 token, staging keys, CORS, and verification after the write.
- Should stdio
cloudhal mcpget upload links through a loopback listener? Decided (2026-11-29), as recommended: no. ReportsignedUrl: false. Thepathinput (#250 triage D) is the better local answer and gets its own issue. - Should there be a
cloudhalupload helper? Decided (2026-11-29), as recommended: not in v1 (“The CLI” under Compatibility & migration). Addcloudhal media hashonly if evals show hashing is where agents fail. - Should the PUT complete the asset by itself when
complete_uploadnever comes? Decided (2026-11-29), as recommended: no. An uncompleted upload is abandoned and collected. Assets are created only by a governed call. - Should
complete_uploadneed its own approval inmanualmode? Decided (2026-11-29), as recommended: no. The approval atcreate_uploadalready binds the exact file, so a second prompt would only add noise. - A dedicated secret and a
kid? Decided (2026-11-29), as recommended: the optionalCLOUDHAL_UPLOAD_SECRETnow, and nokid. Links live 10 minutes, so rotating voids at most that window. - Should
upload_assetbe deprecated? Decided (2026-11-29), as recommended: no. It is the only path for clients without a shell and for stdio, and it stays as is.
Decisions (2026-11-29)
The owner (Halil) accepted this RFC on 2026-11-29 with the recommended answers (“Kabul ediyorum, önerilen cevaplarla”, that is, “I accept, with the recommended answers”). So:
sha256is required oncreate_upload.- The agent cap is 25 MB by default, and an operator can raise it to 100 MB.
- A link lasts 10 minutes for starting the PUT. Received bytes must be completed within 60 minutes.
- No direct R2 presigned URLs in v1. The PUT is proxied through the API on every host.
- Stdio
cloudhal mcpgets no upload links (signedUrl: false). Thepathinput (#250 triage D) gets its own issue. - No
cloudhalupload helper in v1.cloudhal media hashis added only if evals show agents failing at hashing. - An uncompleted upload is abandoned and collected. The PUT never creates an asset.
- No second approval for
complete_upload. - An optional
CLOUDHAL_UPLOAD_SECRET, and nokid. upload_assetstays as it is.
The RFC-0005 I15 amendment (under “Compatibility & migration”) is accepted with this RFC. It is written into the ADR in rollout step 1. Implementation follows rollout steps 1 to 5, one PR each.
Implementation notes
Rollout step 4 (MCP tools).
create_upload’s input requires only the declared file (siteId,filename,bytes,mediaType,sha256). Every optional value also acceptsnullbut may be left out. MCP servers validate arguments againstrequired, so listing every key there, as §5.1 has it, would refuse the clients that §5.1 lets leave null keys out. A strict-mode client that sends every key withnullpasses as written. The output keeps the strict profile: every key is always present, withnullwhere it does not apply.complete_uploadis classifiedadvisory. The policy engine refusesadvisorycalls inplanand lets them run without a person inmanualand every other mode. That is decision 8 (no second approval) with no new rule. Scopes and the key’s status are checked on the call as on any other.- The daily limit is checked at
create_uploadonly. It now counts open uploads with their declared bytes. A completed upload becomes an asset that the next day’s count already includes. Checking again at completion would count the same file twice. The site quota is still re-checked at completion (step 2). - No
outside_runcheck of its own. Inside an automation run,complete_uploadis a write likeupload_asset: the run’s budget and taint rules apply to it as they do to any write. - The hints live in
packages/mcp-server/src/upload-hints.ts, as §5.3 says. The store’s invariant codes are answered with existing tool codes plusdetails.reason. - Where a link points. It uses the deployment’s configured origin (
ApiDeps.studioOrigin, whichcloudhal studio --base-urlsets), else the origin of the/mcprequest.
Rollout step 5 (hosts).
CLOUDHAL_UPLOAD_SECRETis an admin Worker secret of the release manifest. RFC-0046’sSecretNamegains it, an additive contract change, regenerated for TypeScript and Rust.cloudhal deploygenerates it into the 0600 secrets file, and an existing project gets it on its next deploy.- Self-host keeps it optional. The image does not require it, so existing installations start unchanged.
cloudhal selfhost secretsgenerates it for new ones._FILEworks. Unset, workerd receives an empty value and the preview secret signs. A value shorter than 32 characters stops the image at start. cloudhal.jsonmedia.agentUploadsandmedia.agentUploadBytesare read byconfig-media.ts, without takingmediaover from the starter. They aredeploykeys in the release key table, and the admin Worker receives them as the varsCLOUDHAL_AGENT_UPLOADSandCLOUDHAL_AGENT_UPLOAD_BYTES. Self-host passes the same vars through, andcloudhal studioreads the file. Helm and Swarm are unchanged: operators add the optional secret through_FILEor the environment.- Studio labels
create_upload,complete_uploadand the audit eventasset.upload-receivedin every language. The translations are drafts awaiting review. - The eval task is not added. The build eval runs Workers AI models through Build chat’s page-building turn, which has neither the MCP upload tools nor a shell. A “cover from disk” task needs an agent harness with a shell and an MCP client, which this repo does not have yet. The API’s end-to-end test (
agent-uploads-auth.test.ts) runs the same flow without a model.