Skip to main content
Glama

search_arxiv

Search arXiv scholarly articles by keywords, authors, or abstracts to find relevant research papers with metadata.

Instructions

Performs a search query on the arXiv API based on specified parameters and returns matching article metadata. This function allows for flexible querying of the arXiv database. Only parameters that are explicitly provided will be included in the final search query. Results are returned in a JSON-formatted string with article titles as keys and their corresponding arXiv IDs as values.

Args: all_fields: General keyword search across all metadata fields including title, abstract, authors, comments, and categories. title: Keyword(s) to search for within the titles of articles. author: Author name(s) to filter results by. abstract: Keyword(s) to search for within article abstracts. start: Index of the first result to return; used for paginating through search results. Defaults to 0. max_results: Maximum number of results to return (1-50).

Returns: A JSON-formatted string containing article titles and their associated arXiv IDs; otherwise, a structured error JSON string.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
all_fieldsNo
titleNo
authorNo
abstractNo
startNo
max_resultsNo

Implementation Reference

  • The core handler for the 'search_arxiv' tool. Decorated with @mcp.tool() for registration in FastMCP. Handles search queries across arXiv fields, calls API, parses results, and returns title-mapped metadata.
    @mcp.tool()
    async def search_arxiv(
        ctx: Context,
        all_fields: Optional[str] = None,
        title: Optional[str] = None,
        author: Optional[str] = None,
        abstract: Optional[str] = None,
        start: int = 0,
        max_results: int = 10,
    ) -> Any:
        """
        Performs a search query on the arXiv API based on specified parameters and returns matching article metadata.
        This function allows for flexible querying of the arXiv database. Only parameters that are explicitly provided
        will be included in the final search query. Results are returned in a JSON-formatted string with article titles
        as keys and their corresponding arXiv IDs as values.
    
        Args:
            all_fields: General keyword search across all metadata fields including title, abstract, authors, comments, and categories.
            title: Keyword(s) to search for within the titles of articles.
            author: Author name(s) to filter results by.
            abstract: Keyword(s) to search for within article abstracts.
            start: Index of the first result to return; used for paginating through search results. Defaults to 0.
            max_results: Maximum number of results to return (1-50).
    
        Returns:
            A JSON-formatted string containing article titles and their associated arXiv IDs;
            otherwise, a structured error JSON string.
        """
        prefixed_params = []
        if author:
            author = format_text(author)
            prefixed_params.append(f"au:{author}")
        if all_fields:
            all_fields = format_text(all_fields)
            prefixed_params.append(f"all:{all_fields}")
        if title:
            title = format_text(title)
            prefixed_params.append(f"ti:{title}")
        if abstract:
            abstract = format_text(abstract)
            prefixed_params.append(f"abs:{abstract}")
        # Construct search query
        search_query = " AND ".join(prefixed_params)
        params = {
            "search_query": search_query,
            "start": start,
            "max_results": max(1, min(max_results, 50)),
        }
        await ctx.info("Calling the API")
        response = await make_api_call(f"{ARXIV_API_BASE}/query", params=params)
        if response is None:
            return _error("API_ERROR", "Unable to retrieve data from arXiv.org.")
        feed = feedparser.parse(response)
        error_msg = (
            "Unable to extract information for your query. "
            "This issue may stem from an incorrect search query."
        )
        if not feed.entries:
            return _error("NOT_FOUND", error_msg)
        entries: Dict[str, Dict[str, Any]] = {}
        await ctx.info("Extracting information")
        for entry in feed.entries:
            id = entry.id
            article_title = entry.title
            arxiv_id = id.split("/abs/")[-1]
            authors = [author['name'] for author in entry.authors]
            entries[article_title] = {"arXiv ID": arxiv_id, "Authors": authors}
        return entries
  • Helper function used by search_arxiv to make HTTP requests to arXiv API with retry logic.
    async def make_api_call(url: str, params: Dict[str, str]) -> Optional[str]:
        """Make a request to the arXiv API with retries."""
        headers = {"User-Agent": USER_AGENT, "Accept": "application/atom+xml"}
        async with httpx.AsyncClient(timeout=DEFAULT_TIMEOUT, limits=HTTP_LIMITS) as client:
            for attempt in range(RETRY_ATTEMPTS):
                try:
                    resp = await client.get(url, params=params, headers=headers)
                    resp.raise_for_status()
                    return resp.text
                except Exception:
                    if attempt < RETRY_ATTEMPTS - 1:
                        await _retry_sleep(attempt)
                        continue
                    return None
  • Utility function to format/clean search terms used in search_arxiv queries.
    def format_text(text: str) -> str:
        """Clean a given text string by removing escape sequences and leading and trailing whitespaces."""
        # Remove common escape sequences
        text_without_escapes = re.sub(r"\\[ntr]", " ", text)
        # Replace colon with space
        text_without_colon = text_without_escapes.replace(":", " ")
        # Remove both single quotes and double quotes
        text_without_quotes = re.sub(r"['\"]", "", text_without_colon)
        # Collapse multiple spaces into one
        text_single_spaced = re.sub(r"\s+", " ", text_without_quotes)
        # Trim leading and trailing spaces
        cleaned_text = text_single_spaced.strip()
        return cleaned_text
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses that 'only parameters explicitly provided will be included in the search query' and specifies the return format as JSON with titles as keys and arXiv IDs as values. However, it lacks details on rate limits, authentication needs, or error handling beyond a vague mention of 'structured error JSON string.'

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 is appropriately sized and front-loaded, starting with the core purpose. The Args and Returns sections are structured but slightly verbose; sentences like 'This function allows for flexible querying' could be trimmed without losing value, keeping it efficient overall.

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 6 parameters, no annotations, and no output schema, the description is moderately complete. It covers parameter semantics and return format but lacks details on behavioral aspects like rate limits or error structures. For a search tool with multiple parameters, it provides a baseline but misses advanced context needed for optimal agent use.

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

Parameters4/5

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

Schema description coverage is 0%, so the description must compensate. It effectively explains all 6 parameters: all_fields searches across all metadata, title searches titles, author filters by author, abstract searches abstracts, start is for pagination, and max_results limits results. This adds clear meaning beyond the bare schema, though it could detail format specifics like author name conventions.

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 'performs a search query on the arXiv API' and 'returns matching article metadata,' specifying both the action (search) and resource (arXiv articles). It distinguishes from siblings like download_article and get_details by focusing on search rather than retrieval or downloading.

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_details or load_article_to_context. It mentions 'flexible querying' but offers no explicit when/when-not instructions or comparisons to sibling tools, leaving usage context unclear.

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/lecigarevolant/arxiv-mcp-server-gpt'

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