Skip to main content
Glama

search_articles

Search New York Times articles by keyword, date range, and sort order to find relevant news content.

Instructions

Search New York Times articles by query, date range, and other criteria.

Args: query: Search query string sort: Sort order - "newest" or "oldest" (default: "newest") begin_date: Start date in YYYYMMDD format (optional) end_date: End date in YYYYMMDD format (optional) page: Page number for pagination, 0-indexed (optional)

Returns: Formatted response with articles array containing headline, snippet, web_url, and pub_date

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
sortNobest
begin_dateNo
end_dateNo
pageNo

Implementation Reference

  • Core handler function implementing the search_articles tool logic: parameter validation, NYT API request, and response formatting.
    async def search_articles(
        query: str,
        sort: SortOrder = "best",
        begin_date: str | None = None,
        end_date: str | None = None,
        page: int | None = None,
    ) -> dict:
        """
        Search New York Times articles by query, date range, and other criteria.
    
        Args:
            query: Search query string
            sort: Sort order - "best", "newest", "oldest", or "relevance" (default: "best")
            begin_date: Start date in YYYYMMDD format (optional)
            end_date: End date in YYYYMMDD format (optional)
            page: Page number for pagination (10 articles per page), 0-indexed, max=100 (optional)
    
        Returns:
            Formatted response with articles array containing headline, snippet, web_url, and pub_date
        """
        params = {
            "q": query.strip(),
            "sort": sort,
        }
    
        # Add optional date parameters only if specified
        if begin_date and len(begin_date) == 8:
            params["begin_date"] = begin_date
        elif begin_date:
            raise ValueError("begin_date must be in YYYYMMDD format.")
        if end_date and len(end_date) == 8:
            params["end_date"] = end_date
        elif end_date:
            raise ValueError("end_date must be in YYYYMMDD format.")
    
        # Only add page if it's greater than 0
        if page and page > 0 and page <= 100:
            params["page"] = str(page)
        elif page and page != 0:
            raise ValueError("Page number must be between 0 and 100.")
    
        client = get_client()
        response = await client.make_nyt_request("search/v2/articlesearch.json", params)
    
        return format_articles_response(response)
  • Tool registration using @mcp.tool() decorator, defines schema via type hints and docstring, thin wrapper delegating to tools.py implementation.
    @mcp.tool()
    async def search_articles(
        query: str,
        sort: tools.SortOrder = "best",
        begin_date: str | None = None,
        end_date: str | None = None,
        page: int | None = None,
    ) -> dict:
        """
        Search New York Times articles by query, date range, and other criteria.
    
        Args:
            query: Search query string
            sort: Sort order - "newest" or "oldest" (default: "newest")
            begin_date: Start date in YYYYMMDD format (optional)
            end_date: End date in YYYYMMDD format (optional)
            page: Page number for pagination, 0-indexed (optional)
    
        Returns:
            Formatted response with articles array containing headline, snippet, web_url, and pub_date
        """
        return await tools.search_articles(query, sort, begin_date, end_date, page)
  • Type definitions (Literals) for tool parameters, specifically SortOrder used in search_articles.
    type NewsSource = Literal["nyt", "inyt", "all"]
    type SortOrder = Literal["best", "newest", "oldest", "relevance"]
    type PopularityType = Literal["viewed", "shared", "emailed"]
    type PopularityPeriod = Literal["1", "7", "30"]
  • Helper function to format the NYT article search API response into a simplified structure used by search_articles.
    def format_articles_response(response: dict[str, Any]) -> dict[str, Any]:
        """
        Format article search response to extract essential fields.
    
        Args:
            response: Raw NYT article search API response
    
        Returns:
            Formatted response with articles array and total_hits
        """
        if "response" in response and "docs" in response["response"]:
            return {
                "articles": [
                    {
                        "headline": doc.get("headline", {}).get("main", ""),
                        "snippet": doc.get("snippet", ""),
                        "web_url": doc.get("web_url", ""),
                        "pub_date": doc.get("pub_date", ""),
                    }
                    for doc in response["response"]["docs"]
                ],
                "total_hits": response["response"].get("meta", {}).get("hits", 0),
            }
        return response
  • Shared NYT client factory used by search_articles to make API requests.
    def get_client() -> NytClient:
        """Get or create the shared HTTP client."""
        global _nyt_client
        if _nyt_client is None:
            _nyt_client = NytClient()
        return _nyt_client
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions pagination (page parameter) and returns formatted articles, but lacks details on rate limits, authentication needs, result limits, error handling, or whether this is a read-only operation. The description doesn't contradict annotations (none exist), but provides minimal 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.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Well-structured with a clear opening sentence followed by Args/Returns sections. Every sentence adds value, though the opening could be slightly more specific about what makes this search unique compared to siblings.

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?

For a search tool with 5 parameters, no annotations, and no output schema, the description covers parameters well but lacks behavioral context (rate limits, auth) and doesn't explain the return format beyond listing fields. It's adequate but has clear gaps in completeness.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description fully compensates by documenting all 5 parameters with clear semantics: query purpose, sort options with default, date formats, and pagination details. It adds significant value beyond the bare schema.

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 searches New York Times articles with specific criteria (query, date range, etc.), which is a specific verb+resource combination. However, it doesn't explicitly differentiate from sibling tools like 'get_latest_news' or 'get_archive', which might have overlapping functionality.

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 like 'get_latest_news' or 'get_archive'. It mentions search criteria but doesn't specify use cases, exclusions, or comparisons with sibling tools.

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/jeffmm/nytimes-mcp'

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