examples/MCP-tools Public
import { DurableObject } from "cloudflare:workers";import { msUntilFull, take, type Bucket, type Decision } from "./bucket.ts";// One RateLimiter per client, named by the client's IP (src/worker.ts). A Durable Object runs// one call at a time, so two requests can never spend the same token.export class RateLimiter extends DurableObject { async take(): Promise<Decision> { const now = Date.now(); const { bucket, decision } = take(await this.ctx.storage.get<Bucket>("bucket"), now); await this.ctx.storage.put("bucket", bucket); // A full bucket is the same as an empty object, so clear it then instead of keeping one // row per IP we have ever seen. await this.ctx.storage.setAlarm(now + msUntilFull(bucket)); return decision; } async alarm(): Promise<void> { await this.ctx.storage.deleteAll(); }}