Skip to main content
Glama
pshempel

MCP Time Server Node

by pshempel

calculate_duration

Calculate the time duration between two specified times with customizable output units and timezone support for accurate interval measurement.

Instructions

Calculate duration between two times

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
start_timeYesStart time
end_timeYesEnd time
unitNoOutput unit (default: "auto")
timezoneNoTimezone for parsing (default: system timezone)

Implementation Reference

  • Main execution handler for the calculate_duration tool. Validates inputs, resolves timezone, parses dates, computes duration difference using date-fns, formats output based on unit, applies caching, and returns structured result.
    export function calculateDuration(params: CalculateDurationParams): CalculateDurationResult {
      debug.timing('calculateDuration called with params: %O', params);
      const { start_time, end_time } = params;
    
      // Validate string lengths first
      if (typeof start_time === 'string') {
        validateDateString(start_time, 'start_time');
      }
      if (typeof end_time === 'string') {
        validateDateString(end_time, 'end_time');
      }
    
      const config = getConfig();
      const unit = validateUnit(params.unit);
      const timezone = resolveTimezoneUtil(params.timezone, config.defaultTimezone);
    
      // Use withCache wrapper instead of manual cache management
      return withCache(
        `duration_${start_time}_${end_time}_${unit}_${timezone}`,
        CacheTTL.CALCULATIONS,
        () => {
          // Validate timezone
          if (!validateTimezone(timezone)) {
            debug.error('Invalid timezone: %s', timezone);
            throw new TimezoneError(`Invalid timezone: ${timezone}`, timezone);
          }
    
          // Parse dates with proper error context
          const startDate = parseDateWithContext(start_time, timezone, 'start_time');
          debug.timing('Parsed start date: %s', startDate.toISOString());
    
          const endDate = parseDateWithContext(end_time, timezone, 'end_time');
          debug.timing('Parsed end date: %s', endDate.toISOString());
    
          // Calculate all duration values
          const values = calculateDurationValues(startDate, endDate);
          debug.timing('Duration in milliseconds: %d', values.milliseconds);
    
          // Format the result
          const formatted = formatDurationResult(values, unit);
          debug.timing('Formatted duration: %s', formatted);
    
          const result: CalculateDurationResult = {
            ...values,
            formatted,
          };
    
          debug.timing('Returning result: %O', result);
          return result;
        }
      );
    }
  • TypeScript type definitions for input parameters (CalculateDurationParams) and output result (CalculateDurationResult) used by the handler.
    export interface CalculateDurationParams {
      start_time: string;
      end_time: string;
      unit?: string;
      timezone?: string;
    }
    
    export interface CalculateDurationResult {
      milliseconds: number;
      seconds: number;
      minutes: number;
      hours: number;
      days: number;
      formatted: string;
      is_negative: boolean;
    }
  • src/index.ts:116-131 (registration)
    Registration of the calculate_duration tool in TOOL_DEFINITIONS array, including name, description, and MCP input schema. Used in tools/list response.
      name: 'calculate_duration',
      description: 'Calculate duration between two times',
      inputSchema: {
        type: 'object' as const,
        properties: {
          start_time: { type: 'string' as const, description: 'Start time' },
          end_time: { type: 'string' as const, description: 'End time' },
          unit: { type: 'string' as const, description: 'Output unit (default: "auto")' },
          timezone: {
            type: 'string' as const,
            description: 'Timezone for parsing (default: system timezone)',
          },
        },
        required: ['start_time', 'end_time'],
      },
    },
  • src/index.ts:264-265 (registration)
    Mapping of tool name 'calculate_duration' to the imported calculateDuration handler function in TOOL_FUNCTIONS object, used during tools/call execution.
    calculate_duration: (params: unknown) =>
      calculateDuration(params as Parameters<typeof calculateDuration>[0]),
  • Core helper function that computes all duration components (ms, s, min, h, d) from two Date objects using date-fns differenceInMilliseconds.
    export function calculateDurationValues(startDate: Date, endDate: Date): DurationValues {
      debug.timing(
        'calculateDurationValues called with: start=%s, end=%s',
        startDate.toISOString(),
        endDate.toISOString()
      );
    
      const milliseconds = differenceInMilliseconds(endDate, startDate);
      const seconds = milliseconds / 1000;
      const minutes = seconds / 60;
      const hours = minutes / 60;
      const days = hours / 24;
      const is_negative = milliseconds < 0;
    
      const result = {
        milliseconds,
        seconds,
        minutes,
        hours,
        days,
        is_negative,
      };
    
      debug.timing('Calculated duration values: %O', result);
      return result;
    }
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 states the basic function but doesn't mention critical details like time format expectations (e.g., ISO 8601), error handling for invalid inputs, whether it supports negative durations, or if it's a pure calculation without side effects. This leaves significant gaps for an agent to use it correctly.

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 extremely concise at just four words ('Calculate duration between two times'), front-loading the core purpose with zero wasted text. Every word earns its place by directly conveying the tool's function, making it efficient and easy to parse.

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 time calculations and the lack of annotations and output schema, the description is incomplete. It doesn't address behavioral aspects like input formats, output details (e.g., numeric vs. string), or error cases, which are essential for an agent to invoke this tool reliably without structured guidance elsewhere.

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, clearly documenting all four parameters (start_time, end_time, unit, timezone) with their types and defaults. The description adds no additional parameter semantics beyond the schema, such as examples or constraints, so it meets the baseline for high schema coverage without compensating further.

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 'Calculate duration between two times' with a specific verb ('calculate') and resource ('duration'), making it immediately understandable. However, it doesn't differentiate from sibling tools like 'calculate_business_hours' or 'days_until', which also involve time calculations but with different scopes or constraints.

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. With siblings like 'calculate_business_hours' (which might exclude weekends/holidays) and 'days_until' (which might focus on calendar days), there's no indication of this tool's specific context, such as whether it handles raw time intervals or has other limitations.

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/pshempel/mcp-time-server-node'

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