AstraPay logo
AI & Data Platform Integration•

Enterprise SaaS-to-MCP Gateway: Securing Agentic AI Workflows to Google BigQuery

Architectural design and implementation of a stateless enterprise Model Context Protocol (MCP) gateway connecting external SaaS AI agents (Atlassian Rovo) to Google BigQuery with strict security guardrails, RFC 7591 Dynamic Client Registration, OAuth 2.1 PKCE, and automated cost protection.

Model Context Protocol (MCP)Google BigQueryTypeScriptOAuth 2.1Dynamic Client RegistrationCloud RunSecurity Guardrails

Protocol

MCP (SSE/HTTP) + RFC 7591

Security

OAuth 2.1 PKCE + JWE Stateless

Guardrails

Max Bytes Billed & AST Filter

Executive Summary

In the emerging era of Agentic AI, bridging enterprise AI platforms (such as Atlassian Rovo) directly with internal analytical data warehouses (Google BigQuery) unlocks substantial business productivity gains. Non-technical business stakeholders can pose complex analytical questions in natural language and receive verified, aggregated metrics in seconds.

However, exposing enterprise data warehouse engines directly to autonomous LLM agents introduces critical operational risks:

  1. Runaway Compute Costs: LLMs are prone to generating queries without partition filters or clustering constraints. On BigQuery’s on-demand model ($6.25 per TB scanned), a single unconstrained scan can trigger hundreds of dollars in unplanned cloud billing.
  2. Security Vulnerabilities & Destructive Queries: Potential SQL injection or prompt injection attacks attempting DDL/DML modifications (DROP, UPDATE, ALTER) or unauthorized access beyond the agent’s specific domain.
  3. Identity & Protocol Standards: The need for standardized, federated authentication without exposing static Google Cloud Service Account keys to third-party SaaS vendors.

To solve this challenge, I designed and developed the Enterprise SaaS-to-MCP Gateway—a custom server built on Anthropic’s Model Context Protocol (MCP) specification that functions as a standalone Policy Enforcement Point (PEP) deployed on Google Cloud Run. Even though the initiative concluded as an internal Proof of Concept (PoC) / R&D Solution, the project proved that autonomous AI agents can be seamlessly integrated with enterprise data systems under zero-compromise governance.


System Architecture & Interaction Flow

The gateway sits at the network boundary between the Atlassian Cloud ecosystem and Google Cloud Platform (GCP). All communication is authenticated using OAuth 2.1 with PKCE, while BigQuery data retrieval is governed by a strict two-phase interaction cycle: Dry-Run Cost Estimation and Capped Readonly Execution.

graph TD
    subgraph Atlassian_Cloud [Atlassian Cloud]
        Rovo[SERSAN Agent in Rovo]
    end

    subgraph Internet_Layer [Protected Ingress]
        OAuth[HTTPS / OAuth 2.1 PKCE Flow]
    end

    subgraph GCP_Cloud_Run [Google Cloud Run Gateway]
        MCPServer[Stateless MCP Gateway Engine<br/>TypeScript / Express]
        PolicyEngine[SQL Policy & AST Validator]
        AuthEngine[Stateless DCR & JWE Decryptor]
        AuditLogger[Structured Audit Logger]
    end

    subgraph GCP_Data_Platform [Google Cloud Platform]
        BigQuery[Google BigQuery Engine]
        CloudLogging[Cloud Logging / Audit Sink]
        Datasets[(Allowlisted Datasets)]
    end

    Rovo -->|1. Tool Call Request| OAuth
    OAuth -->|2. Ingress HTTP/SSE| MCPServer
    MCPServer -->|3. Validate Token & Policy| PolicyEngine
    PolicyEngine -->|4. Dry Run Estimate| BigQuery
    PolicyEngine -->|5. Enforce Max Bytes Billed| BigQuery
    BigQuery -->|6. Query Restricted Data| Datasets
    MCPServer -->|7. Stream Audit Trail| CloudLogging
    MCPServer -->|8. Return Aggregated Insights| Rovo

Two-Phase Interaction: Cost Estimation & Execution Cycle

To prevent accidental cost spikes, the gateway enforces a two-step validation model. The agent is strictly instructed to evaluate scan volume before submitting a query for actual execution:

sequenceDiagram
    autonumber
    actor User as Business User
    participant Rovo as SERSAN Agent (Rovo)
    participant MCP as MCP Gateway (Cloud Run)
    participant BQ as BigQuery

    User->>Rovo: Asks: "What was the total QRIS transaction volume last week?"
    Note over Rovo: Agent inspects table schema <br/>& drafts a parameterized SELECT query
    Rovo->>MCP: Call Tool: estimate_query_cost(sql)
    Note over MCP: Policy Validation:<br/>- Strip SQL Comments (Anti-Bypass)<br/>- Check Table Allowlist<br/>- Deny DDL/DML Keywords
    MCP->>BQ: Dry Run Query (dryRun=true, $0 cost)
    BQ-->>MCP: Return Bytes Scanned & Cost Estimate ($)
    Note over MCP: Validate scan against budget cap
    MCP-->>Rovo: Return Estimate: 250 MB (~$0.0015 USD) - Status: APPROVED
    
    rect rgb(240, 248, 255)
        Note over Rovo: If approved, agent proceeds to execution
        Rovo->>MCP: Call Tool: execute_readonly_query(sql)
        MCP->>BQ: Execute Query (Enforce maximumBytesBilled=10GB)
        BQ-->>MCP: Return Aggregated Result Rows
        Note over MCP: Enforce max 1,000 row cap<br/>Write Structured Audit Log (User, SQL, Latency)
        MCP-->>Rovo: Return Clean JSON Data
    end
    
    Rovo->>User: Formulate executive summary with transparent query cost

