Skip to main content
Glama
modellers

ConsignCloud MCP Server

by modellers

calculate_sales_totals

Calculate sales totals with filtering by date, status, location, customer, payment type, and amount. Returns revenue, tax, sale count, average value, and optional breakdowns for business analysis.

Instructions

Calculate sales totals with filtering by date range, status, location, customer, payment type, and amount. Returns total revenue, tax, sale count, average sale value, and optional breakdown by status, location, or date period.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
statusNoFilter by sale status
locationNoFilter by location ID
customerNoFilter by customer account ID
date_fromNoFilter sales created on or after this date (ISO 8601: YYYY-MM-DD)
date_toNoFilter sales created on or before this date (ISO 8601: YYYY-MM-DD)
payment_typeNoFilter by payment type (cash, card, etc.)
total_gteNoFilter sales with total >= this value (in cents)
total_lteNoFilter sales with total <= this value (in cents)
group_byNoGroup results by field for detailed breakdown
date_intervalNoWhen group_by=date, aggregate by this interval (day, week, or month)

Implementation Reference

  • src/server.ts:354-380 (registration)
    Tool registration in createTools() array, including name, description, and detailed inputSchema for parameters like status, location, dates, grouping.
    {
      name: 'calculate_sales_totals',
      description: 'Calculate sales totals with filtering by date range, status, location, customer, payment type, and amount. Returns total revenue, tax, sale count, average sale value, and optional breakdown by status, location, or date period.',
      inputSchema: {
        type: 'object',
        properties: {
          status: { type: 'string', enum: ['completed', 'voided', 'returned'], description: 'Filter by sale status' },
          location: { type: 'string', description: 'Filter by location ID' },
          customer: { type: 'string', description: 'Filter by customer account ID' },
          date_from: { type: 'string', description: 'Filter sales created on or after this date (ISO 8601: YYYY-MM-DD)' },
          date_to: { type: 'string', description: 'Filter sales created on or before this date (ISO 8601: YYYY-MM-DD)' },
          payment_type: { type: 'string', description: 'Filter by payment type (cash, card, etc.)' },
          total_gte: { type: 'number', description: 'Filter sales with total >= this value (in cents)' },
          total_lte: { type: 'number', description: 'Filter sales with total <= this value (in cents)' },
          group_by: {
            type: 'string',
            enum: ['status', 'location', 'date'],
            description: 'Group results by field for detailed breakdown'
          },
          date_interval: {
            type: 'string',
            enum: ['day', 'week', 'month'],
            description: 'When group_by=date, aggregate by this interval (day, week, or month)'
          },
        },
      },
    },
  • MCP server request handler (CallToolRequestSchema) switch case that executes the tool by calling ConsignCloudClient.calculateSalesTotals() with arguments and returns JSON stringified result.
    case 'calculate_sales_totals':
      return { content: [{ type: 'text', text: JSON.stringify(await client.calculateSalesTotals(args as any), null, 2) }] };
  • Core tool implementation in ConsignCloudClient: fetches all sales via pagination using listSales(), applies server-supported filters and client-side date filtering, calculates aggregate totals (revenue, tax, count, average), supports grouping by status/location/date with intervals, formats output with locale/currency awareness.
    async calculateSalesTotals(params?: {
      status?: string;
      location?: string;
      customer?: string;
      date_from?: string;
      date_to?: string;
      payment_type?: string;
      total_gte?: number;
      total_lte?: number;
      group_by?: 'status' | 'location' | 'date';
      date_interval?: 'day' | 'week' | 'month';
    }): Promise<SalesTotalsResult> {
      const { group_by, date_interval, ...filterParams } = params || {};
      const filters: string[] = [];
    
      // Track applied filters
      if (filterParams.status) filters.push(`status=${filterParams.status}`);
      if (filterParams.location) filters.push(`location=${filterParams.location}`);
      if (filterParams.customer) filters.push(`customer=${filterParams.customer}`);
      if (filterParams.date_from) filters.push(`date_from=${filterParams.date_from}`);
      if (filterParams.date_to) filters.push(`date_to=${filterParams.date_to}`);
      if (filterParams.payment_type) filters.push(`payment_type=${filterParams.payment_type}`);
      if (filterParams.total_gte !== undefined) filters.push(`total>=${filterParams.total_gte}`);
      if (filterParams.total_lte !== undefined) filters.push(`total<=${filterParams.total_lte}`);
    
      let allSales: Sale[] = [];
      let cursor: string | null = null;
    
      // Build query params with only defined values (excluding date filters - not supported by API)
      const queryParams: Record<string, any> = { limit: 100 };
      if (filterParams.status) queryParams.status = filterParams.status;
      if (filterParams.location) queryParams.location = filterParams.location;
      if (filterParams.customer) queryParams.customer = filterParams.customer;
      if (filterParams.payment_type) queryParams.payment_type = filterParams.payment_type;
      if (filterParams.total_gte !== undefined) queryParams.total_gte = filterParams.total_gte;
      if (filterParams.total_lte !== undefined) queryParams.total_lte = filterParams.total_lte;
      // NOTE: date_from/date_to NOT sent to API (not supported) - will filter client-side
    
      // Fetch all pages
      do {
        if (cursor) queryParams.cursor = cursor;
        const response = await this.listSales(queryParams);
        allSales = allSales.concat(response.data);
        cursor = response.next_cursor;
      } while (cursor);
    
      // Apply client-side date filtering (API doesn't support this)
      if (filterParams.date_from || filterParams.date_to) {
        allSales = allSales.filter(sale => {
          if (!sale.created) return false;
          const saleDate = new Date(sale.created);
          if (filterParams.date_from && saleDate < new Date(filterParams.date_from)) return false;
          if (filterParams.date_to && saleDate > new Date(filterParams.date_to)) return false;
          return true;
        });
      }
    
      // Calculate totals
      let totalRevenue = 0;
      let totalTax = 0;
      let totalSales = 0;
      const breakdown: Record<string, { revenue: number; revenue_formatted: string; tax: number; tax_formatted: string; count: number }> = {};
    
      for (const sale of allSales) {
        totalRevenue += sale.total || 0;
        totalTax += sale.tax || 0;
        totalSales += 1;
    
        // Group by if specified
        if (group_by) {
          let groupKey: string;
          switch (group_by) {
            case 'status':
              groupKey = sale.status;
              break;
            case 'location':
              groupKey = sale.location || 'no_location';
              break;
            case 'date':
              if (date_interval) {
                const date = new Date(sale.created);
                if (date_interval === 'day') {
                  groupKey = date.toISOString().split('T')[0];
                } else if (date_interval === 'week') {
                  const weekStart = new Date(date);
                  weekStart.setDate(date.getDate() - date.getDay());
                  groupKey = weekStart.toISOString().split('T')[0];
                } else if (date_interval === 'month') {
                  groupKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
                } else {
                  groupKey = date.toISOString().split('T')[0];
                }
              } else {
                groupKey = sale.created.split('T')[0];
              }
              break;
            default:
              groupKey = 'all';
          }
    
          if (!breakdown[groupKey]) {
            breakdown[groupKey] = { revenue: 0, revenue_formatted: '', tax: 0, tax_formatted: '', count: 0 };
          }
          breakdown[groupKey].revenue += sale.total || 0;
          breakdown[groupKey].tax += sale.tax || 0;
          breakdown[groupKey].count += 1;
        }
      }
    
      // Format breakdown values
      const formattedBreakdown: Record<string, { revenue: number; revenue_formatted: string; tax: number; tax_formatted: string; count: number }> | undefined =
        group_by ? Object.fromEntries(
          Object.entries(breakdown).map(([key, data]) => [
            key,
            {
              revenue: data.revenue,
              revenue_formatted: this.formatAmount(data.revenue),
              tax: data.tax,
              tax_formatted: this.formatAmount(data.tax),
              count: data.count
            }
          ])
        ) : undefined;
    
      const avgSale = totalSales > 0 ? Math.round(totalRevenue / totalSales) : 0;
    
      return {
        total_revenue: totalRevenue,
        total_revenue_formatted: this.formatAmount(totalRevenue),
        total_tax: totalTax,
        total_tax_formatted: this.formatAmount(totalTax),
        total_sales: totalSales,
        average_sale: avgSale,
        average_sale_formatted: this.formatAmount(avgSale),
        breakdown: formattedBreakdown,
        filters_applied: filters,
        currency: this.currency,
        locale: this.locale,
      };
    }
  • TypeScript interface defining the structured output returned by calculateSalesTotals, including totals, formatted strings, optional breakdown, applied filters, currency, and locale.
    export interface SalesTotalsResult {
      total_revenue: number; // in cents
      total_revenue_formatted: string; // locale-formatted
      total_tax: number; // in cents
      total_tax_formatted: string; // locale-formatted
      total_sales: number; // count
      average_sale: number; // in cents
      average_sale_formatted: string; // locale-formatted
      breakdown?: {
        [key: string]: {
          revenue: number;
          revenue_formatted: string;
          tax: number;
          tax_formatted: string;
          count: number;
        };
      };
      filters_applied: string[];
      currency: string; // ISO currency code
      locale: string; // BCP 47 locale
    }
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. While it mentions what the tool returns (revenue, tax, count, etc.), it doesn't address critical behavioral aspects like whether this is a read-only operation, potential performance impacts of complex filters, rate limits, authentication requirements, or error conditions. For a calculation tool with 10 parameters and no annotation coverage, this represents a significant transparency gap.

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 efficiently structured in two sentences that cover both the filtering capabilities and return values. It's appropriately sized for the tool's complexity, though it could be slightly more front-loaded by mentioning the core purpose more prominently before listing filter options.

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?

For a calculation tool with 10 parameters, no annotations, and no output schema, the description provides adequate basic information about what the tool does and what it returns. However, it lacks important context about behavioral characteristics, performance considerations, and differentiation from sibling tools. The absence of an output schema means the description should ideally provide more detail about return formats, but it only gives a high-level overview of what metrics are returned.

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 description lists filtering dimensions (date range, status, location, etc.) and mentions the optional breakdown capability, which aligns with the input schema parameters. However, with 100% schema description coverage where each parameter is already well-documented in the schema, the description adds only marginal value beyond what's already structured. The baseline of 3 is appropriate since the schema does the heavy lifting for parameter documentation.

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 as calculating sales totals with filtering capabilities, which is specific and actionable. However, it doesn't explicitly differentiate this from sibling tools like 'get_sales_trends' or 'get_account_stats' that might also involve sales data analysis, leaving room for ambiguity about when to choose this particular calculation tool.

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 like 'get_sales_trends' or 'list_sales'. It mentions filtering capabilities but doesn't specify scenarios where this calculation is preferred over other sales-related tools, leaving the agent without contextual usage instructions.

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/modellers/mcp-consigncloud'

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