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;
    }
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. It mentions 'correlation analysis' which hints at statistical behavior, but doesn't describe what the output looks like, whether it requires authentication, rate limits, or data sources. For a tool with 4 parameters and no output schema, this is inadequate behavioral context.

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 a single, efficient sentence that communicates the core functionality without any wasted words. It's appropriately sized and front-loaded with the main purpose, making it easy for an agent to parse quickly.

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, no output schema, no annotations), the description is incomplete. It doesn't explain what 'trends' or 'correlation analysis' means in practice, what data source is used, or what format the results will be in. For a comparative analysis tool, this leaves significant gaps in understanding.

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 schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema (like explaining what 'correlation analysis' means in terms of parameters). Baseline 3 is appropriate when the schema does the heavy lifting.

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 with specific verbs ('compare trends', 'correlation analysis') and resources ('multiple topics over time'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate from sibling tools like 'guardian_content_timeline' or 'guardian_lookback' which might also involve time-based analysis, so it doesn't reach the highest score.

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 doesn't mention any prerequisites, exclusions, or compare it to sibling tools like 'guardian_search' or 'guardian_content_timeline' that might handle similar data. This leaves the agent without context for tool selection.

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

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