Skip to main content
Glama
jbenton

guardian-mcp-server

by jbenton

guardian_search_by_length

Search Guardian articles by specifying word count range to find content matching desired length requirements.

Instructions

Search Guardian articles filtered by word count range

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryNoSearch terms (optional)
min_wordsNoMinimum word count (default: 0)
max_wordsNoMaximum word count (default: unlimited)
sectionNoFilter by section ID
from_dateNoStart date (YYYY-MM-DD format)
to_dateNoEnd date (YYYY-MM-DD format)
order_byNoSort order: 'newest', 'oldest', 'relevance' (default: 'newest')
page_sizeNoResults per page, max 200 (default: 20)

Implementation Reference

  • The core handler function that implements the tool logic: parses args, builds Guardian API search params, fetches articles, filters by wordcount range, and formats results.
    export async function guardianSearchByLength(client: GuardianClient, args: any): Promise<string> {
      const params = SearchByLengthParamsSchema.parse(args);
    
      // Build search parameters
      const searchParams: Record<string, any> = {
        'show-fields': 'headline,standfirst,byline,publication,firstPublicationDate,wordcount',
        'order-by': params.order_by || 'newest',
        'page-size': Math.min(params.page_size || 20, 200) // Get max for filtering
      };
    
      if (params.query) {
        searchParams.q = params.query;
      }
      if (params.section) {
        searchParams.section = params.section;
      }
      if (params.from_date) {
        const fromDate = validateDate(params.from_date);
        if (!fromDate) {
          throw new Error(`Invalid from_date format: ${params.from_date}. Use YYYY-MM-DD format.`);
        }
        searchParams['from-date'] = fromDate;
      }
      if (params.to_date) {
        const toDate = validateDate(params.to_date);
        if (!toDate) {
          throw new Error(`Invalid to_date format: ${params.to_date}. Use YYYY-MM-DD format.`);
        }
        searchParams['to-date'] = toDate;
      }
    
      const response = await client.search(searchParams);
      const articles = response.response.results;
    
      // Filter by word count
      const minWords = params.min_words || 0;
      const maxWords = params.max_words || Number.POSITIVE_INFINITY;
    
      const filteredArticles = articles.filter(article => {
        const wordCount = article.fields?.wordcount;
        if (wordCount && !isNaN(Number(wordCount))) {
          const count = Number(wordCount);
          return count >= minWords && count <= maxWords;
        }
        return false;
      });
    
      if (filteredArticles.length > 0) {
        const maxWordsDisplay = maxWords === Number.POSITIVE_INFINITY ? '∞' : maxWords.toString();
        let result = `Found ${filteredArticles.length} article(s) with ${minWords}-${maxWordsDisplay} words:\n\n`;
    
        filteredArticles.forEach((article, index) => {
          result += `**${index + 1}. ${article.webTitle || 'Untitled'}**\n`;
    
          if (article.fields) {
            const { fields } = article;
            
            if (fields.byline) {
              result += `By: ${fields.byline}\n`;
            }
            
            if (fields.firstPublicationDate) {
              const pubDate = fields.firstPublicationDate.substring(0, 10);
              result += `Published: ${pubDate}\n`;
            }
            
            if (fields.wordcount) {
              result += `Word count: ${fields.wordcount}\n`;
            }
            
            if (fields.standfirst) {
              result += `Summary: ${fields.standfirst}\n`;
            }
          }
    
          result += `Section: ${article.sectionName || 'Unknown'}\n`;
          result += `URL: ${article.webUrl || 'N/A'}\n\n`;
        });
    
        return result;
      } else {
        const maxWordsDisplay = maxWords === Number.POSITIVE_INFINITY ? '∞' : maxWords.toString();
        return `No articles found with word count between ${minWords} and ${maxWordsDisplay} words.`;
      }
    }
  • Zod schema for input validation used in the handler to parse and validate arguments.
    export const SearchByLengthParamsSchema = z.object({
      query: z.string().optional(),
      min_words: z.number().min(0).optional(),
      max_words: z.number().min(1).optional(),
      section: z.string().optional(),
      from_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
      to_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
      order_by: z.enum(['newest', 'oldest', 'relevance']).optional(),
      page_size: z.number().min(1).max(200).optional(),
    });
  • Registers the guardianSearchByLength handler function under the tool name 'guardian_search_by_length' in the tools registry returned by registerTools.
    guardian_search_by_length: (args) => guardianSearchByLength(client, args),
  • MCP tool schema definition including name, description, and inputSchema advertised in the ListTools response.
      name: 'guardian_search_by_length',
      description: 'Search Guardian articles filtered by word count range',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description: 'Search terms (optional)',
          },
          min_words: {
            type: 'integer',
            description: 'Minimum word count (default: 0)',
            minimum: 0,
          },
          max_words: {
            type: 'integer',
            description: 'Maximum word count (default: unlimited)',
            minimum: 1,
          },
          section: {
            type: 'string',
            description: 'Filter by section ID',
          },
          from_date: {
            type: 'string',
            description: 'Start date (YYYY-MM-DD format)',
          },
          to_date: {
            type: 'string',
            description: 'End date (YYYY-MM-DD format)',
          },
          order_by: {
            type: 'string',
            description: "Sort order: 'newest', 'oldest', 'relevance' (default: 'newest')",
            enum: ['newest', 'oldest', 'relevance'],
          },
          page_size: {
            type: 'integer',
            description: 'Results per page, max 200 (default: 20)',
            minimum: 1,
            maximum: 200,
          },
        },
      },
    },
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries full burden for behavioral disclosure. While 'search' implies a read-only operation, the description doesn't address important behavioral aspects like authentication requirements, rate limits, pagination behavior (beyond the 'page_size' parameter), error conditions, or what the response format looks like (no output schema exists).

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 states the core functionality without unnecessary words. It's appropriately sized for a search tool and front-loads the essential information (search + word count filtering).

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?

Given the tool's moderate complexity (8 parameters, no output schema, no annotations), the description is minimally adequate but incomplete. It identifies the core filtering dimension (word count) but doesn't provide context about how this integrates with other search capabilities, what constitutes a 'Guardian article' in this context, or typical use cases for word count filtering.

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?

Schema description coverage is 100%, so the schema already documents all 8 parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema - it mentions 'word count range' which corresponds to 'min_words' and 'max_words' parameters, but provides no extra context about how these interact with other parameters like 'query' or 'section'.

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: 'Search Guardian articles filtered by word count range.' It specifies the action (search), resource (Guardian articles), and key filtering dimension (word count range). However, it doesn't explicitly differentiate from sibling tools like 'guardian_search' or 'guardian_longread' which might also involve searching or filtering by length.

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 14 sibling tools including 'guardian_search' (general search) and 'guardian_longread' (likely for longer articles), there's no indication of when word count filtering is preferred over other search methods or when this tool is inappropriate.

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