build it in 30 minutesby updated 7 min read

Build a Calendar-Blocker AI Agent in 30 Minutes

A weekly script reads next week's Google Calendar, asks Claude where focus blocks fit around your priorities, checks every block and books it as focus time.

A weekly Apps Script trigger lists the coming week's Google Calendar events, sends the busy times and your priorities to Claude, and gets back proposed focus blocks as JSON. The script checks every block against working hours and existing events, then books the ones that fit as focus time events that can decline new conflicting invitations.

The build: every Sunday evening, a script reads the coming week from your Google Calendar, sends your busy times and current priorities to Claude, and gets back a short list of focus blocks with specific names. The script checks each block against your working hours and your existing events before booking it, so a bad suggestion is dropped instead of double-booking you. The blocks are created as Google Calendar focus time events, which can decline meeting invitations that arrive later for the same slot.

Claude proposes where the blocks go and what to call them. A plain check in the code accepts or rejects each one before anything is booked.

The 30 minutes assume a Google Workspace account that includes focus time, a Claude API key, and that you're comfortable pasting code into Apps Script. Google lists focus time for Business Standard and Plus, Enterprise Standard and Plus, Education and Nonprofits. On other accounts the same script can book ordinary busy events, covered near the end.

Step 1: Create the script and turn on the Calendar API

Go to script.google.com/create. On the left, next to Services, click Add a service, choose Google Calendar API and click Add. These are the same steps Google's own guide uses for creating focus time from Apps Script.

Open Project Settings and add two script properties:

  • ANTHROPIC_API_KEY, with your Claude API key.
  • PRIORITIES, with a few lines on what matters this week, for example "Q1 pricing review, hiring plan for the ops lead, client onboarding checklist". Update it whenever the list changes.

Step 2: Paste the code

const DRY_RUN = true;          // log the plan first, book nothing
const WORK_START = '09:00';    // working hours, in your calendar's time zone
const WORK_END = '17:00';
const MIN_MINUTES = 90;
const MAX_BLOCKS = 5;

function setup() {
  ScriptApp.newTrigger('planFocusTime')
    .timeBased()
    .onWeekDay(ScriptApp.WeekDay.SUNDAY)
    .atHour(18)
    .inTimezone(CalendarApp.getDefaultCalendar().getTimeZone())
    .create();
}

function planFocusTime() {
  const tz = CalendarApp.getDefaultCalendar().getTimeZone();
  const now = new Date();
  const weekEnd = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);

  const list = Calendar.Events.list('primary', {
    timeMin: now.toISOString(),
    timeMax: weekEnd.toISOString(),
    singleEvents: true,
    orderBy: 'startTime',
  });
  const busy = (list.items || [])
    .filter(e => e.start.dateTime && e.transparency !== 'transparent')
    .filter(e => !(e.attendees || []).some(a => a.self && a.responseStatus === 'declined'))
    .map(e => ({ start: e.start.dateTime, end: e.end.dateTime }));

  const props = PropertiesService.getScriptProperties();
  const plan = askClaude(props.getProperty('ANTHROPIC_API_KEY'),
    'Plan focus blocks for the next 7 days.\n' +
    'Time zone: ' + tz + '. Working hours: ' + WORK_START + ' to ' + WORK_END + ', Monday to Friday.\n' +
    'Busy times (do not overlap these): ' + JSON.stringify(busy) + '\n' +
    'Current priorities:\n' + props.getProperty('PRIORITIES') + '\n\n' +
    'Propose up to ' + MAX_BLOCKS + ' blocks of 90 to 180 minutes in the free time.\n' +
    'Give each a specific title naming the priority it serves, such as "Focus: hiring plan draft".\n' +
    'Use ISO 8601 times with the UTC offset for that date.');

  const accepted = [];
  plan.blocks.forEach(b => {
    if (accepted.length < MAX_BLOCKS && fits(b, busy, now, weekEnd, tz)) {
      accepted.push(b);
      busy.push({ start: b.start, end: b.end });
    }
  });

  accepted.forEach(b => {
    if (DRY_RUN) {
      console.log('Would book: ' + b.title + ', ' + b.start + ' to ' + b.end);
      return;
    }
    Calendar.Events.insert({
      summary: b.title,
      start: { dateTime: b.start },
      end: { dateTime: b.end },
      eventType: 'focusTime',
      transparency: 'opaque',
      focusTimeProperties: {
        chatStatus: 'doNotDisturb',
        autoDeclineMode: 'declineOnlyNewConflictingInvitations',
        declineMessage: 'This is a focus block. Please suggest another time.',
      },
    }, 'primary');
  });
}

function fits(b, busy, now, weekEnd, tz) {
  const s = new Date(b.start);
  const e = new Date(b.end);
  if (isNaN(s) || isNaN(e) || s >= e || s < now || e > weekEnd) return false;
  if ((e - s) / 60000 < MIN_MINUTES) return false;
  const day = d => Utilities.formatDate(d, tz, 'yyyy-MM-dd');
  const hhmm = d => Utilities.formatDate(d, tz, 'HH:mm');
  if (day(s) !== day(e)) return false;
  if (Number(Utilities.formatDate(s, tz, 'u')) > 5) return false;  // 6 = Saturday, 7 = Sunday
  if (hhmm(s) < WORK_START || hhmm(e) > WORK_END) return false;
  return busy.every(x => e <= new Date(x.start) || s >= new Date(x.end));
}

