Skip to content
Scalekit Docs
Talk to an EngineerDashboard

Build a daily briefing agent with Vercel AI SDK and Scalekit Agent Auth

Connect a TypeScript or Python agent via Vercel AI SDK and Scalekit AgentKit to Google Calendar and Gmail with authenticated tool calls.

A daily briefing agent needs two things: today’s calendar events and the latest unread emails. Both live behind OAuth-protected APIs, and each requires its own token, its own authorization flow, and its own refresh logic. Before you write any scheduling logic, you’re already maintaining two parallel token lifecycles.

Scalekit eliminates that overhead. It stores one OAuth session per connector per user, refreshes tokens automatically, and exposes built-in tools such as googlecalendar_list_events and gmail_fetch_mails. Your agent calls those tools through Scalekit; it never talks to the Google Calendar or Gmail REST APIs directly.

What this recipe covers:

  • Authorize once per connector — create connected accounts for Calendar and Gmail, open the OAuth link if needed, and wait until status is ACTIVE
  • Built-in tool callsexecute_tool("googlecalendar_list_events") and execute_tool("gmail_fetch_mails") so Scalekit runs the provider call and returns structured data
  • Wire both tools into an agent — Vercel AI SDK (TypeScript) or Anthropic messages (Python)

The complete source used here is available in the vercel-ai-agent-toolkit repository, with a TypeScript implementation using the Vercel AI SDK and a Python implementation using the Anthropic SDK directly.

In the Scalekit Dashboard, create two connections under AgentKit > Connections > Create Connection:

  • googlecalendar — Google Calendar OAuth connection
  • gmail — Gmail OAuth connection

The connection names are identifiers your code references directly. They must match exactly.

Terminal window
cd typescript
pnpm install

The typescript/package.json includes:

{
"dependencies": {
"ai": "^4.3.15",
"@ai-sdk/anthropic": "^1.2.12",
"@scalekit-sdk/node": "2.2.0-beta.1",
"zod": "^3.0.0",
"dotenv": "^16.0.0"
}
}

Copy the example env file and fill in your credentials:

Terminal window
cp typescript/.env.example typescript/.env # TypeScript
cp typescript/.env.example python/.env # Python (same variables)
.env
SCALEKIT_ENV_URL=https://your-env.scalekit.dev
SCALEKIT_CLIENT_ID=skc_...
SCALEKIT_CLIENT_SECRET=your-secret
ANTHROPIC_API_KEY=sk-ant-...

Get your Scalekit credentials at app.scalekit.com → Settings → API Credentials.

import { ScalekitClient } from '@scalekit-sdk/node';
import { ConnectorStatus } from '@scalekit-sdk/node/lib/pkg/grpc/scalekit/v1/connected_accounts/connected_accounts_pb.js';
import 'dotenv/config';
// Never hard-code credentials — they would be exposed in source control.
// Pull them from environment variables at runtime.
const scalekit = new ScalekitClient(
process.env.SCALEKIT_ENV_URL!,
process.env.SCALEKIT_CLIENT_ID!,
process.env.SCALEKIT_CLIENT_SECRET!,
);
const actions = scalekit.actions;
const USER_ID = 'user_123'; // Replace with the real user ID from your session

ConnectorStatus is imported from the SDK’s generated protobuf file. Compare connectedAccount.status against ConnectorStatus.ACTIVE rather than the string 'ACTIVE' — TypeScript’s type system enforces this.

Before calling any API, check whether the user has an active connected account. If not, print an authorization link and wait for them to complete the browser OAuth flow.

async function ensureConnected(connectionName: string) {
let { connectedAccount } = await actions.getOrCreateConnectedAccount({
connectionName,
identifier: USER_ID,
});
// Do not call tools until the user finishes OAuth and status is ACTIVE.
if (connectedAccount?.status !== ConnectorStatus.ACTIVE) {
const { link } = await actions.getAuthorizationLink({
connectionName,
identifier: USER_ID,
});
console.log(`\n[${connectionName}] Authorization required.`);
console.log(`Open this link:\n\n ${link}\n`);
console.log('Press Enter once you have completed the OAuth flow...');
await new Promise<void>(resolve => {
process.stdin.resume();
process.stdin.once('data', () => { process.stdin.pause(); resolve(); });
});
const refreshed = await actions.getOrCreateConnectedAccount({
connectionName,
identifier: USER_ID,
});
connectedAccount = refreshed.connectedAccount;
}
if (connectedAccount?.status !== ConnectorStatus.ACTIVE) {
throw new Error(`${connectionName} is still not ACTIVE. Complete authorization and try again.`);
}
return connectedAccount;
}

After the first successful authorization, getOrCreateConnectedAccount / get_or_create_connected_account returns an active account on all subsequent calls. Scalekit refreshes expired tokens automatically — your code never calls a token-refresh endpoint.

6. Fetch calendar events with a built-in tool

Section titled “6. Fetch calendar events with a built-in tool”

Call execute_tool with googlecalendar_list_events. Scalekit uses the stored OAuth session, calls Google Calendar, and returns structured event data. Your agent never handles a Google access token or the Calendar REST API.

import { tool } from 'ai';
import { z } from 'zod';
const getCalendarEvents = tool({
description: "Fetch today's events from Google Calendar via Scalekit",
parameters: z.object({
maxResults: z.number().optional().default(5),
}),
execute: async ({ maxResults }) => {
const response = await actions.executeTool({
toolName: 'googlecalendar_list_events',
connectedAccountId: calendarAccount?.id,
toolInput: {
max_results: maxResults,
},
});
// Tool output lives under data — log once when integrating a new tool.
return response.data ?? {};
},
});

