### Quick Start Development Commands with Make Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/README.md Essential `make` commands for quickly setting up and building the `mcp-gemini-grounding` project. This includes commands for installing dependencies, compiling the project, running basic tests, and performing a full audit of the codebase for quality checks. ```bash # Install dependencies make deps # Build the project make build # Run tests make test # Run all quality checks make audit ``` -------------------------------- ### Implement Hello World Tool with mark3labs/mcp-go Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/go_mcp_server_research.md A complete example demonstrating server setup, tool definition ('hello_world' with a required 'name' parameter), and a handler function using the 'mark3labs/mcp-go' library. It shows how to serve the MCP server via standard I/O, handling tool calls and returning results. ```go package main import ( "context" "fmt" "github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server" ) func main() { s := server.NewMCPServer( "Demo Server", "1.0.0", server.WithToolCapabilities(false), ) tool := mcp.NewTool("hello_world", mcp.WithDescription("Say hello to someone"), mcp.WithString("name", mcp.Required(), mcp.Description("Name of the person to greet"), ), ) s.AddTool(tool, helloHandler) if err := server.ServeStdio(s); err != nil { fmt.Printf("Server error: %v\n", err) } } func helloHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) { name, err := request.RequireString("name") if err != nil { return mcp.NewToolResultError(err.Error()), nil } return mcp.NewToolResultText(fmt.Sprintf("Hello, %s!", name)), nil } ``` -------------------------------- ### Install Gemini Grounding MCP Server Globally Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/README.md This snippet shows two methods to install the Gemini Grounding MCP server globally: using `make install` from source or directly via `go install` to make the executable available system-wide. ```bash make install ``` ```bash go install github.com/ml0-1337/mcp-gemini-grounding/cmd/gemini-grounding@latest ``` -------------------------------- ### Run MCP Server with OAuth2 Authentication Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/OAUTH2_SETUP.md This command starts the MCP server. When `GEMINI_API_KEY` is unset, the server automatically detects and utilizes the previously configured OAuth2 credentials for authentication with the Gemini Code Assist API. ```go go run ./cmd/gemini-grounding ``` -------------------------------- ### Install mark3labs/mcp-go Community Library Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/go_mcp_server_research.md Command to install the recommended 'mark3labs/mcp-go' community library using Go Modules. This library is considered the most mature and widely used community implementation for MCP servers in Go. ```bash go get github.com/mark3labs/mcp-go ``` -------------------------------- ### Implement Search Tool with metoro-io/mcp-golang Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/go_mcp_server_research.md Example showcasing type-safe tool arguments using a Go struct (`SearchArgs`) and automatic schema generation from struct tags. It registers a 'google_search' tool with 'query' and optional 'limit' parameters, demonstrating how to handle tool calls and return text content using the 'metoro-io/mcp-golang' library. ```go package main import ( "fmt" mcp_golang "github.com/metoro-io/mcp-golang" "github.com/metoro-io/mcp-golang/transport/stdio" ) type SearchArgs struct { Query string `json:"query" jsonschema:"required,description=The search query"` Limit int `json:"limit,omitempty" jsonschema:"description=Maximum results to return"` } func main() { server := mcp_golang.NewServer(stdio.NewStdioServerTransport()) err := server.RegisterTool("google_search", "Search the web", func(args SearchArgs) (*mcp_golang.ToolResponse, error) { // Implement search logic here result := fmt.Sprintf("Searching for: %s", args.Query) return mcp_golang.NewToolResponse( mcp_golang.NewTextContent(result), ), nil }) if err != nil { panic(err) } err = server.Serve() if err != nil { panic(err) } } ``` -------------------------------- ### Expected Server Output for OAuth2 Authentication Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/OAUTH2_SETUP.md This output confirms that the MCP server has successfully enabled OAuth2 authentication, initialized the Code Assist onboarding process, and obtained a project ID. ```text OAuth2 authentication enabled using custom HTTP client OAuth2: Starting Code Assist onboarding... OAuth2: Code Assist onboarding successful, project ID: ``` -------------------------------- ### Configure Claude Code MCP Server for Project Scope via CLI Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/README.md This snippet provides CLI commands to configure the Gemini Grounding MCP server for a project-specific scope in Claude Code, ideal for team collaboration. It includes examples for both globally installed and absolute path binaries. ```bash claude mcp add gemini-grounding -s project ``` ```bash claude mcp add gemini-grounding -s project /full/path/to/mcp-gemini ``` -------------------------------- ### Authenticate Gemini CLI for OAuth2 Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/OAUTH2_SETUP.md This command initiates the OAuth2 authentication flow using the Gemini CLI. It opens a browser for Google authentication, requests Cloud Platform permissions, and saves credentials locally. ```bash gemini -p "test" ``` -------------------------------- ### Implementing Gemini API Grounding Request in Go Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/go_mcp_server_research.md Provides a Go example for constructing a request payload to utilize the Gemini API's grounding feature. It defines the necessary `GroundingRequest` and `Tool` structs, specifically demonstrating how to integrate Google Search as a tool for grounding. ```go // Using Gemini API for grounding type GroundingRequest struct { Contents []Content `json:"contents"` Tools []Tool `json:"tools"` } type Tool struct { GoogleSearch *GoogleSearch `json:"googleSearch,omitempty"` } // Make request with grounding request := GroundingRequest{ Contents: []Content{{ Role: "user", Parts: []Part{{Text: query}}, }}, Tools: []Tool{{ GoogleSearch: &GoogleSearch{}, }}, } ``` -------------------------------- ### Configure Claude Code MCP Server for User Scope via CLI Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/README.md This snippet provides CLI commands to configure the Gemini Grounding MCP server for a user-specific (global) scope in Claude Code, making it available across all projects. It includes examples for both globally installed and absolute path binaries. ```bash claude mcp add gemini-grounding -s user ``` ```bash claude mcp add gemini-grounding -s user /full/path/to/mcp-gemini ``` -------------------------------- ### Required OAuth2 Scopes for Gemini CLI Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/OAUTH2_SETUP.md These are the Google API scopes automatically requested by the Gemini CLI during the OAuth2 authentication process. They grant necessary permissions for Cloud Platform access and user information retrieval. ```APIDOC - https://www.googleapis.com/auth/cloud-platform - https://www.googleapis.com/auth/userinfo.email - https://www.googleapis.com/auth/userinfo.profile ``` -------------------------------- ### Unset GEMINI_API_KEY for OAuth2 Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/OAUTH2_SETUP.md This command ensures that the `GEMINI_API_KEY` environment variable is not set, allowing the MCP server to default to OAuth2 authentication instead of API key authentication. ```bash unset GEMINI_API_KEY ``` -------------------------------- ### Configure Claude Code MCP Server for Local Scope via CLI Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/README.md This snippet demonstrates how to add the Gemini Grounding MCP server to Claude Code's local scope using the CLI, suitable for personal development. It shows commands for both globally installed and absolute path scenarios, emphasizing the requirement for absolute paths. ```bash claude mcp add gemini-grounding ``` ```bash claude mcp add gemini-grounding /full/path/to/mcp-gemini-grounding ``` -------------------------------- ### Google Search Tool API Definition for Claude Code Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/README.md Defines the JSON schema for the `google_search` tool, detailing its name, description, and input parameters. This tool integrates Google Search via Gemini AI grounding to provide synthesized answers with citations, returning AI-generated summaries rather than raw search results. An example of the tool's output format is also provided in the source documentation. ```json { "name": "google_search", "description": "Uses Google Search via Gemini AI grounding to find information and provide synthesized answers with citations. Returns AI-generated summaries rather than raw search results.", "inputSchema": { "type": "object", "properties": { "query": { "type": "string", "description": "The search query to find information on the web" } }, "required": ["query"] } } ``` -------------------------------- ### Gemini CLI OAuth Client Configuration Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-implementation-report.md Defines the OAuth 2.0 client ID and secret used by the Gemini CLI for authentication with Google. The secret is intentionally stored in the source code as per Google's 'installed application' OAuth flow guidelines, where it is not treated as confidential. ```typescript const OAUTH_CLIENT_ID = '681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com'; const OAUTH_CLIENT_SECRET = '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'; ``` -------------------------------- ### Go MCP Server with 'hello_world' Tool Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/go_mcp_server_research.md Sets up a basic MCP server in Go, defining a 'hello_world' tool that accepts a 'name' argument and returns a greeting. It includes server initialization, tool definition, handler implementation, and standard I/O serving. ```go package main import ( "context" "fmt" "github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server" ) // helloHandler is the function that executes when the "hello_world" tool is called. func helloHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) { // Extract the "name" argument from the tool request. name, err := request.RequireString("name") if err != nil { // Return an error result if the required argument is missing. return mcp.NewToolResultError(err.Error()), nil } // If successful, return a text result. return mcp.NewToolResultText(fmt.Sprintf("Hello, %s!", name)), nil } func main() { // 1. Create a new MCP server instance. s := server.NewMCPServer( "HelloWorldServer", "1.0.0", // You can configure server capabilities, for example, disabling resource capabilities. server.WithToolCapabilities(false), ) // 2. Define a tool. tool := mcp.NewTool( "hello_world", mcp.WithDescription("Say hello to someone."), // Define the arguments the tool accepts. This one takes a required string named "name". mcp.WithString( "name", mcp.Required(), mcp.Description("The name of the person to greet."), ), ) // 3. Add the tool to the server and associate it with its handler function. s.AddTool(tool, helloHandler) fmt.Println("Starting MCP server over stdio...") // 4. Start the server using the stdio transport. // This is a common transport for local MCP servers. if err := server.ServeStdio(s); err != nil { fmt.Printf("Server error: %v\n", err) } } ``` -------------------------------- ### Initialize MCP Server and Add Tool with Official Go SDK (Unstable) Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/go_mcp_server_research.md Demonstrates how to create a new MCP server and register a simple 'greet' tool using the unstable official Go SDK. It shows basic server instantiation and tool input definition with a description for the 'name' property. ```go server := mcp.NewServer("greeter", "v1.0.0", nil) server.AddTools( mcp.NewServerTool("greet", "say hi", SayHi, mcp.Input( mcp.Property("name", mcp.Description("the name of the person to greet")) ) ) ) ``` -------------------------------- ### Build Gemini Grounding MCP Server from Source Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/README.md This snippet provides commands to clone the repository, navigate into the directory, and build the Gemini Grounding MCP server executable from its source code using `make`. An additional command is provided to list all available `make` commands. ```bash git clone https://github.com/ml0-1337/mcp-gemini-grounding.git cd mcp-gemini-grounding make build ``` ```bash make help ``` -------------------------------- ### Build Server to Resolve Missing Binary Error Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/scripts/test/README.md If you encounter 'command not found' errors for the server binary, navigate to the project root and run `make build`. This compiles the necessary components, after which you can return to the test script directory. ```bash cd ../.. make build cd scripts/test ``` -------------------------------- ### Running Project Tests and Coverage with Make Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/README.md Commands for executing various types of tests for the `mcp-gemini-grounding` project, including running all tests, generating code coverage reports, and detecting race conditions. An option to generate an HTML coverage report for detailed analysis is also provided. ```bash # Run all tests make test # Run tests with coverage make cover # Run tests with race detection make test-race # Generate HTML coverage report make cover-html ``` -------------------------------- ### Build Go MCP Server Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/go_mcp_server_research.md Compiles the Go source code into an executable binary. This command should be executed in the directory containing the `main.go` file. ```bash go build ``` -------------------------------- ### Run Go MCP Server Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/go_mcp_server_research.md Executes the compiled MCP server. The server will then listen for incoming MCP client connections over standard I/O streams. ```bash ./mcp-server-example ``` -------------------------------- ### Go: Authenticating Gemini API with Service Account OAuth2 Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-mcp-implementation-analysis-updated.md This Go code snippet demonstrates how to initialize a `genai.Client` using a Google Cloud service account JSON key for authentication. It illustrates the use of `option.WithCredentialsFile` to provide the service account credentials, ensuring secure server-to-server authentication with the Gemini API. ```Go import ( "google.golang.org/api/option" "google.golang.org/genai" ) // Use service account ctx := context.Background() client, err := genai.NewClient(ctx, &genai.ClientConfig{ APIKey: "", // Leave empty Backend: genai.BackendGeminiAPI, Options: []option.ClientOption{ option.WithCredentialsFile("path/to/service-account.json"), }, }) ``` -------------------------------- ### Recommendations for Integrating OAuth2 Authentication Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-implementation-report.md Provides guidance for developers integrating similar OAuth2 authentication mechanisms, drawing lessons from the Gemini CLI's implementation. Key recommendations include using established libraries, implementing token caching, handling multiple authentication methods, providing clear error messages, supporting offline access, and ensuring proper cleanup. ```APIDOC 1. Use Established Libraries: Leverage google-auth-library for OAuth2 handling 2. Implement Token Caching: Store tokens securely in user-specific locations 3. Handle Multiple Auth Methods: Provide fallback authentication options 4. Clear Error Messages: Provide specific guidance for common issues 5. Support Offline Access: Request offline access for refresh token support 6. Implement Proper Cleanup: Allow users to clear cached credentials ``` -------------------------------- ### MCP Server Configuration with Environment Variables Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/go_mcp_server_research.md Illustrates how to configure MCP servers within a `settings.json` file to inject environment variables, such as `GEMINI_API_KEY` and `GOOGLE_CSE_ID`, into the server's execution environment. This promotes secure credential management by externalizing sensitive information. ```json { "mcpServers": { "gemini-grounding": { "command": "go", "args": ["run", "./mcp-gemini-grounding"], "env": { "GEMINI_API_KEY": "$GEMINI_API_KEY", "GOOGLE_SEARCH_ENGINE_ID": "$GOOGLE_CSE_ID" } } } } ``` -------------------------------- ### Gemini CLI OAuth2 Authentication Flow Steps Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-implementation-report.md Outlines the sequential steps of the OAuth2 authentication process in the Gemini CLI, from checking cached credentials to initiating web login, browser authentication, and finally, token exchange and local caching. ```APIDOC 1. Check for Cached Credentials: The system first checks for cached credentials in ~/.gemini/oauth_creds.json 2. Initiate Web Login: If no valid cached credentials exist, the system: - Finds an available local port - Creates a local HTTP server to handle the OAuth callback - Generates a secure state parameter for CSRF protection - Creates an authorization URL with the redirect URI http://localhost:[port]/oauth2callback 3. Browser Authentication: - Opens the user's default browser to the authorization URL - User authenticates with Google and grants permissions - Google redirects back to the local callback server 4. Token Exchange: - The callback server receives the authorization code - Exchanges the code for access and refresh tokens - Caches the tokens locally for future use ``` -------------------------------- ### Securely Accessing API Keys in Go Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/go_mcp_server_research.md Demonstrates the secure way to access API keys in Go by reading them from environment variables using `os.Getenv()`, contrasting it with the insecure practice of hardcoding credentials directly in the source code. ```go // Bad const API_KEY = "sk_1234567890abcdef" // Good apiKey := os.Getenv("GEMINI_API_KEY") ``` -------------------------------- ### Gemini CLI Code Assist API Integration Details Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-implementation-report.md Describes how the OAuth2 client integrates with Google's Code Assist API. This includes the user onboarding process to determine tier and project requirements, and how all API requests are automatically authenticated using the OAuth2Client's `request()` method, handling token refresh transparently. ```APIDOC User Onboarding: - After OAuth authentication, users go through an onboarding process - The system determines the user's tier (free-tier, legacy-tier, standard-tier) - For Workspace users, a Google Cloud Project ID is required Request Authentication: - All API requests use the OAuth2Client's request() method - This automatically includes the access token in request headers - Handles token refresh transparently on 401/403 responses ``` -------------------------------- ### Google Go SDK (genai) Custom Authentication Mechanisms Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-mcp-implementation-research.md This API documentation outlines the methods provided by the `google.golang.org/genai` SDK for custom authentication. It details the `NewClient` function and the `ClientConfig` struct, specifically highlighting the `HTTPClient` and `Credentials` fields as mechanisms to inject pre-configured authentication, allowing developers to use OAuth2 or other credential types. ```APIDOC Package: google.golang.org/genai Function: NewClient(ctx context.Context, config *ClientConfig) (*Client, error) Purpose: Creates a new GenAI client instance. Parameters: ctx: Context for the client operations. config: Configuration options for the client. Struct: ClientConfig Fields: HTTPClient *http.Client Purpose: An optional HTTP client to use for requests. Can be pre-configured with OAuth2 or other authentication. Credentials google.Credentials Purpose: Google credentials to use for authentication. If not specified, Application Default Credentials (ADC) are used by default. Backend genai.Backend Purpose: Specifies the backend API to use (e.g., BackendVertexAI, BackendGeminiAPI). ``` -------------------------------- ### Manual Claude Code MCP Server Configuration for Local Scope Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/README.md This JSON snippet illustrates the manual configuration for adding the Gemini Grounding MCP server to Claude Code's local scope. It specifies the command path and environment variables for authentication, stored in the project's `.claude/settings.local.json` file. ```json { "mcpServers": { "gemini-grounding": { "command": "/path/to/mcp-gemini-grounding", "env": { "GEMINI_API_KEY": "$GEMINI_API_KEY" } } } } ``` -------------------------------- ### Configure Google GenAI SDK with OAuth2 HTTP Client Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-mcp-implementation-research.md This Go code demonstrates how to integrate an OAuth2-configured HTTP client with the Google GenAI SDK. It shows how to create a client using `oauth2Config.Client` and then pass it to `genai.NewClient` via the `HTTPClient` field in `genai.ClientConfig` for custom authentication, enabling the SDK to use a pre-authenticated HTTP client. ```go // Create OAuth2-configured HTTP client httpClient := oauth2Config.Client(ctx, token) // Use with genai SDK client, err := genai.NewClient(ctx, &genai.ClientConfig{ HTTPClient: httpClient, Backend: genai.BackendVertexAI, // or BackendGeminiAPI }) ``` -------------------------------- ### Configure Gemini API Key Environment Variables Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/README.md Instructions for setting the `GEMINI_API_KEY` environment variable across different operating systems (macOS/Linux, Windows PowerShell, Windows Command Prompt) for secure API access. This variable is crucial for authenticating with the Gemini API and adheres to security best practices by avoiding hardcoding API keys. ```bash export GEMINI_API_KEY="your-api-key-here" ``` ```powershell $env:GEMINI_API_KEY="your-api-key-here" ``` ```cmd set GEMINI_API_KEY=your-api-key-here ``` -------------------------------- ### Manual Claude Code MCP Server Configuration for User Scope Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/README.md This JSON snippet illustrates the manual configuration for adding the Gemini Grounding MCP server to Claude Code's user-level settings. This global configuration allows the server to be used across all projects, referencing the command and environment variables. ```json { "mcpServers": { "gemini-grounding": { "command": "gemini", "env": { "GEMINI_API_KEY": "$GEMINI_API_KEY" } } } } ``` -------------------------------- ### Run Basic MCP Protocol Test with OAuth2 Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/scripts/test/README.md This script performs a basic MCP protocol test, forcing OAuth2 authentication by unsetting the GEMINI_API_KEY. It sends initialize and search requests via stdin to test the full flow: OAuth2 authentication, Code Assist API interaction, and Google Search integration. ```bash ./test_mcp_basic.sh ``` -------------------------------- ### Manual Claude Code MCP Server Configuration for Project Scope Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/README.md This JSON snippet shows the manual configuration for adding the Gemini Grounding MCP server to Claude Code's project scope. This configuration is stored in a `.mcp.json` file in the project root and is designed for team sharing, using environment variables for sensitive data. ```json { "mcpServers": { "gemini-grounding": { "command": "mcp-gemini-grounding", "env": { "GEMINI_API_KEY": "$GEMINI_API_KEY" } } } } ``` -------------------------------- ### MCP Protocol Core Architecture and Tool Endpoints Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/go_mcp_server_research.md Details the Model Context Protocol (MCP) client-server architecture, including the roles of Host, Clients, Servers, and the Base Protocol (JSON-RPC 2.0). It also specifies the two main endpoints (`tools/list` and `tools/call`) used by MCP servers for tool discovery and execution, along with supported transport options. ```APIDOC MCP Protocol: Core Architecture: Host: - Coordinates the system - Manages LLM interactions Clients: - Connect hosts to servers (1:1 relationships) Servers: - Provide specialized capabilities through tools, resources, and prompts Base Protocol: - Defines communication using JSON-RPC 2.0 Tool Implementation: Endpoints: - tools/list: - Returns all available tools with their schemas - tools/call: - Executes a specific tool with provided parameters Transport Options: - Stdio: - Communication via stdin/stdout (most common) - SSE (Server-Sent Events): - For web-based implementations - HTTP Streaming: - For HTTP-based communication ``` -------------------------------- ### Implemented Best Practices for OAuth2 Authentication Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-implementation-report.md Lists the security and usability best practices integrated into the Gemini CLI's OAuth2 implementation. These practices ensure robust authentication, including CSRF protection, automatic token refresh, comprehensive error handling, token validation, and clean credential management. ```APIDOC 1. Secure State Parameter: Uses crypto.randomBytes for CSRF protection 2. Automatic Token Refresh: Leverages google-auth-library's built-in refresh mechanism 3. Proper Error Handling: Comprehensive error messages and fallback behaviors 4. Token Validation: Validates cached tokens both locally and with the server 5. Clean Credential Management: Provides methods to clear cached credentials ``` -------------------------------- ### MCP Tool Schema for Google Search Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/web_search_mcp_prd.md Defines the structure and parameters for the 'google_search' tool exposed via the Model Context Protocol (MCP). This schema specifies the tool's name, a description of its functionality, and the input parameters required for its execution, which in this case is a single 'query' string. ```json { "name": "google_search", "description": "Uses Google Search via Gemini AI grounding to find information and provide synthesized answers with citations. Returns AI-generated summaries rather than raw search results.", "inputSchema": { "type": "object", "properties": { "query": { "type": "string", "description": "The search query to find information on the web" } }, "required": ["query"] } } ``` -------------------------------- ### Authentication Limitations and Considerations Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-implementation-report.md Outlines key limitations and requirements for different authentication methods within the Gemini CLI. This includes restrictions on token caching for OAuth users, environment variable requirements for Google Workspace accounts, and the necessity of a web browser for authentication. ```APIDOC Token Caching Limitations: - OAuth users cannot use the token caching feature for API optimization - This is because the Code Assist API doesn't support cached content creation - Only API key users (Gemini API key or Vertex AI) can benefit from token caching Workspace Account Requirements: - Google Workspace accounts must set `GOOGLE_CLOUD_PROJECT` environment variable - The project must have the Gemini for Cloud API enabled - Proper IAM permissions must be configured Browser Requirement: - Authentication requires a web browser that can communicate with localhost - This can be challenging in remote development environments - The authentication URL is displayed for manual copying if browser auto-open fails ``` -------------------------------- ### Go: Authenticating Gemini API with Application Default Credentials (ADC) Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-mcp-implementation-analysis-updated.md This snippet illustrates how to use Google Cloud's Application Default Credentials (ADC) for authenticating with the Gemini API. It shows setting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable or using `gcloud auth` from the command line, followed by the Go code that automatically leverages ADC without explicit credential files, simplifying authentication in Google Cloud environments. ```Shell export GOOGLE_APPLICATION_CREDENTIALS="path/to/service-account.json" // Or use gcloud auth gcloud auth application-default login ``` ```Go client, err := genai.NewClient(ctx, &genai.ClientConfig{ Backend: genai.BackendGeminiAPI, // SDK will automatically use ADC }) ``` -------------------------------- ### Go Struct Definitions for Gemini Grounding Metadata Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/web_search_mcp_prd.md These Go structs define the data model for grounding metadata. `GroundingMetadata` aggregates chunks and supports, while `GroundingChunk` details web sources and `GroundingSupport` links text segments to chunks with confidence scores. ```go type GroundingMetadata struct { GroundingChunks []GroundingChunk GroundingSupports []GroundingSupport } type GroundingChunk struct { Web struct { URI string Title string } } type GroundingSupport struct { Segment struct { StartIndex int EndIndex int Text string } GroundingChunkIndices []int ConfidenceScores []float64 } ``` -------------------------------- ### Loading Gemini CLI OAuth Credentials in Go Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/go_mcp_server_research.md Presents a Go function, `loadCredentials`, designed to read OAuth credentials from the `~/.gemini/oauth_creds.json` file. The function parses the JSON data into an `oauth2.Token` structure, providing a robust mechanism for integrating with Gemini CLI authentication, with a fallback if the file is not found. ```go // Check for OAuth credentials first func loadCredentials() (*oauth2.Token, error) { homeDir, _ := os.UserHomeDir() credPath := filepath.Join(homeDir, ".gemini", "oauth_creds.json") data, err := os.ReadFile(credPath) if err != nil { // Fall back to API key return nil, err } var creds OAuthCredentials if err := json.Unmarshal(data, &creds); err != nil { return nil, err } return &oauth2.Token{ AccessToken: creds.AccessToken, RefreshToken: creds.RefreshToken, Expiry: creds.Expiry, }, nil } ``` -------------------------------- ### Gemini CLI OAuth2 Security Considerations Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-implementation-report.md Outlines the security measures implemented in the Gemini CLI's OAuth2 flow. This includes CSRF protection using state parameters, secure handling of the local callback server, token storage security relying on OS-level permissions, and comprehensive error handling for authentication failures. ```APIDOC CSRF Protection: - Uses a cryptographically secure random state parameter - Validates state parameter on callback to prevent CSRF attacks Local Server Security: - Callback server only accepts requests to /oauth2callback - Server is immediately closed after handling the callback - Invalid requests are redirected to failure URL Token Security: - Tokens are stored locally in the user's home directory - File permissions rely on OS-level user isolation - Credentials can be cleared using clearCachedCredentialFile() Error Handling: - Comprehensive error handling for authentication failures - Specific error messages for Workspace accounts requiring project configuration - Graceful fallback to re-authentication on token validation failure ``` -------------------------------- ### Run Comprehensive MCP Protocol Test with Error Handling Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/scripts/test/README.md This script provides a more robust and comprehensive MCP protocol test using Python for proper subprocess and protocol handling. It sends well-formatted MCP requests and captures both stdout and stderr for detailed error analysis, making it more reliable than the basic test. ```bash ./test_mcp_full.sh ``` -------------------------------- ### Go: MCP Server OAuth Incompatibility Warning Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-mcp-implementation-analysis-updated.md This Go code snippet from the MCP server's `internal/gemini/client.go` demonstrates the explicit warning message displayed when an unsupported OAuth authentication type from the Gemini CLI is detected, advising users to use `GEMINI_API_KEY` instead. It highlights the server's current handling of the OAuth incompatibility. ```Go // From internal/gemini/client.go case auth.AuthTypeOAuth: // OAuth credentials from Gemini CLI are not supported with standard Gemini API fmt.Printf("Warning: OAuth authentication from Gemini CLI is not supported. Please use GEMINI_API_KEY instead.\n") ``` -------------------------------- ### MCP Server Configuration for Gemini Grounding (JSON) Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/web_search_mcp_prd.md This JSON snippet defines the configuration for the 'gemini-grounding' MCP server. It specifies the command to run, environment variables like `GEMINI_API_KEY`, and a timeout for the server process. ```json { "mcpServers": { "gemini-grounding": { "command": "mcp-gemini-grounding", "env": { "GEMINI_API_KEY": "$GEMINI_API_KEY" }, "timeout": 30000 } } } ``` -------------------------------- ### Troubleshooting Authentication Credential Checks Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/README.md Commands to verify the presence of OAuth credentials (`~/.gemini/oauth_creds.json`) or the `GEMINI_API_KEY` environment variable. These checks are essential for diagnosing common authentication issues when interacting with the Gemini API, ensuring that the necessary credentials are correctly configured and accessible. ```bash ls ~/.gemini/oauth_creds.json ``` ```bash echo $GEMINI_API_KEY ``` -------------------------------- ### mcp-gemini-grounding System Architecture Diagram Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/README.md A Mermaid diagram definition illustrating the high-level architecture of the `mcp-gemini-grounding` project. It depicts the flow from the MCP Client (e.g., Claude Code) through the project's internal components to the Google Cloud Gemini API, highlighting key interactions and modules like `cmd/gemini-grounding/main.go`, `internal/search`, `internal/gemini`, and `internal/auth`. ```mermaid graph TD subgraph User A[MCP Client e.g. Claude Code] end subgraph "mcp-gemini-grounding" B[cmd/gemini-grounding/main.go] C[internal/search] D[internal/gemini] E[internal/auth] end subgraph "Google Cloud" F[Gemini API] end A -- MCP Request --> B B -- Initializes --> C B -- Initializes --> D B -- Initializes --> E C -- Uses --> D D -- Uses --> E D -- Makes API Calls --> F style A fill:#f9f,stroke:#333,stroke-width:2px style F fill:#bbf,stroke:#333,stroke-width:2px ``` -------------------------------- ### Gemini CLI Authentication Flow Selection Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-implementation-report.md Describes the user interaction for selecting an authentication method in the Gemini CLI. It covers how the selection is prompted, persisted, and how cached credentials are managed when switching between authentication types. ```APIDOC - The CLI prompts users to select an authentication method on first run - Selection is stored in settings and persisted - When switching auth methods, cached credentials are automatically cleared ``` -------------------------------- ### Gemini CLI OAuth Token Management Details Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-implementation-report.md Describes how OAuth tokens are managed within the Gemini CLI, including their storage location, the automatic refresh mechanism provided by Google's `google-auth-library` when tokens expire or authentication errors occur, and the transparency of this process to the application layer. ```APIDOC Token Storage: - Tokens are stored in ~/.gemini/oauth_creds.json - The file contains both access and refresh tokens - Storage location: path.join(os.homedir(), '.gemini', 'oauth_creds.json') Automatic Token Refresh: - The implementation uses Google's google-auth-library OAuth2Client - This library automatically handles token refresh when: - The access token is expired - HTTP 401 or 403 responses are received - The client has a valid refresh token - Token refresh is transparent to the application layer ``` -------------------------------- ### Gemini CLI OAuth Credential File Format Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/go_mcp_server_research.md Defines the expected JSON structure for OAuth credentials as stored by the Gemini CLI. This format includes fields such as `client_id`, `client_secret`, `refresh_token`, `access_token`, and `expiry` for authentication. ```json { "type": "authorized_user", "client_id": "...", "client_secret": "...", "refresh_token": "...", "access_token": "...", "expiry": "2025-01-01T00:00:00Z" } ``` -------------------------------- ### Gemini CLI Cached Credentials Loading and Validation Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-implementation-report.md Asynchronous function signature for loading and validating cached OAuth credentials. It details the internal steps involved: loading tokens from a file, verifying their local structure, and performing a server-side check for revocation. ```typescript async function loadCachedCredentials(client: OAuth2Client): Promise { // 1. Load tokens from file // 2. Verify local token structure // 3. Check with server that token hasn't been revoked // 4. Return true if valid, false otherwise } ``` -------------------------------- ### Run Direct Code Assist API Test with cURL Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/scripts/test/README.md This script directly tests the Code Assist API using cURL, bypassing the MCP protocol. It's useful for isolating API-specific issues from MCP protocol overhead and validates OAuth2 token functionality independently. ```bash ./test_api_direct.sh ``` -------------------------------- ### Gemini CLI Code Assist API Endpoint Configuration Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-implementation-report.md Defines the primary API endpoint for Google's Code Assist service used by the Gemini CLI. It allows for overriding the default endpoint via an environment variable, providing flexibility for different deployment environments. ```typescript const CODE_ASSIST_ENDPOINT = process.env.CODE_ASSIST_ENDPOINT ?? 'https://cloudcode-pa.googleapis.com'; ``` -------------------------------- ### Gemini CLI OAuth Scopes Definition Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-implementation-report.md Specifies the Google API scopes requested by the Gemini CLI during the OAuth 2.0 authentication process. These scopes grant necessary permissions for cloud platform access, user email, and user profile information. ```typescript const OAUTH_SCOPE = [ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile' ]; ``` -------------------------------- ### Refresh Expired OAuth2 Token Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/scripts/test/README.md When encountering OAuth2 authentication errors due to an expired token, use this command to refresh your token via the `gemini` CLI. After refreshing, you can re-run your test scripts. ```bash gemini -p "test" ./test_mcp_basic.sh ``` -------------------------------- ### JSON Format for Gemini OAuth Credentials Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/web_search_mcp_prd.md This JSON structure outlines the format for storing OAuth credentials, including `client_id`, `client_secret`, `refresh_token`, `access_token`, and `expiry` for authentication with Gemini services. ```json { "type": "authorized_user", "client_id": "...", "client_secret": "...", "refresh_token": "...", "access_token": "...", "expiry": "2025-01-01T00:00:00Z" } ``` -------------------------------- ### Define Authentication Types (AuthType Enum) Source: https://github.com/ml0-1337/mcp-gemini-grounding/blob/main/docs/oauth2-implementation-report.md Defines the available authentication types for the Gemini CLI, including OAuth for personal accounts, Gemini API key, and Vertex AI. This enum is used internally to categorize and manage different authentication methods. ```typescript export enum AuthType { LOGIN_WITH_GOOGLE_PERSONAL = 'oauth-personal', USE_GEMINI = 'gemini-api-key', USE_VERTEX_AI = 'vertex-ai', } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.