init.sh
Overview
The init.sh script is a foundational initialization utility designed to prepare a Google Cloud environment for deploying the MCP server to Google Cloud Run. It automates critical setup tasks such as configuring the Google Cloud project, enabling essential APIs, assigning IAM roles, managing authentication contexts, and exporting environment variables required for subsequent deployment and runtime operations.
This script ensures a consistent, reproducible, and authenticated environment, acting as a prerequisite for the deployment automation workflow detailed under Cloud Run Deployment Automation and the environment setup described in Environment Initialization.
Detailed Explanation
Error Handling Function
handle_error() {
echo "Error: $1"
exit 1
}
Purpose: Prints an error message passed as an argument and exits the script immediately with a non-zero status.
Parameters:
$1: The error message string to display.
Usage: Called whenever a critical error occurs (e.g., missing input or failure to write a file) to halt further execution.
Main Functional Segments
1. Change Directory to Project Root
cd ~/mcp-on-cloudrun
Navigates to the local directory assumed to contain the MCP server deployment files and related scripts.
Ensures subsequent operations like sourcing
set_env.shand reading/writing project files happen in the correct context.
2. Google Cloud Project ID Setup
PROJECT_FILE="$HOME/project_id.txt"
echo "--- Setting Google Cloud Project ID File ---"
read -p "Please enter your Google Cloud project ID: " user_project_id
if [[ -z "$user_project_id" ]]; then
handle_error "No project ID was entered."
fi
echo "You entered: $user_project_id"
echo "$user_project_id" > "$PROJECT_FILE"
if [[ $? -ne 0 ]]; then
handle_error "Failed saving your project ID: $user_project_id."
fi
Purpose: Prompts the user to input their Google Cloud project ID, validates input, and saves it to a persistent file (
~/project_id.txt).Details:
Uses a
readprompt to capture input.Checks if input is empty and triggers error handling if so.
Writes the project ID to a file for consistent reuse.
Verifies file write success, errors if failed.
Usage Example:
Please enter your Google Cloud project ID: my-gcp-project-123 You entered: my-gcp-project-123
3. Source Environment Configuration Script
source ./set_env.sh
Loads environment variables and additional configuration from
set_env.sh.This step is critical to export variables like project ID, region, and authentication tokens as described in Environment Initialization.
Variables set here are used for the rest of the initialization process.
4. Set Active Google Cloud Project with gcloud
gcloud config set project $(cat ~/project_id.txt)
echo "Successfully saved project ID."
Configures the active project in the
gcloudCLI environment to the project ID stored in the file.Ensures all subsequent
gcloudcommands operate within the correct project context.
5. Enable Required Google Cloud Services
echo "Enabling Services"
gcloud services enable \
run.googleapis.com \
artifactregistry.googleapis.com \
cloudbuild.googleapis.com
Enables the following Google Cloud APIs necessary for deployment and operation of the MCP server:
Cloud Run API (
run.googleapis.com): Manages serverless container hosting.Artifact Registry (
artifactregistry.googleapis.com): Stores container images.Cloud Build (
cloudbuild.googleapis.com): Builds container images from source.
Automates the prerequisite API activation step to prevent deployment failures.
6. Add IAM Roles for Cloud Run Invocation
echo "Adding IAM Roles"
export GOOGLE_CLOUD_PROJECT=$(gcloud config get project)
if [[ -z "$CLOUD_SHELL" ]] && curl -s -i metadata.google.internal | grep -q "Metadata-Flavor: Google"; then
echo "This VM is running on GCP Defaults to Service Account."
else
gcloud projects add-iam-policy-binding $GOOGLE_CLOUD_PROJECT \
--member=user:$(gcloud config get-value account) \
--role='roles/run.invoker' \
--quiet \
--condition=None
fi
Purpose: Grants the current user permission to invoke Cloud Run services on the project by binding the
roles/run.invokerrole.Details:
Detects if script runs on a Google Cloud VM using metadata server query.
If on a GCP VM (and not Cloud Shell), assumes default service account usage; no explicit IAM binding is performed.
Otherwise, explicitly adds the IAM policy binding for the user account returned by
gcloud config get-value account.
Implementation Notes:
Uses
--quietto suppress prompts.Ensures the user can access Cloud Run services post-deployment.
7. Authentication Context Handling
if [ "$CLOUD_SHELL" = "true" ]; then
echo "Running in Google Cloud Shell."
else
if curl -s -i metadata.google.internal | grep -q "Metadata-Flavor: Google"; then
echo "This VM is running on Google Cloud."
else
echo "Not running in Google Cloud VM or Shell."
echo "Setting ADC Credentials"
gcloud auth application-default login
fi
fi
Detects the environment to determine appropriate authentication flow:
Google Cloud Shell: No additional auth needed.
Google Cloud VM: Uses default service account.
Local Machine or Other Environment: Initiates Application Default Credentials (ADC) login flow via
gcloud auth application-default login.
Ensures that the script has valid credentials to perform Google Cloud operations.
8. Environment-Specific Checks and Messages
if [ -n "$FIREBASE_DEPLOY_AGENT" ]; then
echo "Running in Firebase Studio terminal"
else
echo "Not running in Firebase Studio terminal"
fi
if [ -d "/mnt/chromeos" ] ; then
echo "Running on ChromeOS"
else
echo "Not running on ChromeOS"
fi
Prints diagnostic messages depending on environment variables or filesystem paths.
May assist users or operators in understanding the script’s runtime context, which could affect authentication or deployment behavior.
9. Export Identity Token
export ID_TOKEN=$(gcloud auth print-identity-token)
Generates and exports an OpenID Connect (OIDC) identity token for the active user or service account.
This token can authenticate requests against Cloud Run services in secure deployment modes.
The token is exported as an environment variable
ID_TOKENfor use by deployment or runtime scripts.
Interaction with Other Parts of the System
set_env.sh: This script must be present in the current working directory and is sourced to set environment variables likePROJECT_ID,REGION, and flags.init.shdepends on it to configure the environment properly.Deployment Scripts (
cloudrun.sh,cloudrun-secure.sh): These rely on the environment variables and IAM roles set up byinit.shto deploy the MCP server either publicly or securely, as described in Cloud Run Deployment Automation.Google Cloud CLI (
gcloud):init.shusesgcloudcommands extensively for project configuration, service enabling, IAM role assignment, and authentication token management, integrating tightly with Google Cloud infrastructure.Authentication Contexts: The script adapts behavior if run within Google Cloud Shell, Google Cloud VM, or local environments, ensuring the appropriate credentials are used or requested.
Important Implementation Details
Error Handling: The script employs a dedicated
handle_errorfunction to catch and report failures in critical steps (such as empty project ID input or failure to write the project ID file), then exits immediately to prevent further errors.Environment Detection: Uses HTTP requests to the GCP metadata server (
metadata.google.internal) to detect if running inside GCP infrastructure, influencing authentication and IAM role management logic.Idempotency: Running this script multiple times does not cause adverse side effects. It overwrites the project ID file, re-enables APIs (which is safe), and re-applies IAM roles quietly.
User Interaction: Requires interactive input for the Google Cloud project ID, ensuring the user explicitly sets the correct project context.
Usage Example
$ ./init.sh
--- Setting Google Cloud Project ID File ---
Please enter your Google Cloud project ID: my-gcp-project-123
You entered: my-gcp-project-123
Successfully saved project ID.
Enabling Services
...
Adding IAM Roles
This VM is running on GCP Defaults to Service Account.
Running in Google Cloud Shell.
Not running in Firebase Studio terminal
Not running on ChromeOS
--- Initial Setup complete ---
Visual Diagram: Workflow of init.sh
flowchart TD
A[Start] --> B[Prompt for Project ID]
B --> C{Project ID entered?}
C -- No --> D[Error: No project ID, exit]
C -- Yes --> E[Save Project ID to file]
E --> F[Source set_env.sh]
F --> G[Set gcloud active project]
G --> H[Enable required Cloud APIs]
H --> I[Check environment]
I --> J{Running on GCP VM & not Cloud Shell?}
J -- Yes --> K[Use default service account]
J -- No --> L[Add IAM role for user]
K & L --> M{Running in Cloud Shell?}
M -- Yes --> N[Skip ADC login]
M -- No --> O{Running on GCP VM?}
O -- Yes --> N
O -- No --> P[Run gcloud auth application-default login]
N & P --> Q[Check Firebase Studio terminal]
Q --> R[Check ChromeOS environment]
R --> S[Export ID_TOKEN]
S --> T[Initialization complete]
Summary of Key Variables and Environment Effects
Variable | Description |
|---|---|
| File path to save the project ID ( |
| User-entered Google Cloud project ID |
| Active Google Cloud project configured in |
| OIDC identity token exported for authentication |
| Environment variable indicating if running in Cloud Shell |
| Indicates if running in Firebase Studio terminal |
Reference to Related Topics
The setup steps and environment variables configured by this script align with the processes described in Environment Initialization.
The IAM role assignment and API enabling facilitate deployments covered in Cloud Run Deployment Automation.
This script is foundational to secure or unauthenticated deployment flows, linking directly to Secure Deployment and Unauthenticated Deployment.
This documentation provides a comprehensive understanding of the init.sh script's role, structure, and integration within the MCP server deployment process.