Use the same execute_tool pattern for Gmail with gmail_fetch_mails. Scalekit runs the Gmail API call and returns structured data.

const getUnreadEmails = tool({
description: 'Fetch top unread emails from Gmail via Scalekit actions',
parameters: z.object({
maxResults: z.number().optional().default(5),
}),
execute: async ({ maxResults }) => {
const response = await actions.executeTool({
toolName: 'gmail_fetch_mails',
connectedAccountId: gmailAccount?.id,
toolInput: {
query: 'is:unread',
max_results: maxResults,
},
});
return response.data ?? {};
},
});

You do not need Google Calendar or Gmail API docs for the common path — tool names and parameters are consistent across Scalekit connectors. Browse all supported agent connectors for the full tool list.

Pass both tools to the LLM and ask for a daily summary.

The TypeScript version uses the Vercel AI SDK’s generateText with maxSteps to allow the LLM to call multiple tools in sequence before producing the final response.

import { generateText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
const [calendarAccount, gmailAccount] = await Promise.all([
ensureConnected('googlecalendar'),
ensureConnected('gmail'),
]);
const today = new Date();
const { text } = await generateText({
model: anthropic('claude-sonnet-4-6'),
prompt: `Give me a summary of my day for ${today.toDateString()}: list today's calendar events and my top 5 unread emails.`,
tools: {
getCalendarEvents,
getUnreadEmails,
},
maxSteps: 5, // allow the LLM to call multiple tools before responding
});
console.log(text);

maxSteps controls how many tool-call rounds the LLM can make before it must return a final text response. Without it, generateText stops after the first tool call.

Run the agent:

Terminal window
cd typescript && pnpm start

On first run, you see two authorization prompts in sequence:

[googlecalendar] Authorization required.
Open this link:
https://auth.scalekit.dev/connect/...
Press Enter once you have completed the OAuth flow...
[gmail] Authorization required.
Open this link:
https://auth.scalekit.dev/connect/...
Press Enter once you have completed the OAuth flow...

After both connectors are authorized, the agent fetches your data and returns a summary:

Here's your day for Friday, March 27, 2026:
📅 Calendar — 3 events today
• 9:00 AM Team standup (30 min)
• 1:00 PM Product review
• 4:00 PM 1:1 with manager
📧 Unread emails — top 5
• "Q1 roadmap feedback needed" — Sarah Chen, 1h ago
• "Deploy failed: production" — GitHub Actions, 2h ago
• "New PR review requested" — Lin Feng, 3h ago
...

On subsequent runs, both authorization prompts are skipped. Scalekit returns the active session directly.

Connection name mismatch
  • Symptom: getOrCreateConnectedAccount returns an error for googlecalendar or gmail
  • Cause: The connection name in the Scalekit Dashboard does not match the literal string in your code
  • Fix: Make the dashboard connection name match your code exactly, for example googlecalendar instead of google-calendar
TypeScript status compared to a string
  • Symptom: TypeScript raises TS2367 for connectedAccount?.status !== 'ACTIVE'
  • Cause: The SDK returns a ConnectorStatus enum, not a string literal
  • Fix: Import ConnectorStatus from the SDK’s generated protobuf file and compare against ConnectorStatus.ACTIVE
maxSteps missing in the Vercel AI SDK
  • Symptom: generateText stops after the first tool call instead of returning a final summary
  • Cause: The model is not allowed to make enough tool-call rounds
  • Fix: Set maxSteps to at least 3, and increase it if your workflow needs more than one tool call plus a final response
Tool called before authorization finishes
  • Symptom: First run prints an auth link, then execute_tool fails because the account is not ACTIVE
  • Cause: The sample continued to the tool call without waiting for the browser OAuth flow
  • Fix: Block until the user completes authorization (for example input(...) in Python or a stdin wait in Node), then re-fetch the connected account before calling tools

User ID from session — Both implementations hardcode USER_ID = "user_123". In production, replace this with the real user identifier from your application’s session. A mismatch means Scalekit looks up the wrong user’s connected accounts.

Token freshness — Scalekit refreshes OAuth tokens automatically before tool execution. You do not fetch provider tokens or call a refresh endpoint in application code.

First-run blocking — The authorization prompt blocks the process until the user completes OAuth in the browser. In a web application, redirect the user to link instead of printing it, and handle the callback before proceeding.

execute_tool response shape — Tool output lives under response.data (Python and Node). Keys inside data depend on the tool. Log the raw response once when integrating a new tool, then pass that structure to the LLM.

Rate limits — Google Calendar and Gmail both enforce per-user quotas. If your agent runs frequently, avoid tight polling loops and cache briefing data where freshness allows.

  • Add more connectors — The same ensureConnected + execute_tool pattern works for any Scalekit-supported connector. Swap the connection name and tool name. See all supported connectors.
  • Need a raw provider call — Prefer built-in tools first. If a tool does not cover your case, see proxy API calls rather than extracting tokens in app code.
  • Stream the response — Replace generateText with streamText in the Vercel AI SDK to stream the LLM’s summary token-by-token instead of waiting for the full response.
  • Handle re-authorization — If a user revokes access, getOrCreateConnectedAccount returns an inactive account. Add a re-authorization path to recover gracefully instead of crashing.
  • Review the agent auth quickstart — For a broader overview of the connected-accounts model and supported providers, see the agent auth quickstart.