How to integrate Google Calendar MCP with Pydantic AI

Connect Pydantic AI to Google Calendar MCP. Create a meeting with the marketing team, list all events scheduled for next week, and more using natural language, with authentication handled for you.

Google Calendar logoGoogle Calendar
Oauth2

Google Calendar is a time management service for scheduling meetings, events, and reminders. It streamlines personal and team organization with integrated notifications and sharing options.

47 Tools6 Triggers

Introduction

This guide walks you through connecting Google Calendar to Pydantic AI using the Composio tool router. By the end, you'll have a working Google Calendar agent that can create and update events, find free time slots, check availability, manage your calendars, and control sharing through natural language commands.

This guide will help you understand how to give your Pydantic AI agent real control over a Google Calendar account through Composio's Google Calendar MCP server.

Before we dive in, let's take a quick look at the key ideas and tools involved.

Also integrate Google Calendar with

TL;DR

Here's what you'll learn:
  • How to set up your Composio API key and User ID
  • How to create a Composio Tool Router session for Google Calendar
  • How to attach an MCP Server to a Pydantic AI agent
  • How to stream responses and maintain chat history
  • How to build a simple REPL-style chat interface to test your Google Calendar workflows

What is Pydantic AI?

Pydantic AI is a Python framework for building AI agents with strong typing and validation. It leverages Pydantic's data validation capabilities to create robust, type-safe AI applications.

Key features include:

  • Type Safety: Built on Pydantic for automatic data validation
  • MCP Support: Native support for Model Context Protocol servers
  • Streaming: Built-in support for streaming responses
  • Async First: Designed for async/await patterns

What is the Google Calendar MCP server, and what's possible with it?

The Google Calendar MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Google Calendar account. It provides structured and secure access to your calendars, events, availability, and sharing settings, so your agent can schedule meetings, find events, check availability, update plans, and manage calendars on your behalf.

  • Event scheduling and updates: Have your agent create events with set times or durations, change event details, and delete canceled plans.
  • Event search and review: Instruct your agent to find events by keywords or time range, retrieve event details, and review instances of recurring events.
  • Availability checks: Let the agent check busy periods across one or more calendars before arranging a meeting.
  • Calendar organization: Direct your agent to create, rename, update, delete, add, or remove calendars from your calendar list.
  • Calendar access management: Have your agent create, review, or remove calendar access rules to control sharing.

What is the Composio tool router, and how does it fit here?

What is Composio SDK?

Composio's Composio SDK helps agents find the right tools for a task at runtime. You can plug in multiple toolkits (like Gmail, HubSpot, and GitHub), and the agent will identify the relevant app and action to complete multi-step workflows. This can reduce token usage and improve the reliability of tool calls. Read more here: Getting started with Composio SDK

The tool router generates a secure MCP URL that your agents can access to perform actions.

How the Composio SDK works

The Composio SDK follows a three-phase workflow:

  1. Discovery: Searches for tools matching your task and returns relevant toolkits with their details.
  2. Authentication: Checks for active connections. If missing, creates an auth config and returns a connection URL via Auth Link.
  3. Execution: Executes the action using the authenticated connection.

Step-by-step Guide

Step by step09 STEPS
1

Prerequisites

Before starting, make sure you have:
  • Python 3.9 or higher
  • A Composio account with an active API key
  • Basic familiarity with Python and async programming
2

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key. You'll need credits to use the models, or you can connect to another model provider.
  • Keep the API key safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Navigate to your API settings and generate a new API key.
  • Store this key securely as you'll need it for authentication.
3

Install dependencies

bash
pip install composio pydantic-ai python-dotenv

Install the required libraries.

What's happening:

  • composio connects your agent to external SaaS tools like Google Calendar
  • pydantic-ai lets you create structured AI agents with tool support
  • python-dotenv loads your environment variables securely from a .env file
4

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key

Create a .env file in your project root.

What's happening:

  • COMPOSIO_API_KEY authenticates your agent to Composio's API
  • USER_ID associates your session with your account for secure tool access
  • OPENAI_API_KEY to access OpenAI LLMs
5

Import dependencies

python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()
What's happening:
  • We load environment variables and import required modules
  • Composio manages connections to Google Calendar
  • MCPServerStreamableHTTP connects to the Google Calendar MCP server endpoint
  • Agent from Pydantic AI lets you define and run the AI assistant
6

Create a Tool Router Session

