### Example .clasp.json Configuration Source: https://github.com/google/clasp/blob/master/_autodocs/utils-and-configuration.md Illustrates a typical .clasp.json setup, specifying the script ID, source directory, and file push order. Relative paths are resolved from the project root. ```json { "scriptId": "1d_gxyv_...", "srcDir": "src", "projectId": "my-gcp-project", "filePushOrder": ["src/common.js", "src/main.js"] } ``` -------------------------------- ### Install Clasp via npm Source: https://github.com/google/clasp/blob/master/README.md Install the clasp CLI globally using npm. Ensure you have Node.js and npm installed. ```sh npm install -g @google/clasp ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/google/clasp/blob/master/gemini.md Run this command to install all necessary Node.js dependencies for the project. ```bash npm install ``` -------------------------------- ### Open Google Cloud Credentials Setup Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Navigates to the Google Cloud credentials setup page, which may be required for certain integrations or configurations. ```bash clasp open-credentials-setup ``` -------------------------------- ### Open Credentials Setup Source: https://github.com/google/clasp/blob/master/docs/run.md Navigates to the Google Cloud Console to set up OAuth 2.0 client credentials. ```bash clasp open-credentials-setup ``` -------------------------------- ### ProjectFile Interface Example Source: https://github.com/google/clasp/blob/master/_autodocs/files-api.md Illustrates how to create an instance of the ProjectFile interface with sample data for a local file. ```typescript const file: ProjectFile = { localPath: 'src/main.js', remotePath: 'main', source: 'function myFunction() { ... }', type: 'SERVER_JS' }; ``` -------------------------------- ### Build Project (Compile and Install) Source: https://github.com/google/clasp/blob/master/gemini.md Compiles the TypeScript code and installs the project dependencies. ```bash npm run build ``` -------------------------------- ### Library JSON Example Source: https://github.com/google/clasp/blob/master/_autodocs/types.md Example of a library dependency configuration in the manifest. This specifies how to reference a library and its version. ```json { "userSymbol": "Logger", "libraryId": "1Mf_...", "version": "32", "developmentMode": false } ``` -------------------------------- ### CLASP Global Options Examples Source: https://github.com/google/clasp/blob/master/_autodocs/utils-and-configuration.md Examples of using global CLASP command-line options. These options can be appended to most CLASP commands to modify their behavior. ```bash # Use specific user account clasp push --user work-account # Use service account credentials clasp pull --adc # Use custom config file clasp push --project ./deploy-config.json ``` -------------------------------- ### Get Enabled Services Example Source: https://github.com/google/clasp/blob/master/_autodocs/services-logs-functions.md Retrieves and logs the names and descriptions of enabled Google Cloud Platform services for an Apps Script project. Ensure the Services module is initialized with ClaspOptions. ```typescript const enabledServices = await clasp.services.getEnabledServices(); if (enabledServices) { enabledServices.forEach(service => { console.log(`${service.name}: ${service.description}`); }); } ``` -------------------------------- ### Install CLASP as Claude Plugin Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Installs the CLASP CLI as a plugin for Claude, the recommended method for integrating CLASP with Claude's AI agent capabilities. ```bash /plugin install @google/clasp ``` -------------------------------- ### Serverless Authorization Flow Example Source: https://github.com/google/clasp/blob/master/_autodocs/auth-api.md Illustrates the serverless authorization code flow, where no local server is started. Users must manually copy the authorization code from the browser. ```typescript const flow = new ServerlessAuthorizationCodeFlow({ clientId: '...', clientSecret: '...', redirectUrl: 'urn:ietf:wg:oauth:2.0:oob', scopes: ['...'] }); const tokens = await flow.authorize(); // User will be prompted to manually enter code from browser ``` -------------------------------- ### Get Available Services Example Source: https://github.com/google/clasp/blob/master/_autodocs/services-logs-functions.md Retrieves and logs the names of all publicly available Google Advanced Services that can be enabled for an Apps Script project. Ensure the Services module is initialized with ClaspOptions. ```typescript const available = await clasp.services.getAvailableServices(); if (available) { available.forEach(service => { console.log(`Available: ${service.name}`); }); } ``` -------------------------------- ### Complete CLASP Workflow Example Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Illustrates a typical CLASP workflow from authentication and cloning to making changes, pushing, versioning, deploying, monitoring logs, and executing functions. ```bash # 1. Setup authentication clasp login --creds ./client_secret.json # 2. Clone existing project clasp clone-script 1d_gxyv_... --rootDir ./my-project # 3. View current status clasp show-file-status # 4. Make changes locally # ... edit files ... # 5. Push changes clasp push # 6. Create version clasp create-version "Release v1.0" # 7. Deploy clasp create-deployment --description "Production release" # 8. Monitor logs clasp tail-logs --watch # 9. Execute functions clasp run-function myFunction --params '["arg1", "arg2"]' ``` -------------------------------- ### Install Clasp as Claude Code CLI Plugin Source: https://github.com/google/clasp/blob/master/README.md Install clasp as a plugin within Claude Code CLI for recommended integration. This command directly installs the plugin from the repository. ```sh /plugin install @google/clasp ``` -------------------------------- ### Webapp JSON Example Source: https://github.com/google/clasp/blob/master/_autodocs/types.md Example of web app configuration in the manifest. This sets access to 'ANYONE' and execution as the user accessing the app. ```json { "access": "ANYONE", "executeAs": "USER_ACCESSING" } ``` -------------------------------- ### ExecutionApi JSON Example Source: https://github.com/google/clasp/blob/master/_autodocs/types.md Example of Execution API configuration in the manifest. This allows 'ANYONE' to execute the script via the API. ```json { "access": "ANYONE" } ``` -------------------------------- ### Start MCP Server Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Starts the Model Context Protocol (MCP) server, enabling integration with AI coding assistants like Claude for programmatic Apps Script project management. ```bash clasp mcp ``` -------------------------------- ### FileCredentialStore Example Usage Source: https://github.com/google/clasp/blob/master/_autodocs/auth-api.md Demonstrates how to use the FileCredentialStore to load and save user credentials to a specified JSON file. ```typescript const store = new FileCredentialStore('/path/to/.clasprc.json'); // Load const creds = await store.load('my-user'); // Save await store.save('my-user', { type: 'authorized_user', client_id: '...', client_secret: '...', refresh_token: '...' }); ``` -------------------------------- ### Sample .claspignore for specific file inclusions Source: https://github.com/google/clasp/blob/master/README.md Use this pattern to ignore all files by default and then explicitly include specific files like the manifest and a build script. This is useful for tightly controlling what gets uploaded. ```text **/** !build/main.js !appsscript.json ``` -------------------------------- ### Manifest JSON Example Source: https://github.com/google/clasp/blob/master/_autodocs/types.md An example of a complete Apps Script manifest file in JSON format. This shows how to configure time zone, OAuth scopes, execution API, and dependencies. ```json { "timeZone": "America/New_York", "oauthScopes": [ "https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/drive" ], "executionApi": { "access": "ANYONE" }, "dependencies": { "libraries": [ { "userSymbol": "SS", "libraryId": "1Mf...", "version": "32" } ] } } ``` -------------------------------- ### Install Clasp as Gemini CLI Extension Source: https://github.com/google/clasp/blob/master/README.md Install clasp as a Gemini CLI extension for integration with Gemini CLI. This makes clasp available as an MCP server. ```sh gemini extensions install https://github.com/google/clasp ``` -------------------------------- ### Setup Logs with CLASP Source: https://github.com/google/clasp/blob/master/README.md Command to set up logging for your Apps Script project. Can output logs in JSON format. ```sh clasp setup-logs [--json] ``` -------------------------------- ### CLASP Configuration for Script Extensions Source: https://github.com/google/clasp/blob/master/_autodocs/files-api.md Example of how to configure custom file extensions for server-side scripts and HTML files within the `.clasp.json` configuration file. ```json { "scriptExtensions": [".js", ".gs"], "htmlExtensions": [".html"] } ``` -------------------------------- ### Setup Logs with Clasp Source: https://github.com/google/clasp/blob/master/README.md Configures your script with a GCP project ID to enable viewing logs in Cloud Logging. Use the --json flag for JSON output. ```bash clasp setup-logs ``` ```bash clasp setup-logs --json ``` -------------------------------- ### File Extension Mappings Example Source: https://github.com/google/clasp/blob/master/_autodocs/types.md Illustrates the structure for mapping file types to their corresponding extensions, used in file operations. ```typescript { 'SERVER_JS': ['.js', '.gs'], 'HTML': ['.html'], 'JSON': ['.json'] } ``` -------------------------------- ### EnabledAdvancedService JSON Example Source: https://github.com/google/clasp/blob/master/_autodocs/types.md Example of configuring an enabled advanced service in the manifest. This includes the user symbol, service ID, and version. ```json { "userSymbol": "Sheets", "serviceId": "sheets", "version": "v4" } ``` -------------------------------- ### CI/CD Integration with CLASP Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Provides examples for integrating CLASP into CI/CD pipelines using Application Default Credentials (ADC). This method is suitable for service accounts. ```bash # In CI/CD with service account export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json clasp pull --adc clasp push --adc --force clasp create-deployment --adc --description "CI deployment" ``` -------------------------------- ### Example .clasp.json configuration Source: https://github.com/google/clasp/blob/master/README.md This JSON file configures CLASP settings for a project. It specifies the target script ID, the root directory for local files, the Google Cloud project ID, and file extensions. ```json { "scriptId": "", "rootDir": "build/", "projectId": "project-id-xxxxxxxxxxxxxxxxxxx", "fileExtension": "ts", "filePushOrder": ["file1.ts", "file2.ts"] } ``` -------------------------------- ### CLASP Version Display Commands Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Shows how to display the installed CLASP CLI version. Use either the long `--version` flag or the short `-v` flag. ```bash clasp --version clasp -v ``` -------------------------------- ### Custom .claspignore Patterns Example Source: https://github.com/google/clasp/blob/master/_autodocs/utils-and-configuration.md Demonstrates how to define custom exclusion patterns in a .claspignore file to ignore specific files and directories like test files, node_modules, and build artifacts. ```ignore # Ignore test files **/*test.js **/test/** # Ignore node_modules node_modules/** # Ignore build artifacts build/** dist/** # Ignore hidden files .* # But allow these specific files !.editorconfig !.gitkeep ``` -------------------------------- ### Initialize Clasp Instance Source: https://github.com/google/clasp/blob/master/_autodocs/clasp-core.md Instantiate the Clasp class with configuration options including credentials, project settings, and file synchronization settings. This is the primary way to start using the Clasp core API. ```typescript import { Clasp } from '@google/clasp'; const clasp = new Clasp({ credentials: oauth2Client, configFilePath: '/path/to/.clasp.json', files: { projectRootDir: '/path/to/project', contentDir: '/path/to/project/src', ignoreFilePath: '/path/to/.claspignore', ignorePatterns: ['node_modules/**', '.git/**'], filePushOrder: ['common.js', 'main.js'], skipSubdirectories: false, fileExtensions: { 'SERVER_JS': ['.js', '.gs'], 'HTML': ['.html'], 'JSON': ['.json'] } }, project: { scriptId: 'your-script-id', projectId: 'your-gcp-project-id', parentId: undefined } }); ``` -------------------------------- ### CLASP MCP Server Configuration Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Example JSON configuration file for the CLASP MCP server. This file specifies the command, arguments, and environment variables for running the MCP server. ```json { "name": "clasp", "type": "stdio", "command": "npx", "args": [ "-y", "@google/clasp", "mcp" ], "env": { "DEBUG": "clasp:*" } } ``` -------------------------------- ### Local Server Authorization Flow Example Source: https://github.com/google/clasp/blob/master/_autodocs/auth-api.md Demonstrates how to initiate the OAuth authorization code flow using a local HTTP server to handle the callback. This is suitable for interactive CLI applications. ```typescript const flow = new LocalServerAuthorizationCodeFlow({ clientId: '...', clientSecret: '...', redirectUrl: 'http://localhost:8888', scopes: ['...'] }); const tokens = await flow.authorize(); console.log('Got tokens:', tokens); ``` -------------------------------- ### Apps Script Execution API Configuration Source: https://github.com/google/clasp/blob/master/_autodocs/services-logs-functions.md Example of the required `executionApi` configuration in `appsscript.json` to make a script executable via the API. ```json { "executionApi": { "access": "ANYONE" } } ``` -------------------------------- ### Type Guard Usage Example Source: https://github.com/google/clasp/blob/master/_autodocs/types.md Demonstrates how to use type guard functions like assertAuthenticated and assertScriptConfigured to enforce type safety and handle potential errors during runtime. ```typescript assertAuthenticated(clasp.options); // Now TypeScript knows clasp.options.credentials is defined try { assertScriptConfigured(clasp.options); // Use clasp.options.project.scriptId safely } catch (error) { console.error('Script not configured'); } ``` -------------------------------- ### Initialize CLASP and Push Files Source: https://github.com/google/clasp/blob/master/_autodocs/README.md Demonstrates how to initialize a CLASP instance with authentication credentials and push local files to a Google Apps Script project. It also shows how to create a new version and deploy it. ```typescript import { initClaspInstance, initAuth } from '@google/clasp'; import { OAuth2Client } from 'google-auth-library'; // Initialize authentication const authInfo = await initAuth({ userKey: 'my-user' }); if (!authInfo.credentials) { throw new Error('Not authenticated. Run: clasp login'); } // Initialize Clasp instance const clasp = await initClaspInstance({ credentials: authInfo.credentials, configFile: './.clasp.json' }); // Push local files await clasp.files.push(); // Create version const versionNum = await clasp.project.version('v1.0'); // Deploy const deployment = await clasp.project.deploy( 'Production release', undefined, versionNum ); console.log(`Deployed as ${deployment.deploymentId}`); ``` -------------------------------- ### initClaspInstance Source: https://github.com/google/clasp/blob/master/_autodocs/clasp-core.md Initializes and returns a Clasp instance. It searches for project configuration files (.clasp.json, .claspignore), loads them if found, or sets up default configurations if not. This function is the primary entry point for creating a Clasp instance. ```APIDOC ## initClaspInstance(options) ### Description Initializes and returns a Clasp instance. Searches for project configuration files (`.clasp.json`, `.claspignore`), loads them if found, or sets up default configurations if not. This is the primary entry point for creating a Clasp instance. ### Method `async function` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options.credentials** (OAuth2Client) - Optional - Optional OAuth2 client for authentication - **options.configFile** (string) - Optional - Path to .clasp.json file or its directory - **options.ignoreFile** (string) - Optional - Path to .claspignore file or its directory - **options.rootDir** (string) - Optional - Project root directory if no config found (defaults to process.cwd()) ### Request Example ```typescript import { OAuth2Client } from 'google-auth-library'; import { initClaspInstance } from '@google/clasp'; const credentials = new OAuth2Client(); const clasp = await initClaspInstance({ credentials, configFile: './path/to/.clasp.json', rootDir: process.cwd() }); // Now use clasp instance const scriptId = clasp.project.scriptId; ``` ### Response #### Success Response - **Clasp instance**: A configured Clasp instance. #### Response Example ```typescript // Example of a Clasp instance (structure not fully defined in source) { project: { scriptId: 'YOUR_SCRIPT_ID' } // ... other properties } ``` ### Throws - Error if srcDir in .clasp.json escapes project root (security validation). ``` -------------------------------- ### Initialize CLASP Instance Source: https://github.com/google/clasp/blob/master/_autodocs/clasp-core.md Initializes and returns a CLASP instance. Searches for project configuration files or sets up defaults. Use this as the primary entry point for creating a CLASP instance. ```typescript import { OAuth2Client } from 'google-auth-library'; import { initClaspInstance } from '@google/clasp'; const credentials = new OAuth2Client(); const clasp = await initClaspInstance({ credentials, configFile: './path/to/.clasp.json', rootDir: process.cwd() }); // Now use clasp instance const scriptId = clasp.project.scriptId; ``` -------------------------------- ### Open Clasp Project Source: https://github.com/google/clasp/blob/master/docs/Gitpod/README.md Open the currently created project in your browser. ```bash clasp open ``` -------------------------------- ### Navigate to Gitpod Directory Source: https://github.com/google/clasp/blob/master/docs/Gitpod/README.md Change to the docs/Gitpod/ directory to begin. ```bash cd docs/Gitpod/ ``` -------------------------------- ### Display Clasp Help Source: https://github.com/google/clasp/blob/master/README.md Shows the help information for the Clasp CLI. ```bash clasp ``` ```bash clasp help ``` -------------------------------- ### Managing Multiple CLASP Accounts Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Demonstrates how to set up and use multiple CLASP accounts by specifying a user alias during login and subsequent commands. This is useful for managing different projects or environments. ```bash # Setup multiple users clasp login --user personal clasp login --user work # Use specific account clasp push --user work clasp pull --user personal ``` -------------------------------- ### Clasp CLI Help Source: https://github.com/google/clasp/blob/master/README.md Display the main help information for the clasp CLI, listing available commands and their basic usage. ```sh clasp ``` -------------------------------- ### Check NodeJS Version Source: https://github.com/google/clasp/blob/master/README.md Command to check the installed NodeJS version. The library requires NodeJS version >= 22.0.0. ```sh node -v ``` -------------------------------- ### Apps Script Function Executable via API Source: https://github.com/google/clasp/blob/master/_autodocs/services-logs-functions.md Example of a simple Apps Script function that can be called via the Execution API. ```typescript // In appsscript.json { "executionApi": { "access": "ANYONE" } } // In script code function myFunction(param1) { // This function is now executable via the Execution API return { result: param1 * 2 }; } // Call via Functions.runFunction() const response = await clasp.functions.runFunction('myFunction', [5]); // response = {result: 10} ``` -------------------------------- ### Login and Run Function with Specific User Source: https://github.com/google/clasp/blob/master/README.md Demonstrates how to log in with named credentials and run a function using a specific user account. Use the `--user` flag to specify the account. ```sh clasp login # Saves as default credentials clasp clone # User not specified, runs using default credentials clasp login --user testaccount # Authorized new named credentials clasp run-function --user testaccount myFunction # Runs function as test account ``` -------------------------------- ### Get Access Token Source: https://github.com/google/clasp/blob/master/_autodocs/auth-api.md Exchanges an authorization code received from the OAuth flow for an access token. This method is part of the authorization process. ```typescript async getAccessToken(code: string): Promise ``` -------------------------------- ### Retrieve GCP Project ID Source: https://github.com/google/clasp/blob/master/_autodocs/project-api.md Get the Google Cloud Platform (GCP) project ID associated with the script. This method asserts that the script is configured. ```typescript try { const projectId = clasp.project.getProjectId(); console.log(`GCP Project: ${projectId}`); } catch (error) { console.error('Script not configured'); } ``` -------------------------------- ### Get Authenticated User ID Source: https://github.com/google/clasp/blob/master/_autodocs/clasp-core.md Retrieve the ID of the currently authenticated user. Returns undefined if not authenticated or if the ID is unavailable. This method does not throw errors. ```typescript const userId = await clasp.authorizedUser(); if (userId) { console.log(`Logged in as: ${userId}`); } else { console.log('Not authenticated'); } ``` -------------------------------- ### Get Recent Log Entries Source: https://github.com/google/clasp/blob/master/_autodocs/README.md Retrieves recent log entries from CLASP. You can fetch all recent logs or logs since a specific date and time. ```typescript // Get recent logs const logs = await clasp.logs.getLogEntries(); logs?.results.forEach(entry => { console.log(`[${entry.severity}] ${entry.textPayload}`); }); // Logs since specific time const since = new Date(Date.now() - 3600000); // Last hour const recentLogs = await clasp.logs.getLogEntries(since); ``` -------------------------------- ### LocalServerAuthorizationCodeFlow.authorize Source: https://github.com/google/clasp/blob/master/_autodocs/auth-api.md Runs the complete OAuth authorization flow using a local HTTP server. It starts the server, opens the browser for authentication, and returns the obtained tokens. ```APIDOC ## LocalServerAuthorizationCodeFlow.authorize ### Description Runs the complete OAuth authorization flow. Starts a local server, opens the browser for user authentication, and returns tokens. ### Method authorize ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const flow = new LocalServerAuthorizationCodeFlow({ clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', redirectUrl: 'http://localhost:8888', scopes: ['scope1', 'scope2'] }); const tokens = await flow.authorize(); console.log('Got tokens:', tokens); ``` ### Response #### Success Response (200) - **accessToken** (string) - The obtained access token. - **refreshToken** (string) - The obtained refresh token. - **expiresIn** (number) - The expiration time of the access token in seconds. #### Response Example ```json { "accessToken": "ACCESS_TOKEN_STRING", "refreshToken": "REFRESH_TOKEN_STRING", "expiresIn": 3600 } ``` ``` -------------------------------- ### Get User Information Source: https://github.com/google/clasp/blob/master/_autodocs/auth-api.md Fetches the logged-in user's email and ID using an authorized OAuth2 client. Returns undefined if user information cannot be retrieved. ```typescript const user = await getUserInfo(credentials); if (user) { console.log(`Logged in as: ${user.email}`); } else { console.log('Unable to fetch user info'); } ``` -------------------------------- ### Get Function Names Source: https://github.com/google/clasp/blob/master/_autodocs/services-logs-functions.md Retrieves a list of all function names in the Apps Script project by parsing script content. Use this to discover available functions for execution. ```typescript async getFunctionNames(): Promise ``` ```typescript const functions = await clasp.functions.getFunctionNames(); console.log('Available functions:', functions); // Output: ['myFunction', 'anotherFunction', 'doGet', 'doPost'] ``` -------------------------------- ### Get Untracked Local Files Source: https://github.com/google/clasp/blob/master/_autodocs/files-api.md Retrieves the file paths of local files that are not currently managed by clasp, either because they are ignored or do not match configured file extensions. ```typescript const untracked = await clasp.files.getUntrackedFiles(); untracked.forEach(filePath => { console.log(`Untracked: ${filePath}`); }); ``` -------------------------------- ### Add CLASP MCP Tool Manually Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Manually adds the CLASP MCP tool to your Claude environment using the command line. This method is an alternative to plugin installation. ```bash claude mcp add clasp -- npx -y @google/clasp mcp ``` -------------------------------- ### Login with Custom Credentials and Port Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Log in using a custom client secrets file and specify a redirect port. Useful for specific development environments. ```bash clasp login --creds ./client_secret.json --redirect-port 3000 ``` -------------------------------- ### Get Unauthorized OAuth2 Client Source: https://github.com/google/clasp/blob/master/_autodocs/auth-api.md Creates an OAuth2 client instance that is not yet authenticated. This is useful for initiating authorization flows or when using custom client secret files. ```typescript // Use default Clasp OAuth client const client = getUnauthorizedOuth2Client(); // Use custom OAuth client credentials const customClient = getUnauthorizedOuth2Client('./client_secret.json'); ``` -------------------------------- ### Run Project Tests Source: https://github.com/google/clasp/blob/master/gemini.md Executes the test suite for the project using the configured testing framework. ```bash npm test ``` -------------------------------- ### Get Modified Local Files Source: https://github.com/google/clasp/blob/master/_autodocs/files-api.md Identifies and returns local files that have been changed since the last synchronization. This is useful for determining which files require an update on the remote project. ```typescript const changedFiles = await clasp.files.getChangedFiles(); if (changedFiles.length === 0) { console.log('No changes to push'); } ``` -------------------------------- ### Manually Add Clasp as Claude MCP Server Source: https://github.com/google/clasp/blob/master/README.md Manually add clasp as an MCP server in Claude Code CLI using npx. This method is an alternative to plugin installation. ```sh claude mcp add clasp -- npx -y @google/clasp mcp ``` -------------------------------- ### Clasp List Deployments Source: https://github.com/google/clasp/blob/master/README.md List all existing deployments for the current Apps Script project. ```sh clasp list-deployments ``` -------------------------------- ### Get OAuth Client Type Source: https://github.com/google/clasp/blob/master/_autodocs/auth-api.md Determines if a given client ID corresponds to the default Google-provided client or a user-provided custom client. Returns undefined if no client ID is supplied. ```typescript const type = getOAuthClientType('1072944905499-...'); console.log(type); // 'google-provided' const type2 = getOAuthClientType('my-custom-client-id'); console.log(type2); // 'user-provided' ``` -------------------------------- ### Clasp List Versions Source: https://github.com/google/clasp/blob/master/README.md List all available versions of the Apps Script project. ```sh clasp list-versions ``` -------------------------------- ### Create a New Clasp Project Source: https://github.com/google/clasp/blob/master/docs/Gitpod/README.md Create a new standalone Google Apps Script project with a specified title. ```bash clasp create --title "Clasp Demo" --type standalone ``` -------------------------------- ### Get Log Entries Source: https://github.com/google/clasp/blob/master/_autodocs/services-logs-functions.md Retrieves log entries from Google Cloud Logging. Logs are fetched in descending order of timestamp. Use 'since' parameter to filter logs by date. ```typescript async getLogEntries(since?: Date): Promise<{results: LogEntry[]; partialResults: boolean} | undefined> ``` ```typescript // Get all recent logs const logs = await clasp.logs.getLogEntries(); if (logs) { console.log(`Retrieved ${logs.results.length} log entries`); if (logs.partialResults) { console.log('Results were truncated'); } } ``` ```typescript // Get logs since specific date const since = new Date(Date.now() - 3600000); // Last hour const recentLogs = await clasp.logs.getLogEntries(since); ``` -------------------------------- ### FileCredentialStore Constructor Source: https://github.com/google/clasp/blob/master/_autodocs/auth-api.md Initializes the FileCredentialStore with the path to the JSON file where credentials will be stored. ```APIDOC ## FileCredentialStore Constructor ### Description Initializes the FileCredentialStore with the path to the JSON file where credentials will be stored. ### Method constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **filePath** (string) - Yes - The path to the JSON file (e.g., `~/.clasprc.json`). ### Request Example ```typescript const store = new FileCredentialStore('/path/to/.clasprc.json'); ``` ### Response #### Success Response (200) N/A (Constructor does not return a value directly) #### Response Example N/A ``` -------------------------------- ### Clasp Class Constructor Source: https://github.com/google/clasp/blob/master/_autodocs/clasp-core.md Initializes a new Clasp instance with provided configuration options. This is the primary entry point for interacting with the Clasp core API. ```APIDOC ## Clasp Class Constructor ### Description Initializes a new Clasp instance with provided configuration options. This is the primary entry point for interacting with the Clasp core API. ### Method Signature ```typescript constructor(options: ClaspOptions) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (ClaspOptions) - Required - Configuration options including credentials, project settings, and file configuration. ### Request Example ```typescript import { Clasp } from '@google/clasp'; const clasp = new Clasp({ credentials: oauth2Client, configFilePath: '/path/to/.clasp.json', files: { projectRootDir: '/path/to/project', contentDir: '/path/to/project/src', ignoreFilePath: '/path/to/.claspignore', ignorePatterns: ['node_modules/**', '.git/**'], filePushOrder: ['common.js', 'main.js'], skipSubdirectories: false, fileExtensions: { 'SERVER_JS': ['.js', '.gs'], 'HTML': ['.html'], 'JSON': ['.json'] } }, project: { scriptId: 'your-script-id', projectId: 'your-gcp-project-id', parentId: undefined } }); ``` ### Response #### Success Response N/A (Constructor) #### Response Example N/A (Constructor) ``` -------------------------------- ### Disable Service Example Source: https://github.com/google/clasp/blob/master/_autodocs/services-logs-functions.md Disables a specified Google Advanced Service (e.g., 'docs') for the Apps Script project, removing it from the manifest and disabling it in GCP. Assumes the Services module is initialized. ```typescript await clasp.services.disableService('docs'); console.log('Docs API disabled'); ``` -------------------------------- ### `updateSettings()` Source: https://github.com/google/clasp/blob/master/_autodocs/project-api.md Persists current project settings, such as scriptId and projectId, to the local `.clasp.json` file. ```APIDOC ## `updateSettings()` ### Description Persists project settings (scriptId, projectId, etc.) to the local `.clasp.json` file. ### Method POST ### Endpoint /project/updateSettings ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **void** #### Response Example ```json null ``` **Throws:** - Error with code 'UNCONFIGURED_SCRIPT' if script ID is not configured - File system errors if unable to write .clasp.json ``` -------------------------------- ### Login to CLASP Source: https://github.com/google/clasp/blob/master/README.md Logs the user in and saves client credentials. Use --no-localhost to manually enter the code. Custom credentials can be specified with --creds. ```bash clasp login ``` ```bash clasp login --no-localhost ``` ```bash clasp login --user test-user --creds client_secret.json ``` ```bash clasp login --user test-user --use-project-scopes --creds client_secret.json ``` ```bash clasp login --user test-user --use-project-scopes --include-clasp-scopes --creds client_secret.json ``` ```bash clasp login --user test-user --extra-scopes https://www.googleapis.com/auth/spreadsheets.readonly,https://www.googleapis.com/auth/drive.readonly --creds client_secret.json ``` ```bash clasp login --redirect-port 37473 ``` -------------------------------- ### Login Using Project Scopes Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Authenticate using OAuth scopes defined in the project's appsscript.json file. Ensures the correct permissions are requested for the project. ```bash clasp login --use-project-scopes ``` -------------------------------- ### Add Clasp using Claude MCP JSON Configuration Source: https://github.com/google/clasp/blob/master/README.md Manually add clasp as an MCP server in Claude Code CLI by referencing a provided JSON configuration file. This is useful for custom setups. ```sh claude mcp add-json clasp "$(cat claude-mcp.json)" ``` -------------------------------- ### deploy(description?, deploymentId?, versionNumber?) Source: https://github.com/google/clasp/blob/master/_autodocs/project-api.md Creates a new deployment or updates an existing one. A deployment makes a version of the script available for execution. Returns the Deployment object from the API. ```APIDOC ## deploy(description?, deploymentId?, versionNumber?) ### Description Creates a new deployment or updates an existing one. A deployment makes a version of the script available for execution. ### Method async ### Endpoint project.deploy(description?, deploymentId?, versionNumber?) ### Parameters #### Path Parameters - **description** (string) - Optional - Description of this deployment - **deploymentId** (string) - Optional - ID of existing deployment to update; if provided, creates new version and updates deployment - **versionNumber** (number) - Optional - Version number to deploy; if omitted, creates new version automatically ### Returns The Deployment object from the API containing deploymentId, versionNumber, etc. ### Throws - Error with code 'UNAUTHENTICATED' if credentials are missing - Error with code 'UNCONFIGURED_SCRIPT' if script ID is not configured - GaxiosError if API call fails ### Example ```javascript // Create new deployment const deployment = await clasp.project.deploy('Stable release'); console.log(`Deployed as ${deployment.deploymentId}`); // Update existing deployment const updated = await clasp.project.deploy( 'Bug fixes', 'existing-deployment-id' ); ``` ``` -------------------------------- ### Run CLASP CLI Locally Source: https://github.com/google/clasp/blob/master/gemini.md Executes the CLASP command-line interface locally for development purposes. Replace `` with the desired CLASP command. ```bash npm run clasp -- ``` ```bash npm run clasp -- list-scripts ``` -------------------------------- ### listVersions() Source: https://github.com/google/clasp/blob/master/_autodocs/project-api.md Lists all versions of the script project. Returns an array of version objects or undefined on error. ```APIDOC ## listVersions() ### Description Lists all versions of the script project. ### Method async ### Endpoint project.listVersions() ### Parameters None ### Returns Array of version objects with versionNumber, description, and createTime, or undefined on error. ### Example ```javascript const versions = await clasp.project.listVersions(); if (versions) { versions.forEach(v => { console.log(`v${v.versionNumber}: ${v.description} (${v.createTime})`); }); } ``` ``` -------------------------------- ### Enable Service Example Source: https://github.com/google/clasp/blob/master/_autodocs/services-logs-functions.md Enables a specified Google Advanced Service (e.g., 'sheets') for the Apps Script project. This method updates both the GCP project and the appsscript.json manifest. Includes error handling for common issues. ```typescript try { await clasp.services.enableService('sheets'); console.log('Sheets API enabled'); } catch (error) { console.error('Failed to enable service:', error.message); } ``` -------------------------------- ### Deploy Script Project Source: https://github.com/google/clasp/blob/master/_autodocs/project-api.md Creates a new deployment or updates an existing one. Can optionally take a description, deployment ID, and version number. Returns the deployment object. ```typescript // Create new deployment const deployment = await clasp.project.deploy('Stable release'); console.log(`Deployed as ${deployment.deploymentId}`); // Update existing deployment const updated = await clasp.project.deploy( 'Bug fixes', 'existing-deployment-id' ); ``` -------------------------------- ### Push Local Files to Apps Script Project Source: https://github.com/google/clasp/blob/master/_autodocs/files-api.md Pushes all local files to the remote Apps Script project. Ignores files starting with '.', files without accepted extensions, or those matching patterns in `.claspignore`. This operation replaces the entire remote project content. ```typescript async push(): Promise ``` ```typescript try { await clasp.files.push(); console.log('Files pushed successfully'); } catch (error) { if (error.cause?.code === 'FILE_CONFLICT') { console.error('Filename conflict detected'); } else { console.error('Push failed:', error.message); } } ``` -------------------------------- ### Default .claspignore Patterns Source: https://github.com/google/clasp/blob/master/_autodocs/utils-and-configuration.md Shows the default patterns used by .claspignore if the file is not present. It ignores all files by default, then explicitly includes common Apps Script file types. ```ignore # Ignore all files... **/** # Except the extensions we care about... !appsscript.json !**/*.gs !**/*.js !**/*.ts !**/*.html # Ignore even valid files if in... .git/** node_modules/** ``` -------------------------------- ### Constructor Options Source: https://github.com/google/clasp/blob/master/_autodocs/auth-api.md Defines the options required for initializing an authorization flow, including client credentials, redirect URL, and requested OAuth scopes. ```typescript constructor(options: { clientId: string; clientSecret: string; redirectUrl: string; scopes: string[]; }) ``` -------------------------------- ### Clasp Create Deployment Source: https://github.com/google/clasp/blob/master/README.md Create a new deployment for the Apps Script project. Specify the version number, description, and optionally a deployment ID. ```sh clasp create-deployment [--versionNumber ] [--description ] [--deploymentId ] ``` -------------------------------- ### Create Script with Parent ID and Root Directory Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Create a new Apps Script project bound to a specific Google Drive file and set the local root directory for project files. ```bash clasp create-script --parentId "1D_Gxyv..." --rootDir ./src ``` -------------------------------- ### `exists()` Source: https://github.com/google/clasp/blob/master/_autodocs/project-api.md Checks if the local `.clasp.json` configuration file exists in the project directory. ```APIDOC ## `exists()` ### Description Checks if the local `.clasp.json` file exists. ### Method GET ### Endpoint /project/exists ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **boolean** - true if .clasp.json exists, false otherwise. #### Response Example ```json true ``` ``` -------------------------------- ### Manage Services with CLASP Source: https://github.com/google/clasp/blob/master/_autodocs/README.md Illustrates how to interact with Google Apps Script services using the CLASP library. This includes listing available services, enabling a specific service, and retrieving a list of currently enabled services. ```typescript // List available services const services = await clasp.services.getAvailableServices(); services?.forEach(s => console.log(`${s.name}: ${s.description}`)); // Enable a service await clasp.services.enableService('sheets'); // Get enabled services const enabled = await clasp.services.getEnabledServices(); ``` -------------------------------- ### Create a New Script Project with CLASP Source: https://github.com/google/clasp/blob/master/README.md Creates a new script project. Specify the type, title, root directory, or parent ID for bound scripts. ```bash clasp create-script ``` ```bash clasp create-script --type standalone ``` ```bash clasp create-script --type docs ``` ```bash clasp create-script --type sheets ``` ```bash clasp create-script --type slides ``` ```bash clasp create-script --type forms ``` ```bash clasp create-script --type webapp ``` ```bash clasp create-script --type api ``` ```bash clasp create-script --title "My Script" ``` ```bash clasp create-script --rootDir ./dist ``` ```bash clasp create-script --parentId "1D_Gxyv*****************************NXO7o" ``` ```bash clasp create-script --title "My Script" --parentId "1D_Gxyv*****************************NXO7o" --rootDir ./dist ``` -------------------------------- ### List Available APIs with CLASP Source: https://github.com/google/clasp/blob/master/README.md Command to list all available APIs that can be enabled for your Google Apps Script project. ```sh clasp list-apis ``` -------------------------------- ### Open Google Cloud API Console Source: https://github.com/google/clasp/blob/master/README.md Opens the Google Cloud Console for managing API access. ```bash clasp open-api-console ``` -------------------------------- ### List All Script Deployments Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Retrieves a list of all existing deployments for the current Apps Script project. ```bash clasp list-deployments ``` -------------------------------- ### Execute Functions with CLASP Source: https://github.com/google/clasp/blob/master/_autodocs/README.md Shows how to retrieve a list of available functions within a Google Apps Script project and then execute a specific function with provided arguments using the CLASP library. ```typescript // Get list of functions const functions = await clasp.functions.getFunctionNames(); console.log('Available functions:', functions); // Execute a function const result = await clasp.functions.runFunction('myFunction', [arg1, arg2]); console.log('Result:', result); ``` -------------------------------- ### List All Script Versions Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Retrieves a list of all created versions for the current Apps Script project. ```bash clasp list-versions ``` -------------------------------- ### Login with CLASP using Credentials File Source: https://github.com/google/clasp/blob/master/README.md Authorizes CLASP using a provided credentials file. This is part of the process for bringing your own OAuth client. ```sh clasp login --creds ``` -------------------------------- ### Open Apps Script Project Source: https://github.com/google/clasp/blob/master/docs/run.md Opens the Apps Script project in the browser for editing, deployment, or property configuration. ```bash clasp open-script ``` -------------------------------- ### createApplicationDefaultCredentials Source: https://github.com/google/clasp/blob/master/_autodocs/auth-api.md Creates an OAuth2 client using Application Default Credentials (ADC) from the environment. Used in CI/CD pipelines with service accounts. ```APIDOC ## createApplicationDefaultCredentials() ### Description Creates an OAuth2 client using Application Default Credentials (ADC) from the environment. Used in CI/CD pipelines with service accounts. ### Method async ### Returns An authorized OAuth2 client using ADC. ### Throws Error if ADC are not available in the environment. ### Request Example ```typescript // In CI/CD environment with GOOGLE_APPLICATION_CREDENTIALS set const credentials = await createApplicationDefaultCredentials(); console.log('Using service account credentials'); ``` ``` -------------------------------- ### Open Google Cloud Console Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Opens the Google Cloud console for the associated project, providing access to various cloud services and configurations. ```bash clasp open-api-console ``` -------------------------------- ### Initialize Authentication Source: https://github.com/google/clasp/blob/master/_autodocs/auth-api.md Initializes the authentication process, loading existing credentials or preparing for a new authorization flow. Use this to set up the auth environment with custom user keys or credential file paths. ```typescript import { initAuth } from '@google/clasp'; const authInfo = await initAuth({ userKey: 'my-account', authFilePath: '/path/to/.clasprc.json' }); if (authInfo.credentials) { console.log('Already logged in'); } else { console.log('Need to run authorize()'); } ``` -------------------------------- ### Configure Project ID in .clasp.json Source: https://github.com/google/clasp/blob/master/docs/run.md Ensure your `.clasp.json` file contains the `projectId` to link your script to a Google Cloud Platform project. ```json { "scriptId": "...", "projectId": "my-sample-project-191923" } ``` -------------------------------- ### Create New Script Version Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Creates an immutable version of the current script. An optional description can be provided for the version. ```bash clasp create-version ``` ```bash clasp create-version "Release v1.0" ``` -------------------------------- ### List Script Versions Source: https://github.com/google/clasp/blob/master/_autodocs/project-api.md Lists all available versions of the script project, including their version number, description, and creation time. Returns undefined if an error occurs. ```typescript const versions = await clasp.project.listVersions(); if (versions) { versions.forEach(v => { console.log(`v${v.versionNumber}: ${v.description} (${v.createTime})`); }); } ``` -------------------------------- ### version(description?) Source: https://github.com/google/clasp/blob/master/_autodocs/project-api.md Creates an immutable version of the current script project. Versions are snapshots that can be deployed. Returns the version number of the newly created version. ```APIDOC ## version(description?) ### Description Creates an immutable version of the current script project. Versions are snapshots that can be deployed. ### Method async ### Endpoint project.version(description?) ### Parameters #### Path Parameters - **description** (string) - Optional - Description of this version ### Returns The version number of the newly created version. ### Throws - Error with code 'UNAUTHENTICATED' if credentials are missing - Error with code 'UNCONFIGURED_SCRIPT' if script ID is not configured - GaxiosError if API call fails ### Example ```javascript const versionNumber = await clasp.project.version('Release v1.0'); console.log(`Created version ${versionNumber}`); ``` ``` -------------------------------- ### Push Files with Clasp Source: https://github.com/google/clasp/blob/master/docs/Gitpod/README.md Upload local files to the associated Google Apps Script project. ```bash clasp push ``` -------------------------------- ### Manage Google APIs with Clasp Source: https://github.com/google/clasp/blob/master/README.md Lists available Google APIs for enabling as Advanced Services, and enables or disables them within your Google Cloud project. Use 'clasp apis list' to find API names. ```bash clasp list-apis ``` ```bash clasp enable-api drive ``` ```bash clasp disable-api drive ``` -------------------------------- ### Standard Login Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Perform a standard login with default scopes. This is the most common authentication method. ```bash clasp login ``` -------------------------------- ### FileCredentialStore Constructor Source: https://github.com/google/clasp/blob/master/_autodocs/auth-api.md Initializes the FileCredentialStore, specifying the path to the JSON file where credentials will be stored. ```typescript class FileCredentialStore implements CredentialStore { constructor(filePath: string) } ``` -------------------------------- ### CredentialStore.load Source: https://github.com/google/clasp/blob/master/_autodocs/auth-api.md Loads stored credentials for a given user key. ```APIDOC ## CredentialStore.load ### Description Loads credentials for the specified user. ### Method load ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **userKey** (string) - Yes - The key identifying the user whose credentials to load. ### Request Example ```json { "userKey": "user123" } ``` ### Response #### Success Response (200) - **credential** (StoredCredential | undefined) - The stored credentials object, or undefined if not found. #### Response Example ```json { "credential": { "type": "authorized_user", "client_id": "CLIENT_ID", "client_secret": "CLIENT_SECRET", "refresh_token": "REFRESH_TOKEN", "access_token": "ACCESS_TOKEN", "expiry_date": 1678886400 } } ``` ``` -------------------------------- ### Open Current Apps Script Project Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Opens the current Apps Script project in the script.google.com editor. ```bash clasp open-script ``` -------------------------------- ### `readManifest()` Source: https://github.com/google/clasp/blob/master/_autodocs/project-api.md Reads and parses the `appsscript.json` manifest file from the local filesystem, returning its content. ```APIDOC ## `readManifest()` ### Description Reads and parses the `appsscript.json` manifest file from the local filesystem. ### Method GET ### Endpoint /project/readManifest ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **Manifest** - Manifest object with project configuration. #### Response Example ```json { "oauthScopes": ["script.external_request"], "timeZone": "America/Los_Angeles" } ``` **Throws:** - ENOENT if appsscript.json doesn't exist - JSON parse errors if manifest is malformed - File system errors ``` -------------------------------- ### Show File Status for Push Source: https://github.com/google/clasp/blob/master/_autodocs/cli-and-mcp.md Lists files that are staged to be pushed to the remote project. Use --json to output the file list in JSON format. ```bash clasp show-file-status ``` -------------------------------- ### listDeployments() Source: https://github.com/google/clasp/blob/master/_autodocs/project-api.md Lists all deployments of the script project. Returns an array of deployment objects or undefined on error. ```APIDOC ## listDeployments() ### Description Lists all deployments of the script project. ### Method async ### Endpoint project.listDeployments() ### Parameters None ### Returns Array of deployment objects with deploymentId, description, and versionNumber, or undefined on error. ### Example ```javascript const deployments = await clasp.project.listDeployments(); if (deployments) { deployments.forEach(d => { console.log(`${d.deploymentId} - v${d.versionNumber}: ${d.description}`); }); } ``` ```