Skip to main content
Glama
janetsep

TreePod Financial MCP Agent

by janetsep

Calcular tarifa

calculate_tariff

Calculate booking tariffs based on season, number of guests, and booking channel using real configuration data from TreePod Financial MCP Agent.

Instructions

Calcula tarifas para reservas según temporada, personas y canal basado en configuración real

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
checkin_dateYes
checkout_dateYes
guestsYes
channelNodirecto

Implementation Reference

  • server.js:62-91 (registration)
    Registration of the 'calculate_tariff' tool with MCP server, including input schema, title, description, and a thin async handler that delegates to businessCalculator.calculateTariff with logging and error handling.
    server.registerTool(
      'calculate_tariff',
      {
        title: 'Calcular tarifa',
        description: 'Calcula tarifas para reservas según temporada, personas y canal basado en configuración real',
        inputSchema: z.object({
          checkin_date: z.string(),
          checkout_date: z.string(),
          guests: z.number().min(1).max(4),
          channel: z.string().optional().default('directo'),
        }),
      },
      async ({ checkin_date, checkout_date, guests, channel = 'directo' }) => {
        validator.log('info', `Iniciando cálculo de tarifa: ${guests} huéspedes, ${checkin_date} a ${checkout_date}, canal ${channel}`);
        
        try {
          // Usar módulo de cálculo sin hardcodeo
          const result = await businessCalculator.calculateTariff(checkin_date, checkout_date, guests, channel);
          
          validator.log('info', 'Cálculo de tarifa completado exitosamente');
          return result;
          
        } catch (error) {
          validator.log('error', `Error crítico en cálculo de tarifa: ${error.message}`);
          return validator.generateInsufficientDataResponse(
            'cálculo de tarifa',
            'Error interno del sistema. Contacta al administrador.'
          );
        }
      }
  • Core implementation of the tariff calculation: validates inputs and dates, loads financial configuration data, determines season, calculates base tariff and commission based on channel, computes total, and formats response.
    async calculateTariff(checkinDate, checkoutDate, guests, channel = 'directo') {
      // Validar parámetros de entrada
      const inputValidation = validator.validateUserInput({
        checkin_date: checkinDate,
        checkout_date: checkoutDate,
        guests: guests,
        channel: channel
      }, {
        checkin_date: { required: true, type: 'string' },
        checkout_date: { required: true, type: 'string' },
        guests: { required: true, type: 'number', min: 1, max: 4 },
        channel: { required: false, type: 'string', enum: ['directo', 'airbnb', 'booking', 'whatsapp'] }
      });
    
      if (!inputValidation.valid) {
        return validator.generateInsufficientDataResponse(
          'parámetros de tarifa', 
          `Errores: ${inputValidation.errors.join(', ')}`
        );
      }
    
      // Validar fechas
      const dateValidation = validator.validateDateRange(checkinDate, checkoutDate);
      if (!dateValidation.valid) {
        return validator.generateInsufficientDataResponse(
          'fechas de reserva',
          dateValidation.error
        );
      }
    
      // Cargar configuración de tarifas desde datos reales
      const financialData = await dataLoader.loadFinancialData();
      if (!financialData || !financialData.configuracion_negocio) {
        return validator.generateInsufficientDataResponse(
          'configuración de tarifas',
          'No se pudo acceder a la configuración de precios del sistema'
        );
      }
    
      const config = financialData.configuracion_negocio;
      
      // Verificar que existen las tarifas por temporada
      if (!config.tarifas_temporada) {
        return validator.generateInsufficientDataResponse(
          'tarifas por temporada',
          'La configuración no incluye tarifas por temporada'
        );
      }
    
      try {
        const season = this.determineSeason(dateValidation.checkin, config);
        const seasonData = config.tarifas_temporada[season];
        
        if (!seasonData) {
          return validator.generateInsufficientDataResponse(
            `tarifas para temporada ${season}`,
            'No se encontraron tarifas para la temporada solicitada'
          );
        }
    
        // Calcular tarifa base según número de huéspedes
        const baseTariff = this.calculateBaseTariff(guests, seasonData);
        const nights = dateValidation.nights;
        const subtotal = baseTariff * nights;
        
        // Calcular comisión según canal
        const commissionRate = this.getCommissionRate(channel, config);
        const commission = Math.round(subtotal * commissionRate);
        const total = subtotal + commission;
    
        validator.log('info', `Tarifa calculada: ${guests} huéspedes, ${nights} noches, temporada ${season}, canal ${channel}`);
    
        return {
          content: [{
            type: 'text',
            text: this.formatTariffResponse({
              checkinDate,
              checkoutDate,
              guests,
              channel,
              season,
              nights,
              baseTariff,
              subtotal,
              commissionRate: commissionRate * 100,
              commission,
              total
            })
          }]
        };
    
      } catch (error) {
        validator.log('error', `Error calculando tarifa: ${error.message}`);
        return validator.generateInsufficientDataResponse(
          'cálculo de tarifa',
          'Error interno en el cálculo. Contacta al administrador.'
        );
      }
    }
  • Helper method to determine the season (alta, media, etc.) for the given check-in date using business configuration or fallback logic.
    determineSeason(date, config) {
      if (!config.temporadas) {
        validator.log('warning', 'Configuración de temporadas no encontrada, usando lógica por defecto');
        // Lógica básica si no hay configuración
        const month = date.getMonth() + 1;
        if (month >= 12 || month <= 2) return 'alta';
        if (month >= 6 && month <= 8) return 'alta';
        return 'media';
      }
    
      // Usar configuración real de temporadas
      const month = date.getMonth() + 1;
      const day = date.getDate();
      
      for (const [seasonName, periods] of Object.entries(config.temporadas)) {
        for (const period of periods) {
          if (this.isDateInPeriod(month, day, period)) {
            return seasonName;
          }
        }
      }
      
      return 'media'; // temporada por defecto
    }
  • Helper method to compute the base nightly tariff based on number of guests and season data configuration.
    calculateBaseTariff(guests, seasonData) {
      if (seasonData.por_huesped && seasonData.tarifa_base_por_persona) {
        return seasonData.tarifa_base_por_persona * guests;
      }
      
      if (seasonData.tarifas_por_ocupacion) {
        const guestKey = `${guests}_personas`;
        return seasonData.tarifas_por_ocupacion[guestKey] || seasonData.tarifa_base || 80000;
      }
      
      return seasonData.tarifa_base || 80000;
    }
  • Helper method to get the commission rate for the booking channel from configuration or defaults.
    getCommissionRate(channel, config) {
      if (!config.comisiones_canal) {
        validator.log('warning', 'Configuración de comisiones no encontrada, usando valores por defecto');
        const defaultRates = {
          'directo': 0,
          'airbnb': 0.15,
          'booking': 0.18,
          'whatsapp': 0.05
        };
        return defaultRates[channel] || 0;
      }
      
      return config.comisiones_canal[channel] || 0;
    }
Behavior2/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 of behavioral disclosure. It mentions using 'configuración real' (real configuration), implying it relies on current settings, but doesn't detail aspects like rate limits, error handling, authentication needs, or whether it's a read-only operation. This leaves significant gaps in understanding how the tool behaves in practice.

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 a single, efficient sentence that directly states the tool's function without unnecessary words. It's front-loaded with the core purpose, making it easy to grasp quickly. However, it could be slightly more structured by separating key factors for clarity, but overall, it's concise and to the point.

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 tool's complexity (4 parameters, 0% schema coverage, no annotations, no output schema), the description is incomplete. It lacks details on parameter usage, behavioral traits, output format, and differentiation from siblings. For a tariff calculation tool that likely involves business logic and configuration, this minimal description doesn't provide enough context for effective use.

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?

Schema description coverage is 0%, so the description must compensate for undocumented parameters. It mentions season, people, and channel, which map to 'checkin_date/checkout_date', 'guests', and 'channel', adding some semantic context. However, it doesn't explain parameter formats (e.g., date format for 'checkin_date'), the meaning of 'channel' values, or constraints like the 'guests' range, leaving key details unclear.

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: calculating tariffs for reservations based on season, number of people, and channel using real configuration. It specifies the verb 'calcula' (calculates) and the resource 'tarifas' (tariffs), making the function evident. However, it doesn't explicitly differentiate from sibling tools like 'optimize_pricing' or 'compare_competition', which might have overlapping purposes.

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. It mentions the factors (season, people, channel) but doesn't specify scenarios, prerequisites, or exclusions. For example, it doesn't clarify if this is for real-time bookings, planning, or comparison with other tools like 'optimize_pricing' or 'predict_revenue', leaving usage ambiguous.

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/janetsep/treepod-financial-mcp'

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