python
async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Google Calendar
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["googlecalendar"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")
What's happening:
  • We're creating a Tool Router session that gives your agent access to Google Calendar tools
  • The create method takes the user ID and specifies which toolkits should be available
  • The returned session.mcp.url is the MCP server URL that your agent will use
7

Initialize the Pydantic AI Agent

python
# Attach the MCP server to a Pydantic AI Agent
googlecalendar_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
agent = Agent(
    "openai:gpt-5",
    toolsets=[googlecalendar_mcp],
    instructions=(
        "You are a Google Calendar assistant. Use Google Calendar tools to help users "
        "with their requests. Ask clarifying questions when needed."
    ),
)
What's happening:
  • The MCP client connects to the Google Calendar endpoint
  • The agent uses GPT-5 to interpret user commands and perform Google Calendar operations
  • The instructions field defines the agent's role and behavior
8

Build the chat interface

python
# Simple REPL with message history
history = []
print("Chat started! Type 'exit' or 'quit' to end.\n")
print("Try asking the agent to help you with Google Calendar.\n")

while True:
    user_input = input("You: ").strip()
    if user_input.lower() in {"exit", "quit", "bye"}:
        print("\nGoodbye!")
        break
    if not user_input:
        continue

    print("\nAgent is thinking...\n", flush=True)

    async with agent.run_stream(user_input, message_history=history) as stream_result:
        collected_text = ""
        async for chunk in stream_result.stream_output():
            text_piece = None
            if isinstance(chunk, str):
                text_piece = chunk
            elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                text_piece = chunk.delta
            elif hasattr(chunk, "text"):
                text_piece = chunk.text
            if text_piece:
                collected_text += text_piece
        result = stream_result

    print(f"Agent: {collected_text}\n")
    history = result.all_messages()
What's happening:
  • The agent reads input from the terminal and streams its response
  • Google Calendar API calls happen automatically under the hood
  • The model keeps conversation history to maintain context across turns
9

Run the application

python
if __name__ == "__main__":
    asyncio.run(main())
What's happening:
  • The asyncio loop launches the agent and keeps it running until you exit

Complete Code

Here's the complete code to get you started with Google Calendar and Pydantic AI:

python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()

async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for Google Calendar
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["googlecalendar"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")

    # Attach the MCP server to a Pydantic AI Agent
    googlecalendar_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
    agent = Agent(
        "openai:gpt-5",
        toolsets=[googlecalendar_mcp],
        instructions=(
            "You are a Google Calendar assistant. Use Google Calendar tools to help users "
            "with their requests. Ask clarifying questions when needed."
        ),
    )

    # Simple REPL with message history
    history = []
    print("Chat started! Type 'exit' or 'quit' to end.\n")
    print("Try asking the agent to help you with Google Calendar.\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "bye"}:
            print("\nGoodbye!")
            break
        if not user_input:
            continue

        print("\nAgent is thinking...\n", flush=True)

        async with agent.run_stream(user_input, message_history=history) as stream_result:
            collected_text = ""
            async for chunk in stream_result.stream_output():
                text_piece = None
                if isinstance(chunk, str):
                    text_piece = chunk
                elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                    text_piece = chunk.delta
                elif hasattr(chunk, "text"):
                    text_piece = chunk.text
                if text_piece:
                    collected_text += text_piece
            result = stream_result

        print(f"Agent: {collected_text}\n")
        history = result.all_messages()

if __name__ == "__main__":
    asyncio.run(main())

Conclusion

You've built a Pydantic AI agent that can interact with Google Calendar through Composio's Tool Router. With this setup, your agent can perform real Google Calendar actions through natural language. You can extend this further by:
  • Adding other toolkits like Gmail, HubSpot, or Salesforce
  • Building a web-based chat interface around this agent
  • Using multiple MCP endpoints to enable cross-app workflows (for example, Gmail + Google Calendar for workflow automation)
This architecture makes your AI agent "agent-native", able to securely use APIs in a unified, composable way without custom integrations.
TOOLS & TRIGGERS

Supported Tools and Triggers

Every Google Calendar action and event your agent gets out of the box.

Delete ACL Rule

Deletes an access control rule from a Google Calendar.

Get ACL Rule

Retrieves a specific access control rule for a calendar.

Create ACL Rule

Creates an access control rule for a calendar.

List ACL Rules

Retrieves the list of access control rules (ACLs) for a specified calendar, providing the necessary 'rule_id' values required for updating specific ACL rules.

Patch ACL Rule

Partially updates the role or scope of an existing Google Calendar access control rule.

Update ACL Rule

Updates an access control rule for the specified calendar.

Watch ACL Changes

Tool to watch for changes to ACL resources.

Batch Events

Execute up to 1000 event mutations (create/patch/delete) in one Google Calendar HTTP batch request with per-item status/results.

Remove Calendar from List

Removes a calendar from the user's calendar list, unsubscribing from it without deleting the calendar itself.

Get Single Calendar by ID

Retrieves metadata for a SINGLE specific calendar from the user's calendar list by its calendar ID.

Insert Calendar into List

Inserts an existing calendar into the user's calendar list, with optional display settings.

Patch Calendar List Entry

Updates an existing calendar on the user's calendar list using patch semantics.

Update Calendar List Entry

Updates a calendar list entry's display/subscription settings (color, visibility, reminders, selection) for the authenticated user — does not modify the underlying calendar resource (title, timezone, etc.

Watch Calendar List

Creates a push-notification channel for changes to the user's calendar list.

Delete Calendar

Deletes a secondary calendar that you own or have delete permissions on.

Update Calendar

Full PUT-style update that overwrites all calendar metadata fields; unspecified optional fields are cleared.

Stop Channel

Tool to stop watching resources through a notification channel.

Clear Calendar

Clears a primary calendar by deleting all events from it.

Get Color Definitions

Returns the color definitions for calendars and events.

Create a new calendar

Creates a new secondary Google Calendar with the specified title and optional settings.

Create Event

Creates a timed or all-day Google Calendar event and returns it under response_data, without conflict checking.

Delete event

Deletes an event from the specified calendar.

Create a calendar

Creates a new, empty Google Calendar with the specified title (summary).

Get Event

Retrieves a SINGLE event by its unique event_id (REQUIRED).

Import Event

Tool to import an event as a private copy to a calendar.

Get Event Instances

Returns instances of the specified recurring event.

List Events

Lists or incrementally synchronizes events from one calendar, defaulting to the connected user's primary calendar.

List Events from All Calendars

Lists and deduplicates events across selected calendars or the user's calendar list for a time range.

Move Event

Moves a default event to another calendar, changing its organizer.

Watch Events

Watch for changes to Events resources.

Find event

Finds events in a specified Google Calendar using text, time ranges, and event types.

Find free slots

Queries busy intervals and calculates free gaps for specified calendars, without filtering by meeting duration; the range is limited to 89 days, and calendar errors produce empty free slots marked unreliable.

Query Calendar Availability

Queries raw busy intervals for one or more calendars or groups over an exact time range.

Get Google Calendar

Gets canonical metadata for one Google Calendar, defaulting to the authenticated user's primary calendar.

Get current date and time

Gets the current date and time, allowing for a specific timezone offset.

Get Current Google Calendar User

Identifies the Google user connected to Calendar from the primary calendar resource.

List Buildings

Lists a page of buildings for a Google Workspace customer, including available addresses, coordinates, and floor names.

List Calendar Resources

Retrieves calendar resources (such as conference rooms) from a Google Workspace domain using the Admin SDK Directory API.

List Google Calendars

Lists calendars accessible through the connected user's CalendarList, returning IDs and user-specific metadata such as access role, color, visibility, selection, and reminders.

Patch Calendar

Partially updates (PATCHes) an existing Google Calendar, modifying only the fields provided.

Patch Event

Update specified fields of an existing event in a Google Calendar using patch semantics (array fields like `attendees` are fully replaced if provided); ensure the `calendar_id` and `event_id` are valid and the user has write access to the calendar.

Quick Add Event

Parses natural language text to quickly create a basic Google Calendar event with its title, date, and time, suitable for simple scheduling; does not support direct attendee addition or recurring events, and `calendar_id` must be valid if not 'primary'.

Remove attendee from event

Removes an attendee from a specified event in a Google Calendar; the calendar and event must exist.

Get Calendar Setting

Tool to return a single user setting for the authenticated user.

List Settings

Lists the authenticated user's calendar settings, returning a page of settings identified by their id fields.

Watch Settings

Watch for changes to Settings resources.

Update Google event

Replaces an existing Google Calendar event using its event ID and required start time.

FAQ

Frequently asked questions

Start with Google Calendar.It takes 30 seconds.

Managed auth, hosted MCP servers, and every Google Calendar tool your agent needs.Free to start.

Start building