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()
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries full burden. It states the tool 'Get[s] sleep data' which implies a read-only operation, but doesn't disclose behavioral traits like authentication requirements, rate limits, data format details, or error handling. The description is minimal and doesn't add meaningful context beyond the basic operation.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded with the main purpose in the first sentence. The 'Args' and 'Returns' sections are structured but slightly redundant since the schema already defines parameters. Every sentence earns its place by clarifying parameter formats and return type, though it could be more concise by integrating information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (2 parameters, no annotations, no output schema), the description is minimally complete. It covers the purpose and parameters adequately but lacks details on return value structure, error cases, or integration with sibling tools. Without an output schema, the 'Returns' statement is vague ('Dictionary containing sleep data'), leaving gaps in understanding the response.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It provides clear semantics for both parameters: 'start_date' and 'end_date' are explained with format ('ISO format YYYY-MM-DD') and purpose. Since there are only 2 parameters and both are fully documented in the description, this effectively compensates for the schema gap. The baseline would be 3 with high coverage, but here the description adds significant value.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with a specific verb ('Get') and resource ('sleep data'), and specifies the scope ('for a specific date range'). It distinguishes from siblings like 'get_today_sleep_data' by indicating date range capability rather than just today's data. However, it doesn't explicitly differentiate from other siblings like 'get_readiness_data' or 'get_resilience_data' beyond the resource type.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage context through the date range requirement, suggesting it's for historical data retrieval. It doesn't provide explicit guidance on when to use this tool versus alternatives like 'get_today_sleep_data' for current data, or when not to use it. The context is clear but lacks specific alternatives or exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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