Skip to main content
Glama
RyanCardin15

noaa-tidesandcurrents-mcp

get_next_sun_event

Calculate the next occurrence of a specific sun event (e.g., sunrise, sunset) for a given location and date using latitude, longitude, and optional timezone. Outputs in JSON or text format for easy integration.

Instructions

Get the next occurrence(s) of a specific sun event

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
countNoNumber of occurrences to return. Defaults to 1.
dateNoStarting date (YYYY-MM-DD format). Defaults to current date.
eventYesSun event to find
formatNoOutput format (json or text)
latitudeYesLatitude for location-specific calculations
longitudeYesLongitude for location-specific calculations
timezoneNoTimezone for the results. Defaults to UTC.

Implementation Reference

  • The handler function that executes the tool logic: calls SunService.getNextSunEvent and returns formatted text or JSON output.
    execute: async (params) => {
      try {
        const results = sunService.getNextSunEvent(params);
        if (params.format === 'text') {
          return results.map(result => 
            `Next ${result.event}: ${result.date} at ${result.time}`
          ).join('\n');
        }
        return JSON.stringify(results);
      } catch (error) {
        if (error instanceof Error) {
          throw new Error(`Failed to get next sun event: ${error.message}`);
        }
        throw new Error('Failed to get next sun event');
      }
    }
  • Registration of the get_next_sun_event tool with MCP server, specifying name, description, and input schema.
    // Add next sun event tool
    server.addTool({
      name: 'get_next_sun_event',
      description: 'Get the next occurrence(s) of a specific sun event',
      parameters: NextSunEventParamsSchema,
  • Zod schema for validating the tool's input parameters, including event type, optional date, location coordinates, count, format, and timezone.
    export const NextSunEventParamsSchema = z.object({
      event: z.nativeEnum(SunEventType).describe('Sun event to find'),
      date: z.string().optional().describe('Starting date (YYYY-MM-DD format). Defaults to current date.'),
      latitude: z.number().min(-90).max(90).describe('Latitude for location-specific calculations'),
      longitude: z.number().min(-180).max(180).describe('Longitude for location-specific calculations'),
      count: z.number().positive().optional().describe('Number of occurrences to return. Defaults to 1.'),
      format: z.enum(['json', 'text']).optional().describe('Output format (json or text)'),
      timezone: z.string().optional().describe('Timezone for the results. Defaults to UTC.')
    });
    
    export type NextSunEventParams = z.infer<typeof NextSunEventParamsSchema>; 
  • Supporting utility in SunService that implements the core algorithm for finding the next sun events using SunCalc.getTimes in a loop until required count is reached.
    getNextSunEvent(params: NextSunEventParams): { date: string, time: string, event: string }[] {
      const startDate = params.date ? new Date(params.date) : new Date();
      const count = params.count !== undefined ? params.count : 1;
      const { latitude, longitude } = params;
      const timezone = params.timezone !== undefined ? params.timezone : 'UTC';
      
      const results: { date: string, time: string, event: string }[] = [];
      let currentDate = new Date(startDate);
      
      // Find the next occurrences
      while (results.length < count) {
        const sunTimes = SunCalc.getTimes(currentDate, latitude, longitude);
        const eventTime = sunTimes[params.event as keyof typeof sunTimes];
        
        if (eventTime && !isNaN(eventTime.getTime()) && eventTime > startDate) {
          let formattedTime: string;
          
          try {
            formattedTime = eventTime.toLocaleTimeString('en-US', { timeZone: timezone });
          } catch (error) {
            // If timezone is invalid, fall back to ISO string
            console.warn(`Invalid timezone: ${timezone}. Using UTC.`);
            formattedTime = eventTime.toISOString().split('T')[1].split('.')[0];
          }
          
          results.push({
            date: eventTime.toISOString().split('T')[0],
            time: formattedTime,
            event: params.event as string
          });
          
          // Move to next day to find the next occurrence
          currentDate.setDate(currentDate.getDate() + 1);
        } else {
          // Event not found for this day, try next day
          currentDate.setDate(currentDate.getDate() + 1);
        }
        
        // Safety check to prevent infinite loops
        if (results.length === 0 && currentDate.getTime() - startDate.getTime() > 366 * 24 * 60 * 60 * 1000) {
          throw new Error('Could not find the specified sun event within a year.');
        }
      }
      
      return results;
    }

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/RyanCardin15/NOAA'

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