# Autonomous Google API Agent

> A highly resilient, autonomous LLM agent built for Google Apps Script. Features granular RBAC, hierarchical method blocking, secure network sandboxing, and intelligent middleware (auto-pagination & latency resolution) to execute complex Google API workflows safely via MCP schema discovery.

- **Type:** MCP server
- **Install:** `agentstack add mcp-tanaikech-autonomous-google-api-agent`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [tanaikech](https://agentstack.voostack.com/s/tanaikech)
- **Installs:** 0
- **Category:** [AI & ML](https://agentstack.voostack.com/c/ai-and-ml)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [tanaikech](https://github.com/tanaikech)
- **Source:** https://github.com/tanaikech/Autonomous-Google-API-Agent
- **Website:** https://medium.com/google-cloud/vibe-code-all-google-apis-the-zero-trust-autonomous-agent-for-google-apps-script-77d743bdd545

## Install

```sh
agentstack add mcp-tanaikech-autonomous-google-api-agent
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Vibe Code All Google APIs: The Zero-Trust Autonomous Agent for Google Apps Script (AGAA)

Welcome to the **Autonomous Google API Agent (AGAA)**, the ultimate autonomous workspace orchestrator designed specifically for the strict execution limits of the Google Apps Script (GAS) environment.

Operating within the strict constraints of Google Apps Script—specifically the absolute 6-minute execution limit and synchronous blocking networking—demands an architecture that discards the optimistic assumptions of traditional Node.js environments. **AGAA is a highly engineered survival architecture.** Inspired by Google's Agent Development Kit, AGAA eliminates the hallucination risks and catastrophic data-destruction vulnerabilities inherent in standard LLM function-calling. It introduces a **Zero-Trust Role-Based Access Control (RBAC) architecture**, granular method-level sandboxing, deterministic security auditing, and autonomous schema discovery via the Model Context Protocol (MCP).

By fusing **GASADK** with **GoogleApiApp**, we cross the threshold into true **Vibe Coding**. AGAA allows developers to transition from writing rigid, boilerplate API scripts to dictating cross-service automation entirely via natural language across **all Google APIs**—including Workspace, Analytics, and YouTube—without bloated client libraries.

---

## 🌟 Core Architecture & Innovations

At the core of AGAA is a sophisticated, phase-separated orchestration model that acts as an absolute firewall between the LLM Planner and your live Google data.

- **Autonomous Schema Discovery (MCP Integration):** AGAA is mathematically forbidden from guessing or hallucinating API payloads. It natively queries the Google Developer Knowledge API via MCP (`mcp_0`) to extract official documentation, exact endpoints, and required JSON body structures before executing any network request.
- **Universal API Agnosticism:** AGAA does not care if you are formatting a Docs paragraph, fetching Classroom rosters, parsing Analytics dimensions, or querying YouTube metadata. It utilizes a single dynamic tool wrapper (`call_google_api`) for all Google APIs, eliminating tool bloat entirely.
- **Fast-Fail Method Validation:** Rejects improperly formatted or incomplete method names (e.g., hallucinating `create` instead of `documents.create`) locally before initiating costly network requests, saving tokens and execution time.
- **Formula Latency Suspension:** Autonomously detects uncomputed `#N/A` or `Loading...` states in Spreadsheet cells and suspends the GAS thread to wait for server-side computations to resolve before retrying.
- **Autonomous Pagination Integration:** Detects `nextPageToken` in responses and recursively aggregates list data across multiple pages without requiring the LLM to manage while-loops or page states.
- **Execution Loop Limiters:** Tracks deterministic tool invocation signatures, mathematically halting runaway token burn if the LLM repeatedly attempts to hit a blocked URL or executes the same failed API method more than 3 times.

---

## ⚙️ AGAA Workflow Architecture

The step-by-step workflow of AGAA operates as a dynamic Directed Acyclic Graph (DAG), seamlessly weaving between planning, schema discovery, execution, and security evaluation.

```mermaid
flowchart TD
    Start([User Prompt Input])
    Planner[Task Planning & DAG Generation]
    FastTrack{Requires Tools?}
    DirectOut[Direct Response Bypass]
    TaskLoop[Sequential Task Execution]
    MCP[Pathway A: MCP Schema Lookup]
    HTTP[Pathway B: HTTP Web Retrieval]
    Workspace[Pathway C: Google API Call]
    SecurityCheck{Pass Local RBAC Check?}
    APIExec[Execute API via GoogleApiApp]
    Block[Raise Security Block]
    Synthesis[Final Synthesis & Summary]
    EndNode([Output to User])

    Start --> Planner
    Planner --> FastTrack
    FastTrack -- No --> DirectOut
    DirectOut --> EndNode
    FastTrack -- Yes --> TaskLoop
    TaskLoop --> MCP
    TaskLoop --> HTTP
    TaskLoop --> Workspace
    Workspace --> SecurityCheck
    SecurityCheck -- Denied --> Block
    SecurityCheck -- Allowed --> APIExec
    MCP --> TaskLoop
    HTTP --> TaskLoop
    APIExec --> TaskLoop
    Block --> Synthesis
    TaskLoop -- All Tasks Done --> Synthesis
    Synthesis --> EndNode

    classDef core fill:#0f172a,color:#f8fafc,stroke:#3b82f6,stroke-width:2px;
    classDef tool fill:#1e293b,color:#22d3ee,stroke:#06b6d4,stroke-width:2px;
    classDef check fill:#334155,color:#facc15,stroke:#eab308,stroke-width:2px;
    classDef output fill:#0f172a,color:#10b981,stroke:#059669,stroke-width:2px;
    classDef block fill:#450a0a,color:#f87171,stroke:#ef4444,stroke-width:2px;

    class Start,Planner,TaskLoop core;
    class MCP,HTTP,Workspace,APIExec tool;
    class FastTrack,SecurityCheck check;
    class DirectOut,Synthesis,EndNode output;
    class Block block;
```

### Step-by-Step Workflow Explanation

1.  **Task Planning:** The orchestrator digests the natural language prompt and decomposes it into a logical DAG, taking a Fast-Track route to eliminate execution latency if tools are unnecessary.
2.  **Pathway Evaluation:** The agent selects the correct capability for the current node, routing schema knowledge to MCP, external data to HTTP, and data mutation to the Google API tool.
3.  **Security Interception:** Before any Google API request touches the network, it is intercepted by the local RBAC engine for deterministic method and class validation.
4.  **Execution & Aggregation:** Validated requests are processed by GoogleApiApp, which handles REST endpoint construction, parameter encoding, and automatic pagination aggregation.
5.  **Synthesis:** The LLM receives the aggregated data arrays, parses them natively, and formulates a final, formatted response to the user.

---

## 🚀 Step-by-Step Quick Start Guide for Beginners

This section guide shows absolute beginners how to get AGAA up and running in a Google Apps Script project from scratch.

### Step 1: Install Required Libraries in GAS

AGAA depends on **GASADK** (which manages the cognitive orchestration engine) and **GoogleApiApp** (which dynamically resolves Google API endpoints).

1.  Open your [Google Apps Script Editor](https://script.google.com/).
2.  On the left sidebar, click the **"+"** button next to **Libraries**.
3.  **Install GASADK**:
    - Paste the Project Key: `1kYkLP1KNs2AGBBzw903WE-rt_cF5gS2RlKxu2kg4xn8q0sy6hoAQlBrd`
    - Click **Look up**, select the latest version, and choose the identifier `GASADK`.
    - Click **Add**.
4.  **Install GoogleApiApp**:
    - Paste the Project Key: `1YVWd5qzz0quKljrJkliE143UwwJq1BopoZQSwNEqwNgHOPQ9VeaQeNS7`
    - Click **Look up**, select the latest version, and choose the identifier `GoogleApiApp`.
    - Click **Add**.

### Step 2: Copy `AutonomousGoogleApiAgent.js` into your Project

1.  In your GAS project, click **"+"** next to **Files** and select **Script**.
2.  Name the file `AutonomousGoogleApiAgent`.
3.  Copy the entire source code of [AutonomousGoogleApiAgent.js](src/AutonomousGoogleApiAgent.js) from this repository and paste it into the editor.

### Step 3: Setup Script Properties (Your Secrets API Keys)

AGAA requires two API Keys: one for Gemini, and one for the Developer Knowledge API (MCP).

1.  In your GAS project, navigate to **Project Settings** (the gear icon on the left sidebar).
2.  Scroll down to the **Script Properties** section.
3.  Click **Add script property** and add the following two key-value pairs:
    - **Property Name:** `GEMINI_API_KEY` | **Value:** _Your Gemini API Key_ ([Get one here](https://ai.google.dev/gemini-api/docs/api-key))
    - **Property Name:** `DEVELOPER_MCP_KEY` | **Value:** _Your Google Developer Knowledge API Key_ ([Get one here](https://developers.google.com/knowledge/api))
4.  Click **Save script properties**.

### Step 4: Enable Advanced Google Services (APIs)

You must enable any Google service you plan to have the agent orchestrate.

1.  On the left sidebar of the script editor, click **"+"** next to **Services**.
2.  Select the API you wish to enable (e.g., **Google Sheets API**, **Google Drive API**, **Google Docs API**).
3.  Click **Add**.

### Step 5: Execute Your First Wrapper Script

Create a new script file (e.g. `main.js`) and paste the following simple test code to run your first prompt:

```javascript
function runMyFirstAgent() {
  const prompt =
    'Create a new Google Spreadsheet and write "Hello World from AGAA!" in cell A1 of the first sheet.';

  // Beginners: Highly restrictive zero-trust settings. Read and write are allowed for sheets, everything else is blocked.
  const securityConfig = {
    sheets: { read: true, write: true, delete: false },
  };

  const properties = PropertiesService.getScriptProperties();
  const geminiApiKey = properties.getProperty("GEMINI_API_KEY");
  const developerMcpKey = properties.getProperty("DEVELOPER_MCP_KEY");

  const agent = new AutonomousGoogleApiAgent({
    geminiApiKey,
    developerMcpKey,
    securityConfig,
  });

  console.log("Starting agent...");
  const response = agent.run(prompt, (logEntry) =>
    console.log(logEntry.message),
  );

  console.log("=== Response ===");
  console.log(response);
}
```

---

## 🛡️ Zero-Trust Security Configuration (Deep Dive)

Security cannot be an LLM prompt instruction; it must be a deterministic reality. Granting an LLM unfettered access to your workspace via OAuth scopes is dangerous. AGAA shifts the security burden away from the AI and into hardcoded JavaScript middleware.

### 1. Coarse RBAC (Role-Based Access Control)

The `securityConfig` object enforces strict boundaries regardless of the underlying OAuth token's capabilities. **Any Google API service not explicitly defined in your configuration object is mathematically blocked by default (Implicit Deny).**

```javascript
const securityConfig = {
  sheets: { read: true, write: true, delete: false },
  drive: { read: true, write: false, delete: false },
};
```

- `read`: (Boolean) Allows/disallows read methods (GET operations).
- `write`: (Boolean) Allows/disallows creation and mutation methods (POST, PUT, PATCH, copy, batch).
- `delete`: (Boolean) Allows/disallows destructive methods (DELETE, trash, empty, clear, purge).

### 2. Action Class Inference

AGAA automatically parses the requested REST method string (e.g., `files.delete`) and uses regex to classify it dynamically as `READ`, `WRITE`, or `DELETE`:

- **`DELETE`**: Triggered by method names containing `delete`, `trash`, `empty`, `remove`, `purge`, or `clear`.
- **`WRITE`**: Triggered by method names containing `create`, `update`, `patch`, `insert`, `send`, `write`, `post`, `put`, `copy`, or `batch`.
- **`READ`**: All other method names are classified as read-only.

### 3. Hierarchical Method Masking (`allowMethods` / `denyMethods`)

For highly precise control, you can white- or blacklist specific namespaces using dot-notation hierarchical matching. **Deny rules always override allow rules.**

```javascript
const securityConfig = {
  sheets: {
    read: true,
    write: true,
    delete: false,
    allowMethods: ["spreadsheets.values"], // Restricts only to value manipulation
    denyMethods: ["spreadsheets.values.clear"], // Blocks specific cell clearing
  },
};
```

- Allowing `spreadsheets.values` automatically permits `spreadsheets.values.get` and `spreadsheets.values.update`, but definitively blocks `spreadsheets.create`.

### 4. Network Egress Sandboxing (`httpGet`)

External web scraping via the `fetch_http_get` tool is sandboxed through `allowDomains` and `denyDomains`, evaluated using strict hierarchical string matching to prevent data exfiltration.

```javascript
const securityConfig = {
  httpGet: {
    allowDomains: ["api.github.com"], // External fetch is limited only to GitHub
    denyDomains: ["evil.com"], // Block explicitly restricted domains
  },
};
```

### 5. Intervention Protocol

If an action violates the RBAC policy, the tool locally returns a `[SECURITY BLOCKED]` payload to the agent. AGAA’s system instructions mathematically forbid the LLM from attempting to bypass the firewall (no ReAct hallucinations), forcing a graceful explanation of the permissions failure.

---

## 📖 API Reference

### Constructor Config Parameters (`new AutonomousGoogleApiAgent(config)`)

| Parameter         | Type   | Required |              Default              | Description                                                                     |
| :---------------- | :----- | :------: | :-------------------------------: | :------------------------------------------------------------------------------ |
| `geminiApiKey`    | String | **Yes**  |            `undefined`            | Your Gemini API authorization key.                                              |
| `developerMcpKey` | String | **Yes**  |            `undefined`            | Your Google Developer Knowledge MCP API key.                                    |
| `accessToken`     | String |    No    |               `""`                | Optional. OAuth2 access token to manually override GoogleApiApp authentication. |
| `model`           | String |    No    | `"models/gemini-3-flash-preview"` | The target Gemini model to power the orchestrator.                              |
| `timeoutMs`       | Number |    No    |             `280000`              | Milliseconds before safe abort to avoid GAS 6-minute execution limits.          |
| `securityConfig`  | Object |    No    |               `{}`                | The zero-trust security rule map (Coarse & Granular controls).                  |

### Public Methods

#### `setAccessToken(accessToken)`

Overrides the default script authentication with a custom Google OAuth2 access token.

- **Arguments:** `accessToken` (String) - The raw access token.
- **Returns:** `this` (Allows method chaining).

#### `run(prompt, logCallback)`

Executes the autonomous agent to solve the user's intent.

- **Arguments:**
  - `prompt` (String) - The natural language command.
  - `logCallback` (Function) - Optional callback for telemetry logs. Receives a log object: `{ timestamp, message, data }`.
- **Returns:** `String` - The final synthesized natural language response (or strictly structured JSON matching request).

#### `getHistory()`

Retrieves the complete conversation history.

- **Returns:** `Array` - Array of multi-turn conversation messages.

#### `getLogs()`

Retrieves execution telemetry logs collected during the execution run.

- **Returns:** `Array` - Array of logging entries.

#### `getSecurityLogs()`

Retrieves a detailed history of all blocked requests intercepted by the zero-trust middleware.

- **Returns:** `Array` - Audit trail logs of blocked API calls or domain fetches.

---

## 💻 Guided Real-World Usage Scenarios (Tests)

### Test 1: Spreadsheet Formula Orchestration and Latency Handling

This scenario tests the agent's ability to create a spreadsheet, insert a formula, and read the computed value, managing Sheets computation latency.

- **Required Scopes:** `script.external_request`, `drive`, `spreadsheets`
- **Required Advanced Services:** Google Drive API, Google Sheets API

```javascript
function testSpreadsheetLatency() {
  const prompt =
    'Create a new Google Spreadsheet by putting a formula `=GOOGLEFINANCE("CURRENCY:USDJPY")` in cell "A1" of the first sheet. Then, get and show the value of cell "A1".';

  const securityConfig = {
    sheets: { read: true, write: true, delete: false },
  };

  main_AutonomousGoogleApiAgent_(prompt, securityConfig);
}
```

- **Under the Hood:** Sheets takes time to fetch finance data. The initial cell read returns `#N/A`. The AGAA middleware detects this, suspends execution for 3000ms, and retries the read operation dynamically, ensuring the agent gets the actual exchange rate.

---

### Test 2: Cross-Domain Web Scraping and Document Batch Processing

This script fetches a live website profile, summarizes it within the context, and uses the Google Docs batchUpdate A

…

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [tanaikech](https://github.com/tanaikech)
- **Source:** [tanaikech/Autonomous-Google-API-Agent](https://github.com/tanaikech/Autonomous-Google-API-Agent)
- **License:** MIT
- **Homepage:** https://medium.com/google-cloud/vibe-code-all-google-apis-the-zero-trust-autonomous-agent-for-google-apps-script-77d743bdd545

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-tanaikech-autonomous-google-api-agent
- Seller: https://agentstack.voostack.com/s/tanaikech
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
