Skip to content
AI Agent How-To

Home ›Connect agents to apps

How to Connect an AI Agent to Google Calendar

Intermediate ~11 min read Last tested November 2026

Updated 2026-12-01

This guide connects a Python agent to Google Calendar with the official Calendar API v3. The agent gets two tools: check whether a time range is free (freebusy.query) and create an event (events.insert on the primary calendar). OAuth matches the desktop flow from Connect an AI agent to Gmail. For no-code booking, see Build an AI agent that books meetings (n8n). Last tested 2026-12-01.

Prerequisites

Docs used:

Steps

1. Enable the Google Calendar API and OAuth client

  1. In Google Cloud Console, select a project.
  2. APIs & Services → Library → enable Google Calendar API.
  3. Configure the OAuth consent screen (External + test users while in Testing).
  4. Clients → Create client → Desktop app → download JSON as credentials.json.

2. Install client libraries

pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib openai

3. Authorize once and build a Calendar service

# calendar_tools.py
from __future__ import annotations

import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

SCOPES = ["https://www.googleapis.com/auth/calendar"]

def get_calendar_service():
    creds = None
    if os.path.exists("token.json"):
        creds = Credentials.from_authorized_user_file("token.json", SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
            creds = flow.run_local_server(port=0)
        with open("token.json", "w") as token:
            token.write(creds.to_json())
    return build("calendar", "v3", credentials=creds)

https://www.googleapis.com/auth/calendar scope is required for events.insert (create events guide).

4. Implement free/busy and create-event helpers

from datetime import datetime, timedelta, timezone
from googleapiclient.errors import HttpError

def check_free(service, start_iso: str, end_iso: str, calendar_id: str = "primary") -> str:
    body = {
        "timeMin": start_iso,
        "timeMax": end_iso,
        "items": [{"id": calendar_id}],
    }
    data = service.freebusy().query(body=body).execute()
    busy = data["calendars"][calendar_id].get("busy", [])
    return "free" if not busy else f"busy ({len(busy)} blocks)"

def create_event(
    service,
    summary: str,
    start_iso: str,
    end_iso: str,
    calendar_id: str = "primary",
    time_zone: str = "UTC",
) -> str:
    event = {
        "summary": summary,
        "start": {"dateTime": start_iso, "timeZone": time_zone},
        "end": {"dateTime": end_iso, "timeZone": time_zone},
    }
    created = service.events().insert(calendarId=calendar_id, body=event).execute()
    return created.get("htmlLink", created["id"])

Use RFC3339 timestamps (for example 2026-12-01T15:00:00Z).

5. Expose tools to the LLM

import json
from openai import OpenAI

client = OpenAI()
service = get_calendar_service()

tools = [
    {
        "type": "function",
        "function": {
            "name": "calendar_check_free",
            "description": "Return whether the primary calendar is free between start and end (RFC3339).",
            "parameters": {
                "type": "object",
                "properties": {
                    "start_iso": {"type": "string"},
                    "end_iso": {"type": "string"},
                },
                "required": ["start_iso", "end_iso"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "calendar_create_event",
            "description": "Create a timed event on the primary calendar.",
            "parameters": {
                "type": "object",
                "properties": {
                    "summary": {"type": "string"},
                    "start_iso": {"type": "string"},
                    "end_iso": {"type": "string"},
                },
                "required": ["summary", "start_iso", "end_iso"],
            },
        },
    },
]

def dispatch(name: str, args: dict) -> str:
    if name == "calendar_check_free":
        return check_free(service, args["start_iso"], args["end_iso"])
    if name == "calendar_create_event":
        return create_event(service, args["summary"], args["start_iso"], args["end_iso"])
    raise ValueError(name)

messages = [{"role": "user", "content": "Am I free tomorrow 3–4pm UTC? If yes, book Focus block."}]
for _ in range(6):
    msg = client.chat.completions.create(
        model="gpt-4.1-mini",
        messages=messages,
        tools=tools,
    ).choices[0].message
    if not msg.tool_calls:
        print(msg.content)
        break
    messages.append(msg)
    for call in msg.tool_calls:
        result = dispatch(call.function.name, json.loads(call.function.arguments or "{}"))
        messages.append(
            {"role": "tool", "tool_call_id": call.id, "content": result},
        )

Cap steps like Fix: AI agent stuck in a loop.

6. Confirm in Google Calendar

Open the htmlLink returned from events.insert or check the web UI. While the OAuth app is in Testing, only test users on the consent screen can authorize.

Common errors

403 accessNotConfigured. Enable the Calendar API for the project.

403 insufficientPermissions. Token was created with read-only scope; delete token.json and re-auth with the calendar scope above.

400 Invalid time zone. Pass a valid IANA zone in time_zone or use UTC with Z offsets.

Agent creates overlapping events. Call calendar_check_free in the system message before allowing calendar_create_event.

FAQ

How do I connect an AI agent to Google Calendar?

Use OAuth desktop credentials, build calendar v3 with google-api-python-client, expose freebusy.query and events.insert as LLM tools.

Can the agent delete events?

This guide only adds free/busy and create. Omit delete tools unless you add human approval (LangGraph: human in the loop).

Should I use MCP instead of REST?

Google hosts Workspace MCP for some products (Drive MCP, Gmail MCP). Custom agents with full control of prompts and scopes fit the REST pattern here.

How is this different from the n8n booking guide?

Build an AI agent that books meetings uses n8n’s Google Calendar nodes. This guide keeps the agent and OAuth inside your Python process.