Skip to main content
Glama
jbenton

guardian-mcp-server

by jbenton

guardian_topic_trends

Analyze and compare topic trends over time using The Guardian's archives to identify patterns and correlations between multiple subjects.

Instructions

Compare trends of multiple topics over time with correlation analysis

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
topicsYesList of topics/keywords to compare (max 5)
from_dateYesStart date (YYYY-MM-DD)
to_dateYesEnd date (YYYY-MM-DD)
intervalNoTime interval for comparison

Implementation Reference

  • The core handler function that implements the guardian_topic_trends tool. It validates input, generates time periods, performs Guardian API searches for each topic/period, calculates trends, percentages, strengths, correlations, and seasonal patterns, then formats a comprehensive report.
    export async function guardianTopicTrends(client: GuardianClient, args: any): Promise<string> {
      const params = TopicTrendsParamsSchema.parse(args);
    
      const fromDate = validateDate(params.from_date);
      const toDate = validateDate(params.to_date);
      
      if (!fromDate || !toDate) {
        throw new Error('Invalid date format. Use YYYY-MM-DD format.');
      }
    
      const interval = params.interval || 'quarter';
      
      // Generate time periods
      const periods = generateTimePeriods(fromDate, toDate, interval);
      
      let result = `Topic Trends Analysis (${fromDate} to ${toDate})\n`;
      result += `Comparing: ${params.topics.join(', ')}\n\n`;
      
      const topicData: TopicTrendData[] = [];
      
      // Analyze each topic
      for (const topic of params.topics) {
        const topicTrend: TopicTrendData = {
          topic: topic,
          periods: [],
          totalArticles: 0,
          trend: 'stable',
          trendStrength: 0
        };
        
        for (const period of periods) {
          const searchParams: Record<string, any> = {
            q: `"${topic}"`,
            'from-date': period.start,
            'to-date': period.end,
            'page-size': 1, // We only need the count
            'show-fields': 'headline'
          };
          
          try {
            const response = await client.search(searchParams);
            const count = response.response.total;
            
            topicTrend.periods.push({
              period: period.label,
              count: count,
              percentage: 0 // Will calculate after getting all data
            });
            
            topicTrend.totalArticles += count;
            
            // Rate limiting delay
            await new Promise(resolve => setTimeout(resolve, 100));
            
          } catch (error) {
            topicTrend.periods.push({
              period: period.label,
              count: 0,
              percentage: 0
            });
          }
        }
        
        // Calculate percentages and trend
        topicTrend.periods.forEach(p => {
          p.percentage = topicTrend.totalArticles > 0 ? (p.count / topicTrend.totalArticles) * 100 : 0;
        });
        
        topicTrend.trend = calculateTrend(topicTrend.periods.map(p => p.count));
        topicTrend.trendStrength = calculateTrendStrength(topicTrend.periods.map(p => p.count));
        
        topicData.push(topicTrend);
      }
      
      // Display overall statistics
      result += `**Overall Statistics**\n`;
      topicData.forEach(topic => {
        const trendIcon = getTrendIcon(topic.trend, topic.trendStrength);
        result += `• ${topic.topic}: ${topic.totalArticles} articles ${trendIcon}\n`;
      });
      result += '\n';
      
      // Show period-by-period breakdown
      result += `**Period Breakdown**\n`;
      periods.forEach((period, index) => {
        result += `\n**${period.label}**\n`;
        
        // Sort topics by count for this period
        const periodData = topicData
          .map(topic => ({
            topic: topic.topic,
            count: topic.periods[index].count
          }))
          .sort((a, b) => b.count - a.count);
        
        periodData.forEach((data, rank) => {
          const rankIcon = rank === 0 ? '🥇' : rank === 1 ? '🥈' : rank === 2 ? '🥉' : '  ';
          result += `${rankIcon} ${data.topic}: ${data.count} articles\n`;
        });
      });
      
      // Comparative analysis
      result += `\n**Comparative Analysis**\n`;
      
      // Find the dominant topic
      const dominantTopic = topicData.reduce((prev, current) => 
        prev.totalArticles > current.totalArticles ? prev : current
      );
      result += `• Most Covered: "${dominantTopic.topic}" (${dominantTopic.totalArticles} articles)\n`;
      
      // Find the fastest growing
      const fastestGrowing = topicData
        .filter(t => t.trend === 'increasing')
        .sort((a, b) => b.trendStrength - a.trendStrength)[0];
      
      if (fastestGrowing) {
        result += `• Fastest Growing: "${fastestGrowing.topic}" (${fastestGrowing.trendStrength.toFixed(1)}% increase)\n`;
      }
      
      // Find correlations (topics that trend together)
      const correlations = findCorrelations(topicData);
      if (correlations.length > 0) {
        result += `• Correlated Topics: ${correlations.join(', ')}\n`;
      }
      
      // Seasonal patterns
      if (interval === 'quarter' || interval === 'month') {
        const seasonalInsights = analyzeSeasonalPatterns(topicData, interval);
        if (seasonalInsights) {
          result += `• Seasonal Pattern: ${seasonalInsights}\n`;
        }
      }
      
      return result;
    }
  • Zod validation schema for the tool's input parameters, used in the handler for parsing and validation.
    export const TopicTrendsParamsSchema = z.object({
      topics: z.array(z.string()).min(1).max(5),
      from_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
      to_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
      interval: z.enum(['month', 'quarter', 'year']).optional(),
    });
  • Registers the guardianTopicTrends handler function under the 'guardian_topic_trends' key in the tools registry returned by registerTools.
    guardian_topic_trends: (args) => guardianTopicTrends(client, args),
  • src/index.ts:458-489 (registration)
    MCP tool registration in the ListTools response, including name, description, and input schema matching the zod schema.
    {
      name: 'guardian_topic_trends',
      description: 'Compare trends of multiple topics over time with correlation analysis',
      inputSchema: {
        type: 'object',
        properties: {
          topics: {
            type: 'array',
            items: {
              type: 'string',
            },
            description: 'List of topics/keywords to compare (max 5)',
            minItems: 1,
            maxItems: 5,
          },
          from_date: {
            type: 'string',
            description: 'Start date (YYYY-MM-DD)',
          },
          to_date: {
            type: 'string',
            description: 'End date (YYYY-MM-DD)',
          },
          interval: {
            type: 'string',
            description: 'Time interval for comparison',
            enum: ['month', 'quarter', 'year'],
          },
        },
        required: ['topics', 'from_date', 'to_date'],
      },
    },
  • Helper function to generate time periods based on interval for trend analysis.
    function generateTimePeriods(fromDate: string, toDate: string, interval: string): TimePeriod[] {
      const periods: TimePeriod[] = [];
      const start = new Date(fromDate);
      const end = new Date(toDate);
      
      let current = new Date(start);
      
      while (current <= end) {
        let periodEnd = new Date(current);
        let label = '';
        
        switch (interval) {
          case 'month':
            periodEnd = new Date(current.getFullYear(), current.getMonth() + 1, 0);
            if (periodEnd > end) periodEnd = new Date(end);
            label = current.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
            break;
          case 'quarter':
            const quarter = Math.floor(current.getMonth() / 3) + 1;
            periodEnd = new Date(current.getFullYear(), quarter * 3, 0);
            if (periodEnd > end) periodEnd = new Date(end);
            label = `Q${quarter} ${current.getFullYear()}`;
            break;
          case 'year':
            periodEnd = new Date(current.getFullYear(), 11, 31);
            if (periodEnd > end) periodEnd = new Date(end);
            label = current.getFullYear().toString();
            break;
        }
        
        periods.push({
          start: current.toISOString().substring(0, 10),
          end: periodEnd.toISOString().substring(0, 10),
          label: label
        });
        
        // Move to next period
        switch (interval) {
          case 'month':
            current.setMonth(current.getMonth() + 1);
            current.setDate(1);
            break;
          case 'quarter':
            current.setMonth(current.getMonth() + 3);
            current.setDate(1);
            break;
          case 'year':
            current.setFullYear(current.getFullYear() + 1);
            current.setMonth(0);
            current.setDate(1);
            break;
        }
      }
      
      return periods;
    }

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/jbenton/guardian-mcp-server'

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