Skip to main content
Glama
salwks

mcp-techTrend

pubmed_search

Read-onlyIdempotent

Search PubMed for biomedical publications using keywords, MeSH terms, and field tags. Filter results by recency with the days parameter and set the maximum number of results.

Instructions

Search PubMed for biomedical publications. Plain keywords work; for advanced queries use MeSH and field tags: mammography[MeSH], smith[Author], 2025[PDat]. Combine with AND/OR. days filters by publication date (PDat field).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
daysNo
max_resultsNo
response_formatNomarkdown

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The pubmed_search async function that executes the PubMed search logic. It calls esearch.fcgi for PMIDs, esummary.fcgi for metadata, and efetch.fcgi for abstracts, then formats results as markdown or JSON.
    async def pubmed_search(
        query: str,
        days: int | None = None,
        max_results: int = 20,
        response_format: ResponseFormat = ResponseFormat.MARKDOWN,
    ) -> str:
        try:
            args = PubMedSearchInput(
                query=query,
                days=days,
                max_results=max_results,
                response_format=response_format,
            )
            api_key = os.environ.get("NCBI_API_KEY")
            term = args.query
            if args.days:
                term = f"({term}) AND (\"last {args.days} days\"[PDat])"
    
            common: dict[str, Any] = {"db": "pubmed", "retmode": "json"}
            if api_key:
                common["api_key"] = api_key
    
            # Step 1: esearch -> PMID list
            esearch_params = {**common, "term": term, "retmax": args.max_results, "sort": "pub_date"}
            es_data = await _http_get_json(
                f"{PUBMED_BASE}/esearch.fcgi", params=esearch_params, ttl=TTL_STATIC
            )
            pmids: list[str] = es_data.get("esearchresult", {}).get("idlist", [])
            if not pmids:
                header = f"PubMed `{args.query}` (0건)"
                return _format([], args.response_format, render_md=lambda x: _render_pubmed_md(x, header))
    
            # Step 2: esummary -> metadata
            esum_params = {**common, "id": ",".join(pmids)}
            es2_data = await _http_get_json(
                f"{PUBMED_BASE}/esummary.fcgi", params=esum_params, ttl=TTL_STATIC
            )
            result = es2_data.get("result", {})
            uids = result.get("uids", pmids)
    
            items: list[dict[str, Any]] = []
            for uid in uids:
                r = result.get(uid)
                if not r:
                    continue
                authors = [a.get("name", "") for a in r.get("authors", []) if a.get("name")]
                items.append(
                    {
                        "pmid": uid,
                        "url": f"https://pubmed.ncbi.nlm.nih.gov/{uid}/",
                        "title": r.get("title", "").rstrip("."),
                        "journal": r.get("fulljournalname") or r.get("source") or "",
                        "pubdate": r.get("pubdate") or r.get("epubdate") or "",
                        "authors": authors,
                    }
                )
    
            # Step 3: efetch -> abstracts (one batched call). Best-effort: if it
            # fails or an article has no abstract, we just skip the field.
            abstracts = await _pubmed_fetch_abstracts([it["pmid"] for it in items])
            for it in items:
                it["abstract"] = abstracts.get(it["pmid"], "")
    
            header = f"PubMed `{args.query}` ({len(items)}건)"
            return _format(items, args.response_format, render_md=lambda x: _render_pubmed_md(x, header))
        except Exception as e:
            return _handle_error(e, "pubmed_search")
  • PubMedSearchInput Pydantic model defining input validation schema for pubmed_search: query (required), days, max_results, and response_format.
    class PubMedSearchInput(BaseModel):
        model_config = ConfigDict(str_strip_whitespace=True, extra="forbid")
        query: str = Field(..., min_length=1, max_length=500)
        days: int | None = Field(None, ge=1, le=3650)
        max_results: int = Field(20, ge=1, le=50)
        response_format: ResponseFormat = ResponseFormat.MARKDOWN
  • trends_mcp.py:558-572 (registration)
    Registration of pubmed_search via @_maybe_tool decorator with source='pubmed', name='pubmed_search', description, and annotations. The tool is only registered if 'pubmed' is in ENABLED_SOURCES.
    @_maybe_tool(
        source="pubmed",
        name="pubmed_search",
        description=(
            "Search PubMed for biomedical publications. Plain keywords work; for "
            "advanced queries use MeSH and field tags: `mammography[MeSH]`, "
            "`smith[Author]`, `2025[PDat]`. Combine with `AND`/`OR`. "
            "`days` filters by publication date (`PDat` field)."
        ),
        annotations={
            "readOnlyHint": True,
            "destructiveHint": False,
            "openWorldHint": True,
            "idempotentHint": True,
        },
  • _pubmed_fetch_abstracts helper function that fetches abstract text for given PMIDs via efetch.fcgi (XML). Returns {pmid: abstract_text} dictionary.
    async def _pubmed_fetch_abstracts(pmids: list[str]) -> dict[str, str]:
        """Fetch abstract text for each PMID via efetch.fcgi (XML).
    
        Returns {pmid: abstract_text}. Empty values for PMIDs without abstracts
        (e.g. editorials, letters). Failures are swallowed — caller falls back
        to no-abstract rendering.
        """
        if not pmids:
            return {}
        params: dict[str, Any] = {
            "db": "pubmed",
            "id": ",".join(pmids),
            "retmode": "xml",
        }
        api_key = os.environ.get("NCBI_API_KEY")
        if api_key:
            params["api_key"] = api_key
        try:
            text = await _http_get_text(
                f"{PUBMED_BASE}/efetch.fcgi", params=params, ttl=TTL_STATIC
            )
        except Exception:
            return {}
        out: dict[str, str] = {}
        try:
            root = ET.fromstring(text)
        except ET.ParseError:
            return {}
        for article in root.findall(".//PubmedArticle"):
            pmid_el = article.find(".//MedlineCitation/PMID")
            if pmid_el is None or not pmid_el.text:
                continue
            pmid = pmid_el.text.strip()
            # AbstractText can be split into Background/Methods/Results/Conclusions
            # via the `Label` attribute; concatenate with labels for readability.
            parts: list[str] = []
            for ab in article.findall(".//Abstract/AbstractText"):
                label = ab.attrib.get("Label", "").strip()
                content = "".join(ab.itertext()).strip()
                if not content:
                    continue
                parts.append(f"{label}: {content}" if label else content)
            if parts:
                out[pmid] = " ".join(parts)
        return out
  • _render_pubmed_md helper function that renders a list of PubMed items into Markdown format with title/URL, PMID, journal, date, authors, and abstract.
    def _render_pubmed_md(items: list[dict[str, Any]], header: str) -> str:
        if not items:
            return f"# {header}\n\n_결과 없음_"
        lines = [f"# {header}", f"_총 {len(items)}건_", ""]
        for i, it in enumerate(items, 1):
            authors = ", ".join(it["authors"][:4])
            if len(it["authors"]) > 4:
                authors += f" 외 {len(it['authors']) - 4}명"
            block = (
                f"## {i}. [{it['title']}]({it['url']})\n"
                f"- PMID `{it['pmid']}` · {it['journal']} · {it['pubdate']}\n"
                f"- 저자: {authors}\n"
            )
            if it.get("abstract"):
                block += f"- {_trim(it['abstract'], 500)}\n"
            lines.append(block)
        return "\n".join(lines)
Behavior4/5

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

Annotations already declare readOnlyHint=true, destructiveHint=false, idempotentHint=true. The description adds behavioral context about query syntax and date filtering, which is valuable but not contradicting annotations.

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 concise with no wasted words, front-loaded with the main purpose, and uses clear examples.

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?

An output schema exists, so return values need not be described, but the description fails to mention 'max_results' and 'response_format' parameters, leaving some gaps for a search tool.

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 0%, so description must compensate. It explains 'query' (plain vs. advanced) and 'days' (date filter) but omits 'max_results' and 'response_format', which have no description coverage.

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 'Search PubMed for biomedical publications' with a specific verb and resource, distinguishing it from sibling tools like arxiv_search.

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

Usage Guidelines4/5

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

Provides guidance on using plain keywords vs. advanced MeSH/field tags, and explains the 'days' parameter for date filtering. However, it does not explicitly state when not to use this tool.

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/salwks/mcp-techTrend'

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