config.py•3.01 kB
"""Configuration management for GCP MCP server."""
import os
import json
from pathlib import Path
from typing import Dict, List, Optional, Any
from pydantic import BaseModel, Field
class AuthConfig(BaseModel):
"""Authentication configuration."""
method: str = Field(default="application_default", description="Authentication method")
service_account_path: Optional[str] = Field(default=None, description="Path to service account JSON")
project_id: Optional[str] = Field(default=None, description="Default project ID")
class LoggingConfig(BaseModel):
"""Logging configuration."""
level: str = Field(default="INFO", description="Log level")
format: str = Field(default="json", description="Log format")
class CacheConfig(BaseModel):
"""Cache configuration."""
enabled: bool = Field(default=True, description="Enable caching")
ttl_seconds: int = Field(default=300, description="Cache TTL in seconds")
class Config(BaseModel):
"""Main configuration for GCP MCP server."""
default_project: Optional[str] = Field(default=None, description="Default GCP project ID")
log_retention_days: int = Field(default=30, description="Log retention in days")
max_results: int = Field(default=1000, description="Maximum results per query")
excluded_log_names: List[str] = Field(default_factory=list, description="Log names to exclude")
authentication: AuthConfig = Field(default_factory=AuthConfig)
logging: LoggingConfig = Field(default_factory=LoggingConfig)
cache: CacheConfig = Field(default_factory=CacheConfig)
@classmethod
def load(cls, config_path: Optional[str] = None) -> "Config":
"""Load configuration from file or environment variables."""
config_data = {}
# Load from file if provided
if config_path and Path(config_path).exists():
with open(config_path, 'r') as f:
config_data = json.load(f)
# Override with environment variables
if os.getenv("GCP_PROJECT"):
config_data["default_project"] = os.getenv("GCP_PROJECT")
if os.getenv("GOOGLE_APPLICATION_CREDENTIALS"):
if "authentication" not in config_data:
config_data["authentication"] = {}
config_data["authentication"]["method"] = "service_account"
config_data["authentication"]["service_account_path"] = os.getenv("GOOGLE_APPLICATION_CREDENTIALS")
if os.getenv("LOG_LEVEL"):
if "logging" not in config_data:
config_data["logging"] = {}
config_data["logging"]["level"] = os.getenv("LOG_LEVEL")
return cls(**config_data)
def get_project_id(self) -> Optional[str]:
"""Get the project ID to use."""
return (
self.authentication.project_id
or self.default_project
or os.getenv("GCP_PROJECT")
or os.getenv("GOOGLE_CLOUD_PROJECT")
)