function askClaude(key, prompt) {
  const res = UrlFetchApp.fetch('https://api.anthropic.com/v1/messages', {
    method: 'post',
    contentType: 'application/json',
    headers: { 'Authorization': 'Bearer ' + key, 'anthropic-version': '2026-10-21' },
    payload: JSON.stringify({
      model: 'claude-opus-5-5',
      max_tokens: 8000,
      messages: [{ role: 'user', content: prompt }],
      output_config: { format: { type: 'json_schema', schema: {
        type: 'object',
        properties: { blocks: { type: 'array', items: {
          type: 'object',
          properties: { title: { type: 'string' }, start: { type: 'string' }, end: { type: 'string' } },
          required: ['title', 'start', 'end'],
          additionalProperties: false,
        } } },
        required: ['blocks'],
        additionalProperties: false,
      } } },
    }),
  });
  const data = JSON.parse(res.getContentText());
  return JSON.parse(data.content.filter(c => c.type === 'text').map(c => c.text).join(''));
}

How the code works

  • Reading the week: events.list with singleEvents set to true expands recurring meetings into individual instances, so a weekly call counts as busy every week. Events set to transparent, which Google equates with Show me as Available, and meetings you've declined don't count as busy. All-day events are skipped, since they have no start time.
  • The AI step: Claude gets the busy times, in your calendar's time zone by default, plus your working hours and priorities. output_config.format with a JSON schema makes the reply come back as a list of blocks with a title, a start and an end. The request uses the Authorization and anthropic-version headers from Anthropic's API reference, and claude-opus-5-5 can be swapped for any current model ID.
  • The check: the fits function is the safeguard. A block has to start and end on the same weekday, sit inside working hours, last at least 90 minutes, and overlap nothing already booked, including blocks accepted earlier in the same run. Anything else is skipped, whatever the model suggested.
  • Booking: each accepted block is created with eventType set to focusTime, transparency set to opaque and focusTimeProperties, as Google's guide requires for focus time. declineOnlyNewConflictingInvitations declines only invitations that arrive after the block exists, so meetings already on the calendar stay put. declineAllConflictingInvitations would decline those too, and declineNone turns declining off.

Step 3: Dry run, then schedule it

DRY_RUN starts as true, so running planFocusTime from the editor only logs the blocks it would book. Run it, approve the authorization prompt, and compare the log with your calendar. When the blocks look right, change DRY_RUN to false and run setup once. That creates a time-driven trigger for Sundays at 6 PM in your calendar's time zone.

Google's docs say a recurring time-driven trigger may run at a slightly randomized time: for a 9 AM trigger, Apps Script picks a time between 9 and 10 AM and keeps it from week to week. A Sunday 6 PM trigger runs between 6 and 7 PM.

If your account doesn't have focus time

Google limits focus time to primary calendars and to the Workspace editions listed above. On any other account, delete the eventType and focusTimeProperties lines from the insert call. With transparency set to opaque, each block still shows as busy to anyone checking your availability. It just won't decline anything.

Using Outlook instead

On Microsoft 365, Viva Insights has a focus plan that books up to four hours of focus time a day on your calendar, with an option to silence Teams notifications during it, and it needs no code. To rebuild this script for Outlook, Microsoft Graph's calendarView endpoint returns the occurrences, exceptions and single instances of events in a time range, which matches the singleEvents behavior above, and the event resource's create method adds each block. Graph's event resource has no focus time type: showAs takes free, tentative, busy, oof, workingElsewhere or unknown, so an Outlook block is a busy event that doesn't decline invitations by itself.

Before you leave it running

  • Read the first few weeks of blocks before trusting the titles. The names come from PRIORITIES, so a specific list gives specific names.
  • If the log shows fewer blocks than you expected, your week may not have 90-minute gaps. Lower MIN_MINUTES, or widen the working hours.
  • The script only creates events. It never moves or deletes anything already on your calendar.

What to add next

  • A Friday run that lists which focus blocks survived the week, from the same events.list call with eventTypes set to focusTime.
  • A second set of blocks for admin work, with its own minimum length and prompt.
  • More Google Workspace builds are in the Google AI stack guide.

Sources

  1. Google Calendar API, Manage focus time, out of office, and working location events (Apps Script setup and sample) (checked 2026-12-02)
  2. Google Calendar Help, Use focus time in Google Calendar (eligible Workspace editions) (checked 2026-12-02)
  3. Google Calendar API reference, Events resource (eventType, focusTimeProperties, transparency, attendees) (checked 2026-12-02)
  4. Google Calendar API reference, Events: list (singleEvents, orderBy, time zone of the response) (checked 2026-12-02)
  5. Google Apps Script, Installable triggers (time-driven triggers and their timing) (checked 2026-12-02)
  6. Claude API overview (request headers, Developer API keys) (checked 2026-12-02)
  7. Claude API docs, Structured outputs (output_config.format with a JSON schema) (checked 2026-12-02)
  8. Microsoft Support, Focus plan for Viva Insights (checked 2026-12-02)
  9. Microsoft Graph, List calendarView (checked 2026-12-02)
  10. Microsoft Graph, event resource type (showAs values) (checked 2026-12-02)
calendaragentgoogle calendarapps scriptclaude30 min build
go deeper

Worked steps, FAQs and resources on this topic.

read the guide
the list

Get the next one.

Field notes from real deployments, written the way this one was. No schedule promised and nothing sold to you. Unsubscribe whenever.

ready to ship?

Let's build yours.

Reading is the easy part. We do the work. Tell us what's broken and we'll tell you straight up whether we can help.

let's talk