| disable-model-invocation | true |
| name | clasp |
| description | Google Apps Script via clasp CLI — free serverless platform for Google Workspace automations. Use for: scheduled tasks, webhooks, mail merge, Form generation, Sheet automations, document templates, Drive file organization, cross-service pipelines. Replaces Zapier/Make with free native scripts. NOT for immediate interactive operations (use /gws). Triggers: any Google Workspace automation need, even without mentioning "Apps Script".
|
| argument-hint | <what-to-build> (e.g. 'a Google Form that collects RSVPs') |
| allowed-tools | Bash(clasp:*), Bash(npm install:*), Bash(bun install:*), Bash(which:*), Bash(test:*), Bash(cat:*), Bash(mkdir:*), Bash(ls:*), Read, Write, Edit, Glob, Grep |
Google Apps Script via clasp CLI
Build and deploy Google Apps Script projects locally using TypeScript and clasp.
Dynamic Context
- clasp installed: !
which clasp 2>/dev/null && clasp --version 2>/dev/null || echo "NOT INSTALLED"
- Auth status: !
test -f ~/.clasprc.json && echo "Logged in" || echo "NOT AUTHENTICATED — need clasp login"
- Current directory: !
pwd
- Existing clasp project: !
test -f .clasp.json && cat .clasp.json || echo "No .clasp.json — not a clasp project"
- Manifest: !
test -f appsscript.json && cat appsscript.json || echo "No manifest"
Complete Google Services Reference
Apps Script has native access to the entire Google ecosystem. Use this reference to pick the right APIs for any task.
Core Workspace Services
Gmail — GmailApp / MailApp
- Send, read, search, label, archive, trash emails
- Create drafts, manage threads, parse attachments
- Build mail merge, auto-responders, email digests
- Scopes:
gmail.send, gmail.readonly, gmail.modify, gmail.compose
Google Sheets — SpreadsheetApp
- Read/write cells, ranges, named ranges
- Formatting, conditional formatting, data validation
- Charts, pivot tables, filters, protection
- Custom functions (like Excel formulas but in code)
- Scopes:
spreadsheets, spreadsheets.readonly
Google Docs — DocumentApp
- Create/edit documents programmatically
- Manipulate paragraphs, tables, images, headers, footers
- Find/replace, styling, merge fields
- Generate documents from templates
- Scope:
documents
Google Slides — SlidesApp
- Create/edit presentations
- Manipulate slides, shapes, text, images, tables
- Generate slide decks from data (reporting)
- Scope:
presentations
Google Forms — FormApp
- Create forms with all question types (text, multiple choice, checkbox, grid, date, scale, file upload, section)
- Add validation, branching logic, page navigation
- Read responses, set confirmation messages
- Quiz mode with answer keys and point values
- Scope:
forms
Google Drive — DriveApp
- Create, move, copy, rename, delete files and folders
- Manage sharing permissions and access
- Search files by name, type, date, content
- Convert between formats (Docs↔PDF, Sheets↔CSV)
- File versioning, starring, trashing
- Scopes:
drive, drive.readonly, drive.file
Google Calendar — CalendarApp
- Create, update, delete events
- Manage invitations and RSVPs
- Recurring events, all-day events
- Multiple calendar support
- Find free/busy times
- Scope:
calendar, calendar.readonly
Google Contacts — ContactsApp / People API
- Read, create, update contacts and contact groups
- Search contacts by name, email, phone
- Manage labels and custom fields
- Scope:
contacts, contacts.readonly
Google Maps — Maps
- Geocoding (address → coordinates) and reverse geocoding
- Directions and distance matrix
- Elevation data
- Static map image generation
- Scope:
script.external_request (uses Maps service)
Google Chat — Chat API
- Build Chat bots and interactive cards
- Send messages to Chat spaces
- Respond to slash commands and button clicks
- Scope:
chat.bot
Google Tasks — Tasks API
- Create, list, update, delete task lists and tasks
- Mark tasks complete, set due dates
- Organize and reorder tasks
- Scope:
tasks, tasks.readonly
Data & Analytics Services
BigQuery — BigQuery
- Run SQL queries on massive datasets
- Create and manage datasets and tables
- Load data from Sheets into BigQuery and vice versa
- Schedule recurring queries
- Scope:
bigquery
Google Analytics — Analytics / GA4 API
- Read reports and metrics
- Manage accounts, properties, views
- Export analytics data to Sheets
- Scope:
analytics.readonly
Looker Studio (via URL Fetch)
- Trigger report refreshes
- Embed reports with dynamic parameters
Cloud & Infrastructure
Cloud SQL — Jdbc
- Direct JDBC connection to MySQL, PostgreSQL, SQL Server
- Run SQL queries from Apps Script
- Use Sheets as a frontend for a real database
- Scope:
script.external_request
Cloud Storage (via URL Fetch + Service Account)
- Upload/download files to GCS buckets
- Generate signed URLs
Pub/Sub (via URL Fetch)
- Publish messages to Pub/Sub topics
- Trigger cloud workflows from Apps Script
Utility Services (built-in, no scope needed)
UrlFetchApp — HTTP client for ANY external API
- GET, POST, PUT, DELETE with headers, payload, auth
- Call REST APIs: Slack, Notion, Telegram, OpenAI, Stripe, Twilio, etc.
- Parse JSON/XML responses
- OAuth2 via library (1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF)
- Scope:
script.external_request
HtmlService — Build web UIs
- Serve HTML/CSS/JS as web apps (free hosting)
- Create custom dialogs and sidebars in Sheets/Docs/Slides
- Template engine with scriptlets
- No scope needed (just deploy as web app)
PropertiesService — Persistent key-value store
- Script properties (shared), User properties (per-user), Document properties (per-doc)
- Store API keys, config, state between executions
- No additional scope needed
CacheService — In-memory cache (up to 6 hours)
- Cache expensive API calls or computations
- Shared or per-user cache
- No additional scope needed
LockService — Concurrency control
- Prevent race conditions in concurrent executions
- No additional scope needed
ScriptApp — Triggers and metadata
- Time-driven triggers (every minute, hour, day, week)
- Event triggers: onOpen, onEdit, onSelectionChange, onFormSubmit, onChange
- Installable triggers for more permissions
- Get script URL, project key, OAuth token
Utilities — Helper functions
- Base64 encode/decode, MD5/SHA hashing
- UUID generation, sleep, date formatting
- Zip/unzip, blob manipulation
- CSV parsing, JSON manipulation
ContentService — Serve data as API
- Return JSON or XML from a web app endpoint
- Build webhook receivers
- Create REST API endpoints (GET/POST)
XmlService — XML parsing and creation
- Parse RSS/Atom feeds
- Generate XML for SOAP APIs or data export
Admin Services (Workspace Admin only)
AdminDirectory — User and device management
- List, create, update, delete users
- Manage groups, org units, roles
- Chrome device and mobile device management
AdminReports — Audit and usage
- Login activity, admin actions, Drive usage
- User activity reports
Advanced Services (enable in manifest)
These require explicit activation in appsscript.json under dependencies.enabledAdvancedServices:
- YouTube — Search videos, manage playlists, read comments, upload
- Google Ads — Campaign management, keyword research, bid automation
- Classroom — Course management, assignments, rosters
- People API — Modern contacts API (replaces ContactsApp)
- Sheets API — Advanced Sheets operations (batch updates, developer metadata)
- Docs API — Advanced document manipulation
- Drive API — Advanced Drive operations (shared drives, file properties)
- Admin SDK — Full admin capabilities
Complete OAuth Scopes Reference
| Service | Scope URL |
|---|
| Sheets (full) | https://www.googleapis.com/auth/spreadsheets |
| Sheets (read) | https://www.googleapis.com/auth/spreadsheets.readonly |
| Docs | https://www.googleapis.com/auth/documents |
| Slides | https://www.googleapis.com/auth/presentations |
| Forms | https://www.googleapis.com/auth/forms |
| Drive (full) | https://www.googleapis.com/auth/drive |
| Drive (read) | https://www.googleapis.com/auth/drive.readonly |
| Drive (file only) | https://www.googleapis.com/auth/drive.file |
| Gmail (send) | https://www.googleapis.com/auth/gmail.send |
| Gmail (read) | https://www.googleapis.com/auth/gmail.readonly |
| Gmail (modify) | https://www.googleapis.com/auth/gmail.modify |
| Gmail (compose) | https://www.googleapis.com/auth/gmail.compose |
| Calendar (full) | https://www.googleapis.com/auth/calendar |
| Calendar (read) | https://www.googleapis.com/auth/calendar.readonly |
| Contacts | https://www.googleapis.com/auth/contacts |
| Tasks | https://www.googleapis.com/auth/tasks |
| BigQuery | https://www.googleapis.com/auth/bigquery |
| Analytics | https://www.googleapis.com/auth/analytics.readonly |
| External HTTP | https://www.googleapis.com/auth/script.external_request |
| UI / Menus | https://www.googleapis.com/auth/script.container.ui |
| Chat | https://www.googleapis.com/auth/chat.bot |
| YouTube | https://www.googleapis.com/auth/youtube |
| Classroom | https://www.googleapis.com/auth/classroom.courses |
Real-World Use Cases & Patterns
Use this section to recognize when /clasp is the right tool — even if the user doesn't mention Apps Script.
Email & Communication
- Mail merge from Sheets → personalized emails to hundreds of recipients
- Email digest — aggregate data from multiple sources, send daily/weekly summary
- Auto-responder — reply to emails matching certain criteria
- Email→Sheet logger — parse incoming emails and log structured data
- Slack/Telegram/Discord notifications — trigger from Sheets, Forms, or Calendar events via UrlFetchApp
Data Collection & Forms
- Complex forms with branching logic, multi-section, quizzes with scoring
- Form→Sheet→Email pipeline — collect data, process it, notify stakeholders
- Registration systems — form + capacity limits + confirmation email + calendar event
- Feedback/survey systems with auto-analysis and reporting
- File upload forms with Drive organization
Spreadsheet Automation
- Dashboard auto-refresh — pull data from external APIs into Sheets on a schedule
- Data cleaning/ETL — transform, deduplicate, validate data in Sheets
- Custom Sheet functions — extend Sheets with custom formulas
- Cross-sheet sync — keep multiple spreadsheets in sync
- Automated reporting — generate and email reports as PDF
- Inventory/stock tracking with alerts when below threshold
Document Generation
- Invoice/contract generator — template Docs + data from Sheets → personalized PDFs
- Certificate generator — bulk create from template
- Meeting notes — auto-create Docs from Calendar events with attendee list
- Letter/proposal generator with merge fields
Calendar & Scheduling
- Bulk event creation from a spreadsheet
- Calendar sync between personal and team calendars
- Booking system — form picks available slots, creates events, sends confirmations
- Standup/meeting reminders with custom logic
- Time tracking — log hours via form → Sheet → weekly report
Monitoring & Alerts
- API health monitor — ping endpoints on schedule, log to Sheet, alert on failure
- Website change detection — fetch page, compare with previous, notify on change
- Price tracker — monitor product prices, alert on drops
- Crypto/stock portfolio tracker with real-time data in Sheets
- SSL certificate expiry checker
Web Apps (free hosting)
- Simple landing pages with form submission to Sheets
- Internal dashboards — HTML/CSS/JS served from Apps Script
- Webhook receivers — accept POST data from external services
- REST API endpoints — serve JSON data from Sheets or other sources
- Approval workflows — web UI for reviewing and approving requests
Integration & Workflow
- Sheets↔Database sync via JDBC (MySQL, PostgreSQL)
- Sheets→BigQuery pipeline for analytics
- Drive file organizer — auto-sort uploads by date, type, or content
- Cross-platform sync — Google Calendar↔Notion, Sheets↔Airtable, etc.
- Zapier/Make replacement — build the same automations for free in Apps Script
- CRM lite — Sheets as database + Forms for input + email automation
Education & Admin
- Classroom integration — manage courses, assignments, grades
- Attendance tracker — Form + Sheet + parent notification
- Grade calculator with weighted scoring and auto-email to students
- Permission slip system — Form + Drive for signatures + Calendar for events
Google Ads & Marketing
- Ad performance reports — pull Google Ads data into Sheets
- Automated bid adjustments based on custom rules
- Keyword research aggregator — combine multiple data sources
- Social media scheduler — Sheet as content calendar → post via APIs
Proactive Suggestion Guide
When the user describes ANY of these scenarios outside of a /clasp invocation, suggest using Apps Script:
| User says something like... | Suggest |
|---|
| "I need to send emails from a spreadsheet" | Mail merge with GmailApp + SpreadsheetApp |
| "I want to automate Google Sheets" | Time-driven trigger + SpreadsheetApp |
| "Can I create a form programmatically?" | FormApp via clasp |
| "I need to monitor an API/website" | UrlFetchApp + time trigger + Sheet logging |
| "I want to generate PDFs/invoices/contracts" | DocumentApp template + Drive PDF export |
| "I need a simple web form that saves somewhere" | HtmlService web app + SpreadsheetApp |
| "I want to auto-create calendar events" | CalendarApp + data source |
| "I need to sync data between X and Google Sheets" | UrlFetchApp + SpreadsheetApp + trigger |
| "I want a free webhook endpoint" | ContentService web app (doPost/doGet) |
| "I need to process form responses automatically" | onFormSubmit trigger |
| "I want to send Slack/Telegram notifications from Google" | UrlFetchApp + webhook |
| "I need a simple database for a small project" | Sheets as database + Apps Script as backend |
| "I want to replace Zapier/Make for Google stuff" | Apps Script does it all natively for free |
| "I need to bulk-create Google Docs/Slides" | DocumentApp/SlidesApp + template pattern |
| "I need to organize files in Drive automatically" | DriveApp + time trigger |
| "I want to build a booking/reservation system" | Forms + Calendar + Sheets + email confirmation |
| "I need to pull data from an API into a spreadsheet" | UrlFetchApp + SpreadsheetApp + trigger |
| "I need to manage a mailing list" | Sheets as list + GmailApp for sending |
How to suggest: Don't be pushy. Say something like:
"This sounds like a great use case for Google Apps Script — I can build and deploy it from the terminal with /clasp. Want me to set it up?"
Steps
0. Preflight Checks
Before anything else:
-
Check if clasp is installed. If not:
npm install -g @google/clasp
Node.js >= 20.0.0 required.
-
Check auth status. If ~/.clasprc.json doesn't exist:
-
If inside an existing clasp project (.clasp.json exists), skip to the relevant step (push, deploy, etc.)
1. Understand the Request
Parse what the user wants to build:
- What type? Standalone script, or bound to Sheets/Forms/Docs/Slides?
- What does it do? Match against the use cases above to pick the right APIs.
- Any triggers needed? onOpen, onEdit, onFormSubmit, time-driven, etc.
- What scopes are required? Use the scopes reference table above.
- External integrations? If calling external APIs, include
script.external_request scope.
If unclear, ask before proceeding.
2. Create the Project
clasp create --title "<Project Name>" --type <standalone|sheets|forms|docs|slides>
Immediately after creation:
-
Create .claspignore to prevent pushing junk:
node_modules/**
.git/**
.github/**
README.md
package.json
package-lock.json
bun.lockb
tsconfig.json
.env
**/*.md
-
Update appsscript.json with the correct timezone and ALL required OAuth scopes.
-
If using Advanced Services (YouTube, Classroom, etc.), add them to the manifest:
{
"dependencies": {
"enabledAdvancedServices": [
{ "userSymbol": "YouTube", "version": "v3", "serviceId": "youtube" }
]
}
}
3. Write the Code
Write the Apps Script code as TypeScript files (.ts). clasp handles transpilation.
File structure convention:
project/
├── .clasp.json # Script ID (auto-generated)
├── .claspignore # Files to exclude from push
├── appsscript.json # Manifest with scopes and triggers
├── Code.ts # Main entry point
├── utils/ # Helper modules (optional)
│ └── helpers.ts
└── README.md # What this script does (not pushed)
Important Apps Script TypeScript notes:
- Use
@types/google-apps-script for type definitions (install locally for IDE support, not pushed)
- Top-level functions in
.ts files become callable from Apps Script
- No
import/export between files — Apps Script concatenates all files into one global scope
- Use namespaces or naming conventions to avoid collisions across files
Key coding patterns:
function doGet(e: GoogleAppsScript.Events.DoGet) {
return ContentService.createTextOutput(
JSON.stringify({ status: 'ok' })
).setMimeType(ContentService.MimeType.JSON);
}
function doPost(e: GoogleAppsScript.Events.DoPost) {
const data = JSON.parse(e.postData.contents);
return ContentService.createTextOutput('OK');
}
function callExternalAPI() {
const response = UrlFetchApp.fetch('https://api.example.com/data', {
method: 'get',
headers: { 'Authorization': 'Bearer ' + getApiKey() },
muteHttpExceptions: true
});
const data = JSON.parse(response.getContentText());
return data;
}
function getApiKey(): string {
return PropertiesService.getScriptProperties().getProperty('API_KEY') || '';
}
function createForm() {
const form = FormApp.create('My Form');
form.addTextItem().setTitle('Name').setRequired(true);
form.addMultipleChoiceItem()
.setTitle('Choice')
.setChoiceValues(['A', 'B', 'C']);
Logger.log('Form URL: ' + form.getEditUrl());
}
function processSheet() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('Sheet1');
const data = sheet.getDataRange().getValues();
}
function onOpen(e: GoogleAppsScript.Events.SheetsOnOpen) {
SpreadsheetApp.getUi()
.createMenu('Custom Menu')
.addItem('Run', 'myFunction')
.addToUi();
}
function createTimeTrigger() {
ScriptApp.newTrigger('myFunction')
.timeBased()
.everyHours(1)
.create();
}
function generateDocument(data: Record<string, string>) {
const templateId = 'TEMPLATE_DOC_ID';
const copy = DriveApp.getFileById(templateId).makeCopy('Generated - ' + data.name);
const doc = DocumentApp.openById(copy.getId());
const body = doc.getBody();
Object.entries(data).forEach(([key, value]) => {
body.replaceText(`{{${key}}}`, value);
});
doc.saveAndClose();
return copy.getUrl();
}
function queryDatabase() {
const conn = Jdbc.getConnection('jdbc:mysql://host:3306/db', 'user', 'pass');
const stmt = conn.createStatement();
const results = stmt.executeQuery('SELECT * FROM table');
while (results.next()) {
Logger.log(results.getString('column'));
}
conn.close();
}
4. Configure the Manifest
Update appsscript.json with ALL required scopes. Be explicit — don't rely on auto-detection.
Use the Complete OAuth Scopes Reference table above.
Example manifest:
{
"timeZone": "Europe/Rome",
"dependencies": {},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8",
"oauthScopes": [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/script.external_request"
]
}
5. Push and Test
clasp push
clasp open
Important: clasp push overwrites the remote project entirely. Never edit both locally and in the browser simultaneously.
After pushing, tell the user:
- How to run the script (which function to execute)
- If they'll see an authorization prompt on first run ("This app isn't verified" → Advanced → Go to [project] → Allow)
- Where to find output (Logger, created Form URL, Sheet data, etc.)
- If it's a web app, provide the deployment URL
6. Version and Deploy (if needed)
Only if the user needs a formal deployment (web app, API executable, add-on):
clasp version "Description of this version"
clasp deploy --description "v1.0"
clasp deployments
For web apps, after deploying:
- The URL follows the pattern:
https://script.google.com/macros/s/<deploymentId>/exec
- Set access to "Anyone" or "Anyone with Google account" depending on use case
Troubleshooting
| Problem | Solution |
|---|
| "Script API not enabled" | Visit https://script.google.com/home/usersettings and enable |
| "Permission denied" | Run clasp login again |
"Push failed — no .clasp.json" | Wrong directory, or run clasp create first |
| "This app isn't verified" warning | Advanced → Go to [project name] → Allow |
clasp run fails | Requires GCP project + OAuth client + API Executable deployment — often easier to just clasp push + clasp open |
| Files not appearing after push | Check .claspignore isn't excluding them |
| TypeScript errors on push | clasp transpiles TS → GS; check for unsupported syntax (no ES modules) |
| Quota exceeded | Apps Script has daily quotas — check https://developers.google.com/apps-script/guides/services/quotas |
| JDBC connection fails | Whitelist Apps Script IPs or use Cloud SQL with public IP |
| Web app returns HTML instead of JSON | Make sure doGet/doPost returns ContentService, not HtmlService |
clasp Command Reference
clasp login Log in to Google (interactive)
clasp logout Log out
clasp create Create a new project
clasp clone <id> Clone an existing project by script ID
clasp pull Download remote → local
clasp push Upload local → remote (overwrites remote!)
clasp push --watch Auto-push on file changes
clasp open Open in browser
clasp version Create immutable version
clasp versions List versions
clasp deploy Deploy a version
clasp deployments List deployments
clasp undeploy <id> Remove a deployment
clasp run [fn] Execute a function remotely (requires setup)
clasp logs View Stackdriver logs
clasp status Show local file status
Limits & Quotas (important to know)
- Script runtime: 6 minutes per execution (30 min for Workspace accounts)
- UrlFetchApp: 20,000 calls/day (free), 100,000 (Workspace)
- Email: 100 recipients/day (free), 1,500 (Workspace)
- Triggers: 20 triggers per user per script
- Properties store: 500KB total per store
- Cache: 100KB per cached item, 10MB total
- Drive: 250MB file creation per day
- Custom functions in Sheets: 30 seconds execution time
Important Reminders
- No
import/export — Apps Script uses a flat global scope across all files
clasp push is destructive — it replaces everything on the remote
- TypeScript is supported but transpiled; avoid features that don't map to Apps Script's V8 runtime
- First run requires authorization — the user will see a consent screen
- After pushing, always tell the user which function to run and how
- Apps Script is free — no server costs, no hosting fees, runs on Google's infrastructure
- It's essentially a free serverless platform with native Google API access