All skills
openai avatar

/cloudflare-deploy

@bf9e226 official
by openaiopenai/skills28k stars
1,891

Deploy applications and infrastructure to Cloudflare using Workers, Pages, and related platform services. Use when the user asks to deploy, host, publish, or set up a project on Cloudflare.

Use this Skill: https://skilld.dev/gh/openai/skills/cloudflare-deploy

This session only. Nothing lands on disk.

referencesagents-sdkgotchas.md

≈1.3k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Gotchas & Best Practices

Common Errors

"setState() not syncing"

Cause: Mutating state directly or not calling setState() after modifications
Solution: Always use setState() with immutable updates:

// ❌ this.state.count++
// ✅ this.setState({...this.state, count: this.state.count + 1})

"Message history grows unbounded (AIChatAgent)"

Cause: this.messages in AIChatAgent accumulates all messages indefinitely
Solution: Manually trim old messages periodically:

export class ChatAgent extends AIChatAgent<Env> {
  async onChatMessage(onFinish) {
    // Keep only last 50 messages
    if (this.messages.length > 50) {
      this.messages = this.messages.slice(-50);
    }
    
    return this.streamText({ model: openai("gpt-4"), messages: this.messages, onFinish });
  }
}

"SQL injection vulnerability"

Cause: Direct string interpolation in SQL queries Solution: Use parameterized queries:

// ❌ this.sql`...WHERE id = '${userId}'`
// ✅ this.sql`...WHERE id = ${userId}`

"WebSocket connection timeout"

Cause: Not calling conn.accept() in onConnect Solution: Always accept connections:

async onConnect(conn: Connection, ctx: ConnectionContext) { conn.accept(); conn.setState({userId: "123"}); }

"Schedule limit exceeded"

Cause: More than 1000 scheduled tasks per agent Solution: Clean up old schedules and limit creation rate:

async checkSchedules() { if ((await this.getSchedules()).length > 800) console.warn("Near limit!"); }

"AI Gateway unavailable"

Cause: AI service timeout or quota exceeded
Solution: Add error handling and fallbacks:

try { 
  return await this.env.AI.run(model, {prompt}); 
} catch (e) { 
  console.error("AI error:", e);
  return {error: "Unavailable"}; 
}

"@callable method returns undefined"

Cause: Method doesn't return JSON-serializable value, or has non-serializable types
Solution: Ensure return values are plain objects/arrays/primitives:

// ❌ Returns class instance
@callable()
async getData() { return new Date(); }

// ✅ Returns serializable object
@callable()
async getData() { return { timestamp: Date.now() }; }

"Resumable stream not resuming"

Cause: Stream ID must be deterministic for resumption to work
Solution: Use AIChatAgent (automatic) or ensure consistent stream IDs:

// AIChatAgent handles this automatically
export class ChatAgent extends AIChatAgent<Env> {
  // Resumption works out of the box
}

"MCP connection loss on hibernation"

Cause: MCP server connections don't survive hibernation
Solution: Re-register servers in onStart() or check connection status:

onStart() {
  // Re-register MCP servers after hibernation
  await this.mcp.registerServer("github", { url: env.MCP_URL, auth: {...} });
}

"Agent not found"

Cause: Durable Object binding missing or incorrect class name
Solution: Verify DO binding in wrangler.jsonc and class name matches

Rate Limits & Quotas

Resource/Limit Value Notes
CPU per request 30s (std), 300s (max) Set in wrangler.jsonc
Memory per instance 128MB Shared with WebSockets
Storage per agent 10GB SQLite storage
Scheduled tasks 1000 per agent Monitor with getSchedules()
WebSocket connections Unlimited Within memory limits
SQL columns 100 Per table
SQL row size 2MB Key + value
WebSocket message 32MiB Max size
DO requests/sec ~1000 Per unique DO instance; rate limit if needed
AI Gateway (Workers AI) Model-specific Check dashboard for limits
MCP requests Depends on server Implement retry/backoff

Best Practices

State Management

  • Use immutable updates: setState({...this.state, key: newValue})
  • Trim unbounded arrays (messages, logs) periodically
  • Store large data in SQL, not state

SQL Usage

  • Create tables in onStart(), not onRequest()
  • Use parameterized queries: sql`WHERE id = ${id}` (NOT sql`WHERE id = '${id}'`)
  • Index frequently queried columns

Scheduling

  • Monitor schedule count: await this.getSchedules()
  • Cancel completed tasks to stay under 1000 limit
  • Use cron strings for recurring tasks

WebSockets

  • Always call conn.accept() in onConnect()
  • Handle client disconnects gracefully
  • Broadcast to this.connections efficiently

AI Integration

  • Use AIChatAgent for chat interfaces (auto-streaming, resumption)
  • Trim message history to avoid token limits
  • Handle AI errors with try/catch and fallbacks

Production Deployment

  • Rate limiting: Implement request throttling for high-traffic agents (>1000 req/s)
  • Monitoring: Log critical errors, track schedule count, monitor storage usage
  • Graceful degradation: Handle AI service outages with fallbacks
  • Message trimming: Enforce max history length (e.g., 100 messages) in AIChatAgent
  • MCP reliability: Re-register servers on hibernation, implement retry logic

Source: SKILL.md on GitHub

2 warnings17d5 checks · Risk SAFE
  • Gen Agent Trust Hub17d

    This skill provides comprehensive guidance for deploying and managing infrastructure on the Cloudflare platform. It includes extensive educational material on secure development practices, such as preventing SQL injection and managing secrets effectively. No malicious patterns or security risks were identified.

  • Socket17d

    2 alerts: gptAnomaly

  • Snyk17d

    Risk: LOW · No issues

  • Runlayer7mo

    310/310 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at bf9e226. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Activeupdated 8 months ago

README badge

README badge for openai/skills/cloudflare-deploy

Deploys applications and infrastructure to Cloudflare's platform, including Workers, Pages, D1, R2, Durable Objects, KV, and other services. Use decision trees to route to the right Cloudflare product based on compute, storage, AI, networking, security, or media needs.

Generated from the current SKILL.md.

Does this skill cover all Cloudflare products?
The skill is a consolidated index covering compute, storage, AI, networking, security, media, and developer tools on Cloudflare. It uses decision trees to route you to the right product reference, then loads detailed guidance for that product.
What authentication is required before deploying?
Run `npx wrangler whoami` to check if authenticated. For local deployment, use `wrangler login` (one-time OAuth). For CI/CD, set the `CLOUDFLARE_API_TOKEN` environment variable.
What should I do if deployment fails due to network issues?
Rerun the deploy with `sandbox_permissions=require_escalated` to grant elevated network access, which is required for outbound requests to Cloudflare during deployment.
How long does a Cloudflare deployment typically take?
Deployments may take several minutes. Use appropriate timeout values in your configuration or CI/CD environment.

Generated from the current SKILL.md. These answers refresh after source changes.