Skip to main content
Glama

get_food_log

Retrieve detailed nutrition data from Fitbit food logs for a specific date, including calories, protein, carbs, fat, fiber, sodium, daily totals, and individual food entries.

Instructions

Get comprehensive nutrition data (calories, protein, carbs, fat, fiber, sodium) from Fitbit food log for a specific date. Returns daily summary totals and individual food entries with nutritional values.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dateNoThe date for which to retrieve food log data (YYYY-MM-DD or 'today'). Defaults to 'today'.

Implementation Reference

  • The async handler function for the 'get_food_log' tool. It constructs the Fitbit API endpoint for food log on the specified date, fetches the data using makeFitbitRequest, handles errors, and returns the JSON response.
    async ({
      date = 'today',
    }: FoodLogParams): Promise<ToolResponseStructure> => {
      // Construct the endpoint
      const endpoint = `foods/log/date/${date}.json`;
    
      const foodLogData = await makeFitbitRequest<FoodLogResponse>(
        endpoint,
        getAccessTokenFn,
        FITBIT_API_BASE
      );
    
      // Handle API call failure
      if (!foodLogData) {
        return {
          content: [
            {
              type: 'text',
              text: `Failed to retrieve food log data from Fitbit API for date '${date}'. Check token and permissions.`,
            },
          ],
          isError: true,
        };
      }
    
      // Return successful response with raw JSON
      const rawJsonResponse = JSON.stringify(foodLogData, null, 2);
      return {
        content: [{ type: 'text', text: rawJsonResponse }],
      };
    }
  • Zod schema defining the input parameters for the 'get_food_log' tool, specifically the optional 'date' parameter.
    const foodLogParametersSchemaShape = {
      date: z
        .string()
        .regex(
          /^\d{4}-\d{2}-\d{2}$|^today$/,
          "Date must be in YYYY-MM-DD format or 'today'."
        )
        .optional()
        .describe(
          "The date for which to retrieve food log data (YYYY-MM-DD or 'today'). Defaults to 'today'."
        ),
    };
  • Registers the 'get_food_log' tool on the MCP server using server.tool(), providing name, description, input schema, and handler function.
    server.tool(
      foodLogToolName,
      foodLogDescription,
      foodLogParametersSchemaShape,
      async ({
        date = 'today',
      }: FoodLogParams): Promise<ToolResponseStructure> => {
        // Construct the endpoint
        const endpoint = `foods/log/date/${date}.json`;
    
        const foodLogData = await makeFitbitRequest<FoodLogResponse>(
          endpoint,
          getAccessTokenFn,
          FITBIT_API_BASE
        );
    
        // Handle API call failure
        if (!foodLogData) {
          return {
            content: [
              {
                type: 'text',
                text: `Failed to retrieve food log data from Fitbit API for date '${date}'. Check token and permissions.`,
              },
            ],
            isError: true,
          };
        }
    
        // Return successful response with raw JSON
        const rawJsonResponse = JSON.stringify(foodLogData, null, 2);
        return {
          content: [{ type: 'text', text: rawJsonResponse }],
        };
      }
    );
  • Shared helper function used by the handler to make authenticated requests to the Fitbit API.
    export async function makeFitbitRequest<T>(
      endpoint: string,
      getAccessTokenFn: () => Promise<string | null>,
      apiBase: string = FITBIT_API_VERSIONS.V1
    ): Promise<T | null> {
      const currentAccessToken = await getAccessTokenFn();
      if (!currentAccessToken) {
        console.error(`Error: ${ERROR_MESSAGES.NO_ACCESS_TOKEN}`);
        return null;
      }
    
      // Ensure endpoint starts correctly relative to the user path
      const cleanEndpoint = endpoint.startsWith('/')
        ? endpoint.substring(1)
        : endpoint;
      // Construct the full URL including the user scope '-'.
      const url = `${apiBase}/user/-/${cleanEndpoint}`;
      console.error(`Attempting Fitbit API request to: ${url}`);
    
      const headers = {
        'User-Agent': HTTP_CONFIG.USER_AGENT,
        Authorization: `Bearer ${currentAccessToken}`,
        Accept: 'application/json',
      };
    
      try {
        const response = await fetch(url, { headers });
        if (!response.ok) {
          const errorBody = await response.text();
          console.error(
            `Fitbit API Error! Status: ${response.status}, URL: ${url}, Body: ${errorBody}`
          );
          if (response.status === 401) {
            console.error(ERROR_MESSAGES.TOKEN_EXPIRED);
          }
          return null;
        }
        // Handle potential empty response body for certain success statuses (e.g., 204 No Content)
        if (response.status === 204) {
          return {} as T; // Return an empty object or appropriate type for no content
        }
        return (await response.json()) as T;
      } catch (error) {
        console.error(`Error making Fitbit request to ${url}:`, error);
        return null;
      }
    }
  • src/index.ts:82-82 (registration)
    Top-level call to registerNutritionTools, which includes the registration of 'get_food_log'.
    registerNutritionTools(server, getAccessToken);
Behavior3/5

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

No annotations are provided, so the description carries the full burden. It discloses that the tool returns daily summary totals and individual food entries with nutritional values, which adds useful context beyond basic functionality. However, it lacks details on permissions, rate limits, or error handling, which are important for a read operation.

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

Conciseness5/5

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

The description is front-loaded with the core purpose in the first sentence and efficiently adds details in the second sentence. Every sentence earns its place by specifying data types and return structure without unnecessary words, making it highly concise and well-structured.

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

Completeness4/5

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

Given the tool's low complexity (1 parameter, no output schema, no annotations), the description is fairly complete. It explains what data is retrieved and the return structure, but could improve by addressing potential issues like authentication needs or data availability, which would enhance agent understanding.

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

Parameters3/5

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

The input schema has 100% description coverage, with the 'date' parameter well-documented in the schema. The description adds no additional parameter information beyond what the schema provides, such as format examples or constraints, so it meets the baseline of 3 without compensating further.

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

Purpose5/5

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

The description clearly states the verb ('Get') and resource ('comprehensive nutrition data from Fitbit food log'), specifying the data types (calories, protein, carbs, etc.) and scope (for a specific date). It distinguishes from siblings like 'get_nutrition' by focusing on food log data with daily summary totals and individual entries.

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 for retrieving nutrition data from a food log on a specific date, but does not explicitly state when to use this tool versus alternatives like 'get_nutrition' or 'get_nutrition_by_date_range'. No exclusions or prerequisites are mentioned, leaving some ambiguity for the agent.

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/TheDigitalNinja/mcp-fitbit'

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