Skip to main content
Glama
chrismannina

PubMed MCP Server

by chrismannina

advanced_search

Perform complex PubMed searches using multiple criteria, fields, and filters to find specific biomedical literature.

Instructions

Perform complex PubMed searches with multiple criteria

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
search_termsYesComplex search criteria with fields and operators
filtersNoAdditional filters
max_resultsNo

Implementation Reference

  • Main execution logic for advanced_search tool: parses arguments, constructs complex PubMed query with field-specific terms and operators, applies filters (publication types, languages, species), performs search via pubmed_client, formats and returns results using _format_article_summary.
    async def _handle_advanced_search(self, arguments: Dict[str, Any]) -> MCPResponse:
        """Handle advanced search with multiple criteria."""
        try:
            search_terms = arguments.get("search_terms", [])
            if not search_terms:
                return MCPResponse(
                    content=[{"type": "text", "text": "Search terms are required"}], is_error=True
                )
    
            max_results = arguments.get("max_results", 50)
            filters = arguments.get("filters", {})
    
            # Build complex query
            query_parts = []
            for i, term_info in enumerate(search_terms):
                term = term_info.get("term", "")
                field = term_info.get("field", "all")
                operator = term_info.get("operator", "AND") if i > 0 else ""
    
                if field == "title":
                    field_query = f'"{term}"[Title]'
                elif field == "abstract":
                    field_query = f'"{term}"[Abstract]'
                elif field == "author":
                    field_query = f'"{term}"[Author]'
                elif field == "journal":
                    field_query = f'"{term}"[Journal]'
                elif field == "mesh":
                    field_query = f'"{term}"[MeSH Terms]'
                else:
                    field_query = term
    
                if i > 0:
                    query_parts.append(f" {operator} ")
                query_parts.append(f"({field_query})")
    
            query = "".join(query_parts)
    
            # Apply filters
            filter_parts = []
            if filters.get("publication_types"):
                type_queries = [f'"{pt}"[Publication Type]' for pt in filters["publication_types"]]
                filter_parts.append(f"({' OR '.join(type_queries)})")
    
            if filters.get("languages"):
                lang_queries = [f'"{lang}"[Language]' for lang in filters["languages"]]
                filter_parts.append(f"({' OR '.join(lang_queries)})")
    
            if filters.get("species"):
                if "humans" in [s.lower() for s in filters["species"]]:
                    filter_parts.append("humans[MeSH Terms]")
    
            if filter_parts:
                query += " AND " + " AND ".join(filter_parts)
    
            # Perform search
            search_result = await self.pubmed_client.search_articles(
                query=query, max_results=max_results, cache=self.cache
            )
    
            content = []
            content.append(
                {
                    "type": "text",
                    "text": f"**Advanced Search Results**\n\n"
                    f"Query: {query}\n"
                    f"Total Results: {search_result.total_results:,}\n"
                    f"Returned: {search_result.returned_results}\n",
                }
            )
    
            for i, article_data in enumerate(search_result.articles, 1):
                article_text = self._format_article_summary(article_data, i)
                content.append({"type": "text", "text": article_text})
    
            return MCPResponse(content=content)
    
        except Exception as e:
            logger.error(f"Error in advanced_search: {e}")
            return MCPResponse(
                content=[{"type": "text", "text": f"Error: {str(e)}"}], is_error=True
            )
  • Input schema defining parameters for advanced_search: array of search_terms (with term, field, operator), optional filters object, and max_results.
    {
        "name": "advanced_search",
        "description": ("Perform complex PubMed searches with multiple criteria"),
        "inputSchema": {
            "type": "object",
            "properties": {
                "search_terms": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "term": {"type": "string"},
                            "field": {
                                "type": "string",
                                "enum": ["title", "abstract", "author", "journal", "mesh", "all"],
                            },
                            "operator": {"type": "string", "enum": ["AND", "OR", "NOT"]},
                        },
                        "required": ["term", "field"],
                    },
                    "description": ("Complex search criteria with fields and operators"),
                },
                "filters": {
                    "type": "object",
                    "properties": {
                        "publication_types": {"type": "array", "items": {"type": "string"}},
                        "species": {"type": "array", "items": {"type": "string"}},
                        "languages": {"type": "array", "items": {"type": "string"}},
                        "age_groups": {"type": "array", "items": {"type": "string"}},
                        "sex": {"type": "string", "enum": ["male", "female", "both"]},
                    },
                    "description": "Additional filters",
                },
                "max_results": {"type": "integer", "minimum": 1, "maximum": 200, "default": 50},
            },
            "required": ["search_terms"],
        },
    },
  • Maps tool name 'advanced_search' to its handler method _handle_advanced_search in the tool_handler's routing dictionary.
    handler_map = {
        "search_pubmed": self._handle_search_pubmed,
        "get_article_details": self._handle_get_article_details,
        "search_by_author": self._handle_search_by_author,
        "find_related_articles": self._handle_find_related_articles,
        "export_citations": self._handle_export_citations,
        "search_mesh_terms": self._handle_search_mesh_terms,
        "search_by_journal": self._handle_search_by_journal,
        "get_trending_topics": self._handle_get_trending_topics,
        "analyze_research_trends": self._handle_analyze_research_trends,
        "compare_articles": self._handle_compare_articles,
        "get_journal_metrics": self._handle_get_journal_metrics,
        "advanced_search": self._handle_advanced_search,
    }
Behavior2/5

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

With no annotations provided, the description carries full burden but offers minimal behavioral insight. It doesn't disclose whether this is a read-only operation, potential rate limits, authentication needs, or what the output looks like (e.g., result format, pagination). 'Perform complex searches' implies a query operation but lacks critical details for safe and effective use.

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 front-loads the core purpose without unnecessary elaboration. Every word contributes to understanding the tool's function, making it appropriately concise for a search operation.

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?

For a tool with 3 parameters, nested objects, no output schema, and no annotations, the description is inadequate. It doesn't address behavioral aspects (e.g., safety, limits), output expectations, or differentiation from siblings, leaving significant gaps for an AI agent to navigate this complex search functionality.

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 67%, with parameters like 'search_terms' and 'filters' having descriptions that match the tool's purpose. The description adds marginal value by hinting at 'multiple criteria', but doesn't elaborate beyond what the schema provides (e.g., explaining how operators work in practice). Baseline 3 is appropriate given moderate schema coverage.

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 action ('perform complex PubMed searches') and resource ('PubMed'), distinguishing it from simpler search tools. However, it doesn't explicitly differentiate from sibling tools like 'search_pubmed' or 'search_by_author', which would require more specific language about the 'complex' nature with 'multiple criteria'.

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 'search_pubmed' or 'search_by_author'. It mentions 'complex searches with multiple criteria' but doesn't specify thresholds or scenarios where this tool is preferred over simpler siblings, leaving the agent to guess based on the name alone.

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

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