Skip to main content
Glama
emi-dm

ArxivSearcher MCP Server

by emi-dm

export_search_results

Convert arXiv paper search results into structured formats like BibTeX, CSV, JSON, or Markdown for easy organization and citation management.

Instructions

Export search results to various formats.

:param results: Results from search_papers or other search functions :param format: Export format ('bibtex', 'csv', 'json', 'markdown') :param filename: Output filename (without extension) :param save_path: Directory to save the file (default: current directory)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultsYes
formatNobibtex
filenameNo
save_pathNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Handler function for the 'export_search_results' tool. Exports arXiv search results to formats like bibtex, CSV, JSON, or Markdown, saving to a file and returning metadata.
    @mcp.tool
    def export_search_results(
        results: Dict[str, Any],
        format: str = "bibtex",
        filename: str | None = None,
        save_path: str | None = None,
    ) -> dict:
        """
        Export search results to various formats.
    
        :param results: Results from search_papers or other search functions
        :param format: Export format ('bibtex', 'csv', 'json', 'markdown')
        :param filename: Output filename (without extension)
        :param save_path: Directory to save the file (default: current directory)
        """
        try:
            if save_path is None:
                save_path = os.getcwd()
    
            os.makedirs(save_path, exist_ok=True)
    
            # Extract papers from results
            if isinstance(results, dict) and "results" in results:
                papers = results["results"]
            elif isinstance(results, list):
                papers = results
            else:
                return {
                    "error": "Invalid results format. Expected a list of papers or a dict with a 'results' key."
                }
    
            if not papers:
                return {"error": "No papers to export."}
    
            # Generate default filename if not provided
            if filename is None:
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                filename = f"arxiv_search_{timestamp}"
    
            full_path = os.path.join(save_path, f"{filename}.{format}")
    
            if format == "bibtex":
                bibtex_entries = []
                query_info = results.get("query_used", "N/A")
                export_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
                header = f"""% Query: {query_info}
    % Exported: {export_time}
    """
                bibtex_entries.append(header)
    
                bibtex_keys = set()
                for i, paper in enumerate(papers):
                    authors = paper.get("authors", ["unknown"])
                    year = paper.get("published_date", "unknown").split("-")[0]
    
                    first_author_lastname = "unknown"
                    if authors and isinstance(authors, list) and authors[0] != "unknown":
                        name_parts = authors[0].split(" ")
                        if name_parts:
                            first_author_lastname = name_parts[-1]
    
                    first_author_lastname = re.sub(
                        r"[^a-zA-Z0-9]", "", first_author_lastname
                    ).lower()
    
                    key = f"{first_author_lastname}{year}"
    
                    # Handle duplicates
                    original_key = key
                    suffix = 1
                    while key in bibtex_keys:
                        key = f"{original_key}_{suffix}"
                        suffix += 1
                    bibtex_keys.add(key)
    
                    title = paper.get("title", "No Title Provided")
                    author_str = " and ".join(paper.get("authors", []))
                    pdf_url = paper.get("pdf_url", "")
    
                    arxiv_id_match = (
                        re.search(r"/pdf/([^v]+)", pdf_url) if pdf_url else None
                    )
                    if arxiv_id_match:
                        arxiv_id = arxiv_id_match.group(1)
                        journal = f"arXiv preprint arXiv:{arxiv_id}"
                    else:
                        journal = f"arXiv preprint arXiv:{key}"
    
                    entry = f"""@article{{{key},
        title = {{{title}}},
        author = {{{author_str}}},
        year = {{{year}}},
        journal = {{{journal}}},
        url = {{{pdf_url}}}
    }}"""
                    bibtex_entries.append(entry)
    
                content = "\n\n".join(bibtex_entries)
                with open(full_path, "w", encoding="utf-8") as f:
                    f.write(content)
    
            elif format == "csv":
                df = pd.DataFrame(papers)
                df.to_csv(full_path, index=False, encoding="utf-8-sig")
                content = df.to_string()
    
            elif format == "json":
                with open(full_path, "w", encoding="utf-8") as f:
                    json.dump(papers, f, indent=4)
                content = json.dumps(papers, indent=4)
    
            elif format == "markdown":
                md_entries = []
                for paper in papers:
                    title = paper.get("title", "N/A")
                    authors = ", ".join(paper.get("authors", ["N/A"]))
                    date = paper.get("published_date", "N/A")
                    url = paper.get("pdf_url", "#")
                    summary = paper.get("summary", "N/A").replace("\n", " ")
    
                    md_entries.append(
                        f"""### {title}\n**Authors:** {authors}\n**Published:** {date}\n**[PDF Link]({url})**\n> {summary}\n"""
                    )
    
                content = "\n---\n".join(md_entries)
                with open(full_path, "w", encoding="utf-8") as f:
                    f.write(content)
    
            else:
                return {"error": f"Unsupported format: {format}"}
    
            return {
                "success": True,
                "format": format,
                "saved_path": full_path,
                "papers_exported": len(papers),
                "content_preview": content[:500] + ("..." if len(content) > 500 else ""),
            }
    
        except Exception as e:
            return {"success": False, "error": f"Failed to export results: {str(e)}"}
  • Async handler function for the 'export_search_results' tool in the remote version. Identical logic to export results to various formats.
    @mcp.tool
    async def export_search_results(
        results: Dict[str, Any],
        format: str = "bibtex",
        filename: str | None = None,
        save_path: str | None = None,
    ) -> dict:
        """
        Export search results to various formats.
    
        :param results: Results from search_papers or other search functions
        :param format: Export format ('bibtex', 'csv', 'json', 'markdown')
        :param filename: Output filename (without extension)
        :param save_path: Directory to save the file (default: current directory)
        """
        try:
            if save_path is None:
                save_path = os.getcwd()
    
            os.makedirs(save_path, exist_ok=True)
    
            # Extract papers from results
            if isinstance(results, dict) and "results" in results:
                papers = results["results"]
            elif isinstance(results, list):
                papers = results
            else:
                return {
                    "error": "Invalid results format. Expected a list of papers or a dict with a 'results' key."
                }
    
            if not papers:
                return {"error": "No papers to export."}
    
            # Generate default filename if not provided
            if filename is None:
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                filename = f"arxiv_search_{timestamp}"
    
            full_path = os.path.join(save_path, f"{filename}.{format}")
    
            if format == "bibtex":
                bibtex_entries = []
                query_info = results.get("query_used", "N/A")
                export_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
                header = f"""% Query: {query_info}
    % Exported: {export_time}
    """
                bibtex_entries.append(header)
    
                bibtex_keys = set()
                for i, paper in enumerate(papers):
                    authors = paper.get("authors", ["unknown"])
                    year = paper.get("published_date", "unknown").split("-")[0]
    
                    first_author_lastname = "unknown"
                    if authors and isinstance(authors, list) and authors[0] != "unknown":
                        name_parts = authors[0].split(" ")
                        if name_parts:
                            first_author_lastname = name_parts[-1]
    
                    first_author_lastname = re.sub(
                        r"[^a-zA-Z0-9]", "", first_author_lastname
                    ).lower()
    
                    key = f"{first_author_lastname}{year}"
    
                    # Handle duplicates
                    original_key = key
                    suffix = 1
                    while key in bibtex_keys:
                        key = f"{original_key}_{suffix}"
                        suffix += 1
                    bibtex_keys.add(key)
    
                    title = paper.get("title", "No Title Provided")
                    author_str = " and ".join(paper.get("authors", []))
                    pdf_url = paper.get("pdf_url", "")
    
                    arxiv_id_match = (
                        re.search(r"/pdf/([^v]+)", pdf_url) if pdf_url else None
                    )
                    if arxiv_id_match:
                        arxiv_id = arxiv_id_match.group(1)
                        journal = f"arXiv preprint arXiv:{arxiv_id}"
                    else:
                        journal = f"arXiv preprint arXiv:{key}"
    
                    entry = f"""@article{{{key},
        title = {{{title}}},
        author = {{{author_str}}},
        year = {{{year}}},
        journal = {{{journal}}},
        url = {{{pdf_url}}}
    }}"""
                    bibtex_entries.append(entry)
    
                content = "\n\n".join(bibtex_entries)
                with open(full_path, "w", encoding="utf-8") as f:
                    f.write(content)
    
            elif format == "csv":
                df = pd.DataFrame(papers)
                df.to_csv(full_path, index=False, encoding="utf-8-sig")
                content = df.to_string()
    
            elif format == "json":
                with open(full_path, "w", encoding="utf-8") as f:
                    json.dump(papers, f, indent=4)
                content = json.dumps(papers, indent=4)
    
            elif format == "markdown":
                md_entries = []
                for paper in papers:
                    title = paper.get("title", "N/A")
                    authors = ", ".join(paper.get("authors", ["N/A"]))
                    date = paper.get("published_date", "N/A")
                    url = paper.get("pdf_url", "#")
                    summary = paper.get("summary", "N/A").replace("\n", " ")
    
                    md_entries.append(
                        f"""### {title}\n**Authors:** {authors}\n**Published:** {date}\n**[PDF Link]({url})**\n> {summary}\n"""
                    )
    
                content = "\n---\n".join(md_entries)
                with open(full_path, "w", encoding="utf-8") as f:
                    f.write(content)
    
            else:
                return {"error": f"Unsupported format: {format}"}
    
            return {
                "success": True,
                "format": format,
                "saved_path": full_path,
                "papers_exported": len(papers),
                "content_preview": content[:500] + ("..." if len(content) > 500 else ""),
            }
    
        except Exception as e:
            return {"success": False, "error": f"Failed to export results: {str(e)}"}
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It describes the tool as an exporter with format options and save locations, but lacks details on permissions, rate limits, error handling, or what happens during export (e.g., file creation, overwriting). For a tool with no annotations and potential side effects (file system writes), this is inadequate.

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 with the main purpose. The parameter explanations are concise and directly relevant. However, the colon-prefixed format for parameters is slightly unconventional and could be more integrated, but it doesn't waste space. Every sentence earns its place.

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 the tool's complexity (4 parameters, nested objects, no annotations, but has an output schema), the description is moderately complete. It covers input semantics well but lacks behavioral context and usage guidelines. The output schema exists, so return values needn't be explained, but overall completeness is adequate with clear gaps.

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 adds significant meaning beyond the schema by explaining each parameter's purpose: 'results' as search results, 'format' with specific options, 'filename' as output name, and 'save_path' as directory. This clarifies semantics well, though it doesn't cover all nuances like default behaviors or constraints.

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's purpose: 'Export search results to various formats.' It specifies the verb ('export') and resource ('search results'), but doesn't explicitly differentiate from sibling tools like 'download_paper' or 'analyze_paper_trends', which might have overlapping functionality. The purpose is clear but lacks sibling differentiation.

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 minimal usage guidance. It mentions that 'results' should come from 'search_papers or other search functions,' which gives some context, but doesn't specify when to use this tool versus alternatives like 'download_paper' or how it relates to other export or analysis tools. No explicit when/when-not scenarios or alternatives are provided.

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/emi-dm/Arxiv-MCP'

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