Skip to main content
Glama
CW-Codewalnut

Metabase MCP Server

get_dashboard_cards

Retrieve all cards from a specific Metabase dashboard to analyze or manage its visualizations and data components.

Instructions

Get cards in a dashboard.

Args: dashboard_id (int): ID of the dashboard.

Returns: Dict[str, Any]: Cards in the dashboard.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dashboard_idYes

Implementation Reference

  • The main handler function for the get_dashboard_cards tool. It accepts a dashboard_id parameter and returns cards from the specified dashboard by making a GET request to the Metabase API endpoint /api/dashboard/{dashboard_id}/cards. The function is decorated with @mcp.tool() which registers it as an MCP tool.
    @mcp.tool()
    async def get_dashboard_cards(dashboard_id: int) -> Dict[str, Any]:
        """
        Get cards in a dashboard.
    
        Args:
            dashboard_id (int): ID of the dashboard.
    
        Returns:
            Dict[str, Any]: Cards in the dashboard.
        """
        logger.info(f"Getting cards for dashboard {dashboard_id}")
        return await make_metabase_request(RequestMethod.GET, f"/api/dashboard/{dashboard_id}/cards")
  • Initialization of the FastMCP server instance named 'mcp'. This is the MCP server object that the @mcp.tool() decorator uses to register the get_dashboard_cards function as an available tool.
    mcp = FastMCP("metabase", lifespan=app_lifespan)
  • The make_metabase_request helper function that handles all HTTP communication with the Metabase API. It accepts RequestMethod, endpoint, and optional parameters, then makes the actual API call. The get_dashboard_cards handler delegates to this function with RequestMethod.GET and the appropriate endpoint.
    async def make_metabase_request(
        method: RequestMethod,
        endpoint: str,
        data: Optional[Dict[str, Any] | bytes] = None,
        params: Optional[Dict[str, Any]] = None,
        json: Any = None,
        headers: Optional[Dict[str, str]] = None,
    ) -> Dict[str, Any]:
        """
        Make a request to the Metabase API.
        
        Args:
            method: HTTP method to use (GET, POST, PUT, DELETE)
            endpoint: API endpoint path
            data: Request data (for form data)
            params: URL parameters
            json: JSON request body
            headers: Additional headers
            
        Returns:
            Dict[str, Any]: Response data
            
        Raises:
            MetabaseConnectionError: When the Metabase server is unreachable
            MetabaseResponseError: When Metabase returns a non-2xx status code
            RuntimeError: For other errors
        """
        
        if not METABASE_URL or not METABASE_API_KEY:
            raise RuntimeError("METABASE_URL or METABASE_API_KEY environment variable is not set. Metabase API requests will fail.")
    
        if session is None:
            raise RuntimeError("HTTP session is not initialized. Ensure app_lifespan was called.")
    
        try:
            request_headers = headers or {}
            
            logger.debug(f"Making {method.name} request to {METABASE_URL}{endpoint}")
            
            # Log request payload for debugging (omit sensitive info)
            if json and logger.level <= logging.DEBUG:
                sanitized_json = {**json}
                if 'password' in sanitized_json:
                    sanitized_json['password'] = '********'
                logger.debug(f"Request payload: {sanitized_json}")
                
            response = await session.request(
                method=method.name,
                url=endpoint,
                timeout=aiohttp.ClientTimeout(total=30),
                headers=request_headers,
                data=data,
                params=params,
                json=json,
            )
    
            try:
                # Handle 500 errors with more detailed info
                if response.status >= 500:
                    error_text = await response.text()
                    logger.error(f"Server error {response.status}: {error_text[:200]}")
                    raise MetabaseResponseError(response.status, f"Server Error: {error_text[:200]}", endpoint)
                
                response.raise_for_status()
                response_data = await response.json()
                
                # Ensure the response is a dictionary for FastMCP compatibility
                return ensure_dict_response(response_data)
                
            except aiohttp.ContentTypeError:
                # Handle empty responses or non-JSON responses
                content = await response.text()
                if not content:
                    return {"data": {}}
                logger.warning(f"Received non-JSON response: {content}")
                return {"data": content}
    
        except aiohttp.ClientConnectionError as e:
            logger.error(f"Connection error: {str(e)}")
  • The RequestMethod enum defines the HTTP methods (GET, POST, PUT, DELETE) used by the helper function. The get_dashboard_cards tool uses RequestMethod.GET to specify the HTTP method for the API request.
    class RequestMethod(Enum):
        GET = auto()
        POST = auto()
        PUT = auto()
        DELETE = auto()
  • The DashboardCard dataclass defines the schema for a dashboard card in Metabase. While not directly used by the get_dashboard_cards function (which returns Dict[str, Any]), this model represents the structure of cards that may be returned and is used by related dashboard manipulation tools.
    @dataclass
    class DashboardCard:
        """
        Represents a card within a Metabase dashboard.
        
        Attributes:
            id (int): Use negative numbers to auto generate the ids 
                or use any unique value but,
                it must be unique within the dashboard
            card_id (int): The ID of the card/visualization
            row (int): The row position in the dashboard grid
            col (int): The column position in the dashboard grid
            size_x (int): The width of the card in grid units
            size_y (int): The height of the card in grid units
            parameter_mappings (List[Dict[str, Any]]): Parameter mappings for the card
        """
        id: int  # Use negative numbers to auto generate the ids
        card_id: int
        row: int
        col: int
        size_x: int
        size_y: int
        parameter_mappings: List[Dict[str, Any]] = field(default_factory=list)

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/CW-Codewalnut/metabase-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server