Skip to Content
DocumentationRegistryExamplesGoogle OAuth Example

@loopstack/google-oauth-example

An example module for the Loopstack AI  automation framework.

This module demonstrates how to build workflows that interact with Google Workspace APIs (Calendar, Gmail, Drive) using OAuth authentication. It includes two workflows: a structured calendar summary that fetches upcoming events, and an interactive chat agent powered by Claude that can use all 11 Google Workspace tools.

Workflows

Calendar Summary (google_calendar_summary)

A multi-step workflow that fetches and displays upcoming Google Calendar events. If the user is not authenticated, it launches the OAuth sub-workflow and retries automatically. Includes a custom GoogleCalendarFetchEventsTool that demonstrates building an OAuth-aware tool from scratch using OAuthTokenStore.

Inputs: calendarId (default: primary)

Flow:

start -> calendar_fetched -> end

With OAuth branching:

calendar_fetched -> (unauthorized via @Guard) -> awaiting_auth | auth_completed -> start (retry)

Key patterns:

The workflow uses a custom tool to fetch calendar events, then checks for auth errors via @Guard:

@Transition({ to: 'calendar_fetched' }) async fetchEvents(state: CalendarSummaryState, ctx: WorkflowContext): Promise<CalendarSummaryState> { const args = ctx.input.args as { calendarId: string }; const result = await this.googleCalendarFetchEvents.call({ calendarId: args.calendarId, timeMin: this.now(), timeMax: this.endOfWeek(), }); return { ...state, requiresAuthentication: result.data!.error === 'unauthorized', events: result.data!.events, }; } @Transition({ from: 'calendar_fetched', to: 'awaiting_auth', priority: 10 }) @Guard('needsAuth') async authRequired() { const result = await this.orchestrator.queue( { provider: 'google', scopes: ['https://www.googleapis.com/auth/calendar.readonly'] }, { workflowName: OAuthWorkflow.name, callback: { transition: 'authCompleted' } }, ); await this.documentStore.save( LinkDocument, { label: 'Google authentication required', workflowId: result.workflowId, embed: true, expanded: true, }, { id: `link_${result.workflowId}` }, ); } needsAuth(state: CalendarSummaryState): boolean { return !!state.requiresAuthentication; }

The auth callback uses wait: true with CallbackSchema and transitions back to start to retry:

@Transition({ from: 'awaiting_auth', to: 'start', wait: true, schema: CallbackSchema, }) async authCompleted(state: CalendarSummaryState, payload: { workflowId: string }): Promise<CalendarSummaryState> { await this.documentStore.save( LinkDocument, { status: 'success', label: 'Google authentication completed', workflowId: payload.workflowId, embed: true, expanded: false, }, { id: `link_${payload.workflowId}` }, ); return state; }

On success, the workflow renders a markdown summary using a template:

@Transition({ from: 'calendar_fetched', to: 'end' }) async displayResults(state: CalendarSummaryState): Promise<unknown> { await this.documentStore.save(MarkdownDocument, { markdown: this.render(__dirname + '/templates/calendarSummary.md', { events: state.events }), }); return {}; }

Tools used:

CategoryToolUsed in workflow
Calendargoogle_calendar_list_calendarsNo
Calendargoogle_calendar_fetch_eventsNo
Calendargoogle_calendar_create_eventNo
CalendarCustom GoogleCalendarFetchEventsToolYes
Gmailgmail_search_messagesNo
Gmailgmail_get_messageNo
Gmailgmail_send_messageNo
Gmailgmail_reply_to_messageNo
Drivegoogle_drive_list_filesNo
Drivegoogle_drive_get_file_metadataNo
Drivegoogle_drive_download_fileNo
Drivegoogle_drive_upload_fileNo

Google Workspace Agent (google_workspace_agent)

An interactive chat agent that gives Claude access to all 11 Google Workspace tools. The agent can manage calendar events, search and send emails, browse and upload files to Drive, and handle OAuth automatically via the AuthenticateGoogleTask custom tool.

How it works:

  1. Sets up a hidden system message describing available Google Workspace capabilities
  2. Waits for user input via a wait: true transition
  3. Sends the conversation to Claude with all 11 Google Workspace tools plus authenticate_google
  4. If message.stopReason === 'tool_use', delegates tool calls via LlmDelegateToolCallsTool and collects results with LlmUpdateToolResultTool
  5. If a tool returns an auth error, the LLM calls authenticate_google which launches OAuth
  6. Loops back to wait for the next user message

Agent loop pattern:

@InjectTool({ provider: 'claude', model: 'claude-sonnet-4-6', system: `You are a helpful Google Workspace assistant with access to Calendar, Gmail, and Drive tools. When a tool returns an unauthorized error, use authenticate_google to let the user sign in, then retry. Be concise and format results using markdown.`, tools: [ 'google_calendar_list_calendars', 'google_calendar_fetch_events', 'google_calendar_create_event', 'gmail_search_messages', 'gmail_get_message', 'gmail_send_message', 'gmail_reply_to_message', 'google_drive_list_files', 'google_drive_get_file_metadata', 'google_drive_download_file', 'google_drive_upload_file', 'authenticate_google', ], }) llmGenerateText: LlmGenerateTextTool; @InjectTool({ provider: 'claude' }) llmDelegateToolCalls: LlmDelegateToolCallsTool; @Transition({ from: 'ready', to: 'prompt_executed' }) async llmTurn() { const result: ToolResult<LlmGenerateTextResult> = await this.llmGenerateText.call(); this.llmResult = result.data; } @Transition({ from: 'prompt_executed', to: 'awaiting_tools', priority: 10 }) @Guard('hasToolCalls') async executeToolCalls() { const result: ToolResult<LlmDelegateResult> = await this.llmDelegateToolCalls.call({ message: this.llmResult!.message, callback: { transition: 'toolResultReceived' }, }); this.delegateResult = result.data; } hasToolCalls(): boolean { return this.llmResult?.message.stopReason === 'tool_use'; }

This is the easiest way to interactively test every Google Workspace tool — just ask the agent to perform any operation.

Setup

Environment Variables

Create a Google OAuth App at https://console.cloud.google.com/apis/credentials  and configure:

GOOGLE_CLIENT_ID=your-client-id GOOGLE_CLIENT_SECRET=your-client-secret GOOGLE_OAUTH_REDIRECT_URI=http://localhost:5173/oauth/callback

For the Google Workspace Agent workflow, you also need an LLM API key:

ANTHROPIC_API_KEY=your-anthropic-api-key

Dependencies

  • @loopstack/common - Core workflow/runtime types and documents (BaseWorkflow, @Workflow, @Transition, @Guard, CallbackSchema, LinkDocument, MarkdownDocument)
  • @loopstack/claude-module - Claude provider registration used by LLM tools
  • @loopstack/llm-provider-module - LLM adapter tools (LlmGenerateTextTool, LlmMessageDocument, LlmDelegateToolCallsTool, LlmUpdateToolResultTool)
  • @loopstack/oauth-module - OAuth infrastructure (OAuthWorkflow, OAuthTokenStore)
  • @loopstack/google-workspace-module - All 11 Google Workspace tools (Calendar, Gmail, Drive)

About

Author: Jakob Klippel 

License: MIT

Additional Resources

Last updated on