Skip to main content
Glama

search_pubmed

Search biomedical literature on PubMed using advanced queries, filters, and sorting to find relevant research articles.

Instructions

Search PubMed for articles matching a query.

Args: query: Search query. Supports full PubMed syntax: AND / OR / NOT, field tags like [tiab], [MeSH], [au], etc. Examples: "covid-19 vaccine efficacy" "myocardial infarction[MeSH] AND aspirin[tiab]" max_results: Number of articles to return (1-100, default 10). year_from: Restrict results to articles published from this year. year_to: Restrict results to articles published up to this year. article_type: Filter by publication type, e.g. "Review", "Clinical Trial", "Meta-Analysis", "Randomized Controlled Trial". sort: "relevance" (default) or "date" (most recent first).

Returns: A formatted list of matching articles with PMID, title, authors, journal, date, and a short abstract snippet. Returns an error message if the query fails or yields no results.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
max_resultsNo
year_fromNo
year_toNo
article_typeNo
sortNorelevance

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • main.py:271-375 (handler)
    The `search_pubmed` function is the core handler for searching PubMed articles, implementing logic to build a query, call the NCBI E-utilities API, and format the results.
    async def search_pubmed(
        query: str,
        max_results: int = 10,
        year_from: Optional[int] = None,
        year_to: Optional[int] = None,
        article_type: Optional[str] = None,
        sort: str = "relevance",
    ) -> str:
        """Search PubMed for articles matching a query.
    
        Args:
            query: Search query. Supports full PubMed syntax:
                   AND / OR / NOT, field tags like [tiab], [MeSH], [au], etc.
                   Examples:
                     "covid-19 vaccine efficacy"
                     "myocardial infarction[MeSH] AND aspirin[tiab]"
            max_results: Number of articles to return (1-100, default 10).
            year_from: Restrict results to articles published from this year.
            year_to:   Restrict results to articles published up to this year.
            article_type: Filter by publication type, e.g. "Review",
                          "Clinical Trial", "Meta-Analysis",
                          "Randomized Controlled Trial".
            sort: "relevance" (default) or "date" (most recent first).
    
        Returns:
            A formatted list of matching articles with PMID, title, authors,
            journal, date, and a short abstract snippet.
            Returns an error message if the query fails or yields no results.
        """
        if not query or not query.strip():
            return _err("Query must not be empty.")
    
        max_results = max(1, min(max_results, 100))
    
        # Build full query with optional filters
        full_query = query.strip()
        if year_from and year_to:
            if year_from > year_to:
                return _err(f"year_from ({year_from}) must be ≤ year_to ({year_to}).")
            full_query += f" AND {year_from}:{year_to}[pdat]"
        elif year_from:
            full_query += f" AND {year_from}:3000[pdat]"
        elif year_to:
            full_query += f" AND 1900:{year_to}[pdat]"
    
        if article_type:
            full_query += f' AND "{article_type.strip()}"[pt]'
    
        sort_param = "pub_date" if sort == "date" else "relevance"
    
        try:
            # Step 1: esearch → PMIDs
            search_resp = await _get(
                "esearch.fcgi",
                {
                    "db": "pubmed",
                    "term": full_query,
                    "retmax": max_results,
                    "retmode": "json",
                    "sort": sort_param,
                },
            )
            esearch = search_resp.json().get("esearchresult", {})
            id_list: list[str] = esearch.get("idlist", [])
            total: str = esearch.get("count", "0")
    
            # Warn if query was corrected/translated
            query_translation = esearch.get("querytranslation", "")
    
            if not id_list:
                return (
                    f"No articles found for query: {query!r}\n"
                    f"(Full query sent: {full_query})"
                )
    
            # Step 2: efetch → article XML
            fetch_resp = await _get(
                "efetch.fcgi",
                {
                    "db": "pubmed",
                    "id": ",".join(id_list),
                    "retmode": "xml",
                    "rettype": "abstract",
                },
            )
            root = _require_xml(fetch_resp, "efetch articles")
            articles = [_parse_article(a) for a in root.findall(".//PubmedArticle")]
    
            if not articles:
                return _err("Received empty article list from NCBI.")
    
            header_parts = [f"Found {total} total result(s). Showing {len(articles)}."]
            if query_translation:
                header_parts.append(f"Query interpreted as: {query_translation}")
            header = "\n".join(header_parts) + "\n"
    
            blocks = [_format_brief(a, i) for i, a in enumerate(articles, 1)]
            return header + "\n\n".join(blocks)
    
        except PubMedError as exc:
            return _err(str(exc))
    
    
    @mcp.tool()
    async def get_article(pmid: str) -> str:
Behavior4/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 and succeeds by detailing the return format as 'a formatted list of matching articles with PMID, title, authors, journal, date, and a short abstract snippet.' It also discloses error handling behavior, noting it returns an error message if the query fails or yields no results.

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?

The description uses a clear structured format with Args and Returns sections, and every line provides valuable information such as PubMed syntax examples and field tags. While lengthy, the examples are essential given the complexity of PubMed search syntax, making the length appropriate rather than wasteful.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the zero percent schema coverage and lack of annotations, the description is remarkably complete by documenting all input parameters with examples and explaining the output structure in the Returns section. No significant gaps remain for an agent to successfully invoke this tool.

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?

Despite 0% schema description coverage, the description comprehensively documents all six parameters through the Args section, including syntax examples for the query parameter, valid ranges for max_results, and allowed values for article_type and sort. This fully compensates for the complete lack of schema metadata.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool 'Search PubMed for articles matching a query,' providing a specific verb and resource. It implicitly distinguishes itself from sibling tools like get_article (which likely retrieves by ID) and search_by_author by emphasizing query-based matching rather than specific ID retrieval or author searching.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

While the description explains how to construct queries using PubMed syntax, it lacks explicit guidance on when to use this tool versus siblings like search_by_author. The Args section implies usage through examples but does not explicitly state when to choose this over alternative search methods.

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/benoitleq/mcp-pubmed'

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