Core Engineering Pillars & Features

1. Dynamic Client Registration (RFC 7591) & Stateless OAuth 2.1

Enterprise SaaS integrations like Atlassian Rovo require clients to register dynamically when an administrator configures the tool. The gateway implements:

  • RFC 7591 Dynamic Client Registration (DCR): Programmatically handles registration requests, allocating client metadata and redirect URIs at runtime.
  • Stateless Architecture via JWE: Encrypts dynamic client registration state directly into signed JWE (JSON Web Encryption) tokens. This avoids the requirement for an external database to store transient client secrets, eliminating a single point of failure and enabling effortless zero-state serverless scaling.
  • Optional Firestore Persistence: Provides a pluggable stateful repository backed by Google Cloud Firestore for teams that require centralized persistence and revocation capabilities.

2. Multi-Layered Policy Engine & AST SQL Sanitization

Queries generated by LLMs pass through a rigorous sanitization pipeline before reaching downstream execution:

  • SQL Comment Stripping: Strips single-line (--) and block (/* */) comments to eliminate evasion vectors and prompt-injection payloads that attempt to disguise malicious clauses.
  • Read-Only Enactment: Enforces that queries must start strictly with SELECT or Common Table Expressions (WITH ... SELECT), while aggressively rejecting all DDL, DML, and procedural keywords (INSERT, UPDATE, DELETE, MERGE, DROP, ALTER, TRUNCATE, DECLARE, EXECUTE IMMEDIATE).
  • Table Allowlist Verification: Inspects extracted table references against ALLOWLIST_TABLES. Any attempt to access unauthorized production datasets is immediately blocked at the gateway layer without touching the database.
// Query Safety Validator Implementation in BigQuery Driver
export const validateQuerySafety = (sql: string): { safe: boolean; reason?: string; detectedTables: string[] } => {
  const cleanSql = sql.trim().toLowerCase();
  
  // 1. Strip comments to eliminate tokenization evasion
  const sqlWithoutComments = cleanSql.replace(/\/\*(?:\*[^\/]|[^*])*\*\/|--.*/g, '').trim();
  const sqlCleaned = sqlWithoutComments.replace(/`/g, '');
  
  // 2. Must start with SELECT or CTE (WITH ... SELECT)
  if (!sqlWithoutComments.startsWith('select') && !sqlWithoutComments.startsWith('with')) {
    return { safe: false, reason: 'Only SELECT or CTE (WITH ... SELECT) statements are permitted.', detectedTables: [] };
  }

  // 3. Reject modification and procedural keywords
  const forbiddenKeywords = [
    'insert', 'update', 'delete', 'merge', 'create', 'drop', 'alter',
    'truncate', 'grant', 'revoke', 'declare', 'execute immediate', 'call'
  ];
  for (const word of forbiddenKeywords) {
    if (new RegExp(String.raw`\b${word}\b`, 'i').test(sqlWithoutComments)) {
      return { safe: false, reason: `Query contains forbidden keyword: "${word}"`, detectedTables: [] };
    }
  }

  // 4. Verify touched tables against explicit allowlist
  const detectedTables = extractTables(sqlCleaned);
  for (const table of detectedTables) {
    if (!isTableAllowlisted(table)) {
      return { safe: false, reason: `Table "${table}" is not in the approved allowlist.`, detectedTables };
    }
  }

  return { safe: true, detectedTables };
};

3. Hard-Cap Cost Protection via BigQuery Job API

In addition to the dry-run estimation phase, the gateway sets hard limits directly in the BigQuery client request parameters:

  • The parameter maximumBytesBilled: 10737418240 (10 GB) is attached to every query job.
  • If a query unexpectedly attempts to scan beyond this threshold, BigQuery terminates execution instantly without billing the organization.
  • Strict response row capping (maximum 1,000 rows) ensures memory footprint safety and keeps roundtrip latency well under 3 seconds.

4. Partition & Clustering Awareness for LLM Prompting

Autonomous agents frequently construct slow full-table scans because standard database introspections do not report partitioning semantics. The describe_table and search_allowed_tables tools explicitly return partition fields, partition time granularities, and clustering columns. Supplying this context empowers the AI agent to write date-bounded queries automatically.


Operational Cost Modeling

Deploying the gateway on serverless Google Cloud Run provides high elasticity and near-zero idle overhead:

Stage Monthly Usage Profile Projected Monthly Cost Key Considerations
PoC / Exploration 3–5 users, ~1,000 queries ~$1 / month Cloud Run CPU/RAM and 200 GB BigQuery scans fit comfortably inside free tier limits.
Limited Pilot 10–20 users, ~5,000 queries ~$3 – $8 / month Partition-pruned queries; billing primarily covers logging and minor incremental scans.
Full Production 50–100 users, ~15,000 queries ~$15 – $25 / month Scale-to-zero configuration completely avoids persistent instance overhead.

Key Takeaways & Strategic Impact

  1. Enterprise AI Feasibility: Demonstrated that integrating external generative AI platforms with sensitive corporate data warehouses is fully achievable when reinforced with strict policy enforcement layers.
  2. Protocol Modernization: Mastered emerging standards shaping the future of autonomous software: Model Context Protocol (MCP), Dynamic Client Registration (RFC 7591), and OAuth 2.1 PKCE.
  3. Extensible Open-Source Pattern: Engineered with a modular driver architecture (DriverManager, PolicyEngine, and inbound adapters), creating a portable blueprint that can readily support other enterprise platforms (e.g., Claude Enterprise, Slack AI, or Microsoft Copilot).