Skip to main content
Glama
tomekkorbak

Oura MCP Server

by tomekkorbak

get_sleep_data

Retrieve sleep data from Oura API for specified date ranges to analyze sleep patterns and quality metrics.

Instructions

Get sleep data for a specific date range.

Args:
    start_date: Start date in ISO format (YYYY-MM-DD)
    end_date: End date in ISO format (YYYY-MM-DD)

Returns:
    Dictionary containing sleep data

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
start_dateYes
end_dateYes

Implementation Reference

  • The main MCP tool handler for 'get_sleep_data'. It checks if the Oura client is initialized, parses the input date strings, calls the client's get_sleep_data method, and handles exceptions.
    @mcp.tool()
    def get_sleep_data(start_date: str, end_date: str) -> dict[str, Any]:
        """
        Get sleep data for a specific date range.
    
        Args:
            start_date: Start date in ISO format (YYYY-MM-DD)
            end_date: End date in ISO format (YYYY-MM-DD)
    
        Returns:
            Dictionary containing sleep data
        """
        if oura_client is None:
            return {"error": "Oura client not initialized. Please provide an access token."}
    
        try:
            start = parse_date(start_date)
            end = parse_date(end_date)
            return oura_client.get_sleep_data(start, end)
        except Exception as e:
            return {"error": str(e)}
  • Core helper in OuraClient class that fetches sleep data from the Oura API (/v2/usercollection/sleep), handles the HTTP request, transforms the raw data by formatting durations and times, and structures the output.
    def get_sleep_data(
        self, start_date: date, end_date: Optional[date] = None
    ) -> dict[str, Any]:
        """
        Get sleep data for a specific date range.
    
        Args:
            start_date: Start date for the query
            end_date: End date for the query (optional, defaults to start_date)
    
        Returns:
            Dictionary containing sleep data
        """
        if end_date is None:
            end_date = start_date
    
        params = {
            "start_date": start_date.isoformat(),
            "end_date": end_date.isoformat(),
        }
    
        url = f"{self.BASE_URL}/sleep"
        response = self.client.get(url, headers=self.headers, params=params)
    
        if response.status_code != 200:
            error_msg = f"Error {response.status_code}: {response.text}"
            raise Exception(error_msg)
    
        # Get the raw response
        raw_data = response.json()
    
        # Transform the data
        transformed_data = []
    
        for item in raw_data.get("data", []):
            # Format time durations
            awake_time = self._format_duration(item.get("awake_time", 0))
            deep_sleep_duration = self._format_duration(
                item.get("deep_sleep_duration", 0)
            )
            light_sleep_duration = self._format_duration(
                item.get("light_sleep_duration", 0)
            )
            rem_sleep_duration = self._format_duration(
                item.get("rem_sleep_duration", 0)
            )
            total_sleep_duration = self._format_duration(
                item.get("total_sleep_duration", 0)
            )
            time_in_bed = self._format_duration(item.get("time_in_bed", 0))
    
            # Format bedtime timestamps
            bedtime_start = self._format_time(item.get("bedtime_start", ""))
            bedtime_end = self._format_time(item.get("bedtime_end", ""))
    
            # Extract readiness data if available
            readiness = item.get("readiness", {})
            readiness_score = readiness.get("score") if readiness else None
            readiness_contributors = (
                readiness.get("contributors", {}) if readiness else {}
            )
    
            # Create transformed item
            transformed_item = {
                "day": item.get("day"),
                "bedtime_start": bedtime_start,
                "bedtime_end": bedtime_end,
                "awake_time": awake_time,
                "deep_sleep_duration": deep_sleep_duration,
                "light_sleep_duration": light_sleep_duration,
                "rem_sleep_duration": rem_sleep_duration,
                "total_sleep_duration": total_sleep_duration,
                "time_in_bed": time_in_bed,
                "efficiency": item.get("efficiency"),
                "latency": item.get("latency"),
                "restless_periods": item.get("restless_periods"),
                "average_breath": item.get("average_breath"),
                "average_heart_rate": item.get("average_heart_rate"),
                "average_hrv": item.get("average_hrv"),
                "lowest_heart_rate": item.get("lowest_heart_rate"),
            }
    
            # Add readiness data if available
            if readiness_score is not None:
                transformed_item["readiness_score"] = readiness_score
                transformed_item["readiness_contributors"] = readiness_contributors
    
            transformed_data.append(transformed_item)
    
        # Return with the original structure but with transformed data
        return {"data": transformed_data}
  • Helper function used by the tool handler to parse input date strings into date objects.
    def parse_date(date_str: str) -> date:
        """
        Parse a date string in ISO format (YYYY-MM-DD).
    
        Args:
            date_str: Date string in ISO format
    
        Returns:
            Date object
        """
        try:
            return date.fromisoformat(date_str)
        except ValueError as err:
            raise ValueError(
                f"Invalid date format: {date_str}. Expected format: YYYY-MM-DD"
            ) from err
  • Server initialization with FastMCP and OuraClient, where tools like get_sleep_data are registered via @mcp.tool() decorator.
    mcp = FastMCP("Oura API MCP Server")
    
    # Default access token (will be overridden in main or by direct assignment)
    default_token = os.environ.get("OURA_API_TOKEN")
    oura_client = OuraClient(default_token) if default_token else None
    
    
    # Add tools for querying sleep data
    @mcp.tool()

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/tomekkorbak/oura-mcp-server'

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