Skip to main content
Glama

analyze_bioimpedance_pdf_base64

Analyze bioimpedance PDF data to extract health metrics and generate personalized recommendations from base64-encoded documents.

Instructions

Analyze a bioimpedance PDF document from base64-encoded data

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
base64DataYes
patientIdNo

Implementation Reference

  • MCP tool handler for 'analyze_bioimpedance_pdf_base64'. Defines input schema with Zod, executes PDF analysis from base64 data using PDFAnalysisService, and returns structured JSON response with health metrics, analysis, and recommendations.
    analyze_bioimpedance_pdf_base64: {
      description: 'Analyze a bioimpedance PDF document from base64-encoded data',
      parameters: z.object({
        base64Data: z.string().describe('Base64-encoded PDF data'),
        patientId: z.string().optional().describe('Optional patient ID for reference')
      }),
      execute: async (args: { base64Data: string; patientId?: string }) => {
        try {
          logger.info('Analyzing bioimpedance PDF from base64', {
            patientId: args.patientId,
            dataLength: args.base64Data.length
          });
    
          validateNotEmpty(args.base64Data, 'Base64 data');
    
          const analysis = await pdfService.analyzeBioimpedancePDFFromBase64(args.base64Data);
    
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify(
                  {
                    success: true,
                    patientId: args.patientId,
                    analysis: {
                      patientInfo: {
                        name: analysis.patientName,
                        date: analysis.date
                      },
                      measurements: {
                        weight: analysis.weight ? `${analysis.weight} kg` : 'N/A',
                        height: analysis.height ? `${analysis.height} cm` : 'N/A',
                        bmi: analysis.bmi || 'N/A',
                        bodyFatPercentage: analysis.bodyFatPercentage ? `${analysis.bodyFatPercentage}%` : 'N/A',
                        muscleMassPercentage: analysis.muscleMassPercentage ? `${analysis.muscleMassPercentage}%` : 'N/A',
                        boneMass: analysis.boneMass ? `${analysis.boneMass} kg` : 'N/A',
                        bodyWaterPercentage: analysis.bodyWaterPercentage ? `${analysis.bodyWaterPercentage}%` : 'N/A',
                        visceralFat: analysis.visceralFat || 'N/A',
                        bmr: analysis.bmr ? `${analysis.bmr} kcal` : 'N/A'
                      },
                      analysis: analysis.analysis,
                      recommendations: analysis.recommendations
                    }
                  },
                  null,
                  2
                )
              }
            ]
          };
        } catch (error) {
          logger.error('Failed to analyze bioimpedance PDF from base64', error);
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify(
                  {
                    success: false,
                    error: error instanceof Error ? error.message : 'Unknown error'
                  },
                  null,
                  2
                )
              }
            ],
            isError: true
          };
        }
      }
    }
  • src/index.ts:60-68 (registration)
    Registers the PDF tools (including analyze_bioimpedance_pdf_base64) by calling createPDFTools and merging into the allTools object used by MCP server handlers.
    const ticketTools = createTicketTools(apiService);
    const chatbotTools = createChatbotTools(chatbotService);
    const pdfTools = createPDFTools(pdfService);
    
    const allTools = {
      ...ticketTools,
      ...chatbotTools,
      ...pdfTools
    };
  • Core service method that implements the bioimpedance PDF analysis from base64: decodes data, parses PDF text, extracts measurements using regex patterns, generates analysis/recommendations, optionally enhances with AI.
    async analyzeBioimpedancePDFFromBase64(base64Data: string): Promise<BioimpedanceData> {
      try {
        logger.info('Starting PDF analysis from base64');
    
        // Decode base64 to buffer
        const buffer = Buffer.from(base64Data, 'base64');
        
        // Create parser and extract text
        const pdfParser = new PDFParse({ data: buffer });
        const textResult = await pdfParser.getText();
    
        logger.debug('PDF parsed successfully', {
          pages: textResult.pages.length,
          textLength: textResult.text.length
        });
    
        // Extract bioimpedance data from text
        const extractedData = this.extractBioimpedanceData(textResult.text);
    
        // Generate analysis and recommendations
        const insights = await this.enhanceWithAI(extractedData);
        const { analysis, recommendations } = insights;
    
        const result: BioimpedanceData = {
          ...extractedData,
          analysis,
          recommendations
        };
    
        logger.info('PDF analysis completed successfully');
        return result;
      } catch (error) {
        logger.error('Failed to analyze PDF from base64', error);
        throw new Error(`PDF analysis failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
      }
    }
  • Helper method that uses regex patterns to extract key bioimpedance measurements (patient info, weight, height, BMI, body fat %, muscle %, etc.) from parsed PDF text.
    private extractBioimpedanceData(text: string): Omit<BioimpedanceData, 'analysis' | 'recommendations'> {
      const data: Omit<BioimpedanceData, 'analysis' | 'recommendations'> = {};
    
      // Extract patient name
      const nameMatch = text.match(/(?:paciente|patient|nome|name)[:\s]+([^\n]+)/i);
      if (nameMatch) {
        data.patientName = nameMatch[1].trim();
      }
    
      // Extract date
      const dateMatch = text.match(/(?:data|date)[:\s]+(\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4})/i);
      if (dateMatch) {
        data.date = dateMatch[1];
      }
    
      // Extract weight (kg)
      const weightMatch = text.match(/(?:peso|weight)[:\s]+(\d+(?:\.\d+)?)\s*(?:kg)?/i);
      if (weightMatch) {
        data.weight = parseFloat(weightMatch[1]);
      }
    
      // Extract height (cm)
      const heightMatch = text.match(/(?:altura|height)[:\s]+(\d+(?:\.\d+)?)\s*(?:cm)?/i);
      if (heightMatch) {
        data.height = parseFloat(heightMatch[1]);
      }
    
      // Extract body fat percentage
      const bodyFatMatch = text.match(/(?:gordura corporal|body fat|%\s*gordura)[:\s]+(\d+(?:\.\d+)?)\s*%?/i);
      if (bodyFatMatch) {
        data.bodyFatPercentage = parseFloat(bodyFatMatch[1]);
      }
    
      // Extract muscle mass percentage
      const muscleMassMatch = text.match(/(?:massa muscular|muscle mass|%\s*m[uú]sculo)[:\s]+(\d+(?:\.\d+)?)\s*%?/i);
      if (muscleMassMatch) {
        data.muscleMassPercentage = parseFloat(muscleMassMatch[1]);
      }
    
      // Extract bone mass (kg)
      const boneMassMatch = text.match(/(?:massa [óo]ssea|bone mass)[:\s]+(\d+(?:\.\d+)?)\s*(?:kg)?/i);
      if (boneMassMatch) {
        data.boneMass = parseFloat(boneMassMatch[1]);
      }
    
      // Extract body water percentage
      const bodyWaterMatch = text.match(/(?:[áa]gua corporal|body water|%\s*[áa]gua)[:\s]+(\d+(?:\.\d+)?)\s*%?/i);
      if (bodyWaterMatch) {
        data.bodyWaterPercentage = parseFloat(bodyWaterMatch[1]);
      }
    
      // Extract visceral fat
      const visceralFatMatch = text.match(/(?:gordura visceral|visceral fat)[:\s]+(\d+(?:\.\d+)?)/i);
      if (visceralFatMatch) {
        data.visceralFat = parseFloat(visceralFatMatch[1]);
      }
    
      // Extract BMR (Basal Metabolic Rate)
      const bmrMatch = text.match(/(?:taxa metab[óo]lica basal|bmr|tmb)[:\s]+(\d+(?:\.\d+)?)\s*(?:kcal)?/i);
      if (bmrMatch) {
        data.bmr = parseFloat(bmrMatch[1]);
      }
    
      // Calculate or extract BMI
      const bmiMatch = text.match(/(?:imc|bmi)[:\s]+(\d+(?:\.\d+)?)/i);
      if (bmiMatch) {
        data.bmi = parseFloat(bmiMatch[1]);
      } else if (data.weight && data.height) {
        // Calculate BMI if not found: BMI = weight(kg) / (height(m))^2
        const heightInMeters = data.height / 100;
        data.bmi = parseFloat((data.weight / (heightInMeters * heightInMeters)).toFixed(2));
      }
    
      logger.debug('Extracted bioimpedance data', data);
      return data;
    }
  • TypeScript interface defining the structure of bioimpedance analysis data returned by the tool.
    export interface BioimpedanceData {
      patientName?: string;
      date?: string;
      weight?: number;
      height?: number;
      bodyFatPercentage?: number;
      muscleMassPercentage?: number;
      boneMass?: number;
      bodyWaterPercentage?: number;
      visceralFat?: number;
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure but only states what the tool does without detailing how it behaves. It doesn't mention whether this is a read-only analysis, if it modifies data, what the output format might be, potential errors, or any performance considerations like rate limits or processing time.

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 a single, efficient sentence that front-loads the core functionality without any wasted words. It's appropriately sized for a tool with a straightforward purpose, making it easy to parse quickly.

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

Completeness2/5

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

Given the complexity of analyzing a bioimpedance PDF (which likely involves extracting and interpreting medical data), no annotations, no output schema, and low schema coverage, the description is incomplete. It doesn't address what the analysis entails, what results to expect, or any domain-specific considerations, leaving significant gaps for an AI agent to operate effectively.

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

Parameters2/5

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

The description mentions 'base64-encoded data' but doesn't add meaning beyond what the input schema's parameter names imply. With 0% schema description coverage, the description fails to compensate by explaining the purpose of 'base64Data' or 'patientId', leaving the agent to guess their roles based on naming alone.

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 action ('analyze') and the resource ('bioimpedance PDF document from base64-encoded data'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from its sibling 'analyze_bioimpedance_pdf', which likely handles a different input format, leaving some ambiguity about when to choose one over the other.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives, such as the sibling 'analyze_bioimpedance_pdf' or other document analysis tools. It lacks context about prerequisites, typical use cases, or any exclusions, leaving the agent to infer usage based on the tool name alone.

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/osmarsant/fitslot-mcp'

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