Skip to main content
Glama
fegizii

Semantic Scholar MCP Server

by fegizii

search_snippets

Find specific text passages within academic papers using search queries to locate relevant research content.

Instructions

Search for text snippets across academic papers.

Args:
    query: Search query for text snippets
    limit: Maximum number of results (default: 10, max: 100)
    offset: Number of results to skip (default: 0)

Returns:
    Text snippets from papers

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
limitNo
offsetNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The core handler function for the 'search_snippets' MCP tool. The @mcp.tool() decorator registers the tool, defines its input schema from the type hints and docstring, and this function implements the logic: it calls the Semantic Scholar snippet/search API, formats the results, and returns a formatted string of snippets with paper titles and years.
    @mcp.tool()
    async def search_snippets(query: str, limit: int = 10, offset: int = 0) -> str:
        """
        Search for text snippets across academic papers.
    
        Args:
            query: Search query for text snippets
            limit: Maximum number of results (default: 10, max: 100)
            offset: Number of results to skip (default: 0)
    
        Returns:
            Text snippets from papers
        """
        params = {"query": query, "limit": min(limit, 100), "offset": offset}
    
        result = await make_api_request("snippet/search", params)
    
        if result is None:
            return "Error: Failed to fetch snippets"
    
        if "error" in result:
            return f"Error: {result['error']}"
    
        snippets = result.get("data", [])
        total = result.get("total", 0)
    
        if not snippets:
            return "No snippets found matching your query."
    
        formatted_snippets = []
        for i, snippet in enumerate(snippets, 1):
            paper = snippet.get("paper", {})
            title = paper.get("title", "Unknown Title")
            year = paper.get("year", "Unknown")
            text = snippet.get("text", "No text available")
    
            formatted_snippets.append(f"{i}. From: {title} ({year})\nSnippet: {text}")
    
        result_text = f"Found {total} total snippets (showing {len(snippets)}):\n\n"
        result_text += "\n\n".join(formatted_snippets)
    
        return result_text
  • Supporting helper function that makes HTTP requests to the Semantic Scholar API, handles errors like rate limits, and is called by search_snippets to fetch the snippet search results.
    async def make_api_request(
        endpoint: str, params: Optional[Dict[str, Any]] = None, method: str = "GET"
    ) -> Optional[Dict[str, Any]]:
        """Make a request to the Semantic Scholar API."""
        url = f"{BASE_URL}/{endpoint.lstrip('/')}"
    
        headers = {
            "Accept": "application/json",
            "User-Agent": f"semantic-scholar-mcp/{USER_AGENT_VERSION}",
        }
    
        if API_KEY:
            headers["x-api-key"] = API_KEY
    
        try:
            async with httpx.AsyncClient(timeout=API_TIMEOUT) as client:
                if method == "GET":
                    response = await client.get(url, headers=headers, params=params)
                elif method == "POST":
                    response = await client.post(url, headers=headers, json=params)
                else:
                    raise ValueError(f"Unsupported HTTP method: {method}")
    
                response.raise_for_status()
                return response.json()
    
        except httpx.HTTPStatusError as e:
            if e.response.status_code == 403:
                if not API_KEY:
                    return {
                        "error": "Rate limit exceeded. The shared public rate limit (1000 req/sec) may be exceeded. Get a free API key from https://www.semanticscholar.org/product/api for dedicated limits."
                    }
                else:
                    return {
                        "error": f"API key may be invalid or rate limit exceeded: {str(e)}"
                    }
            elif e.response.status_code == 429:
                return {
                    "error": "Rate limit exceeded. Please wait a moment and try again, or get an API key for dedicated higher limits."
                }
            else:
                return {"error": f"HTTP error: {str(e)}"}
        except httpx.HTTPError as e:
            return {"error": f"HTTP error: {str(e)}"}
        except Exception as e:
            return {"error": f"Request failed: {str(e)}"}
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions the tool 'returns text snippets from papers' but doesn't describe the search scope (full text? abstracts?), result format (snippet length, metadata included), performance characteristics, or any limitations. The description adds minimal behavioral context beyond the basic operation, leaving significant gaps for a search tool with no annotation coverage.

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 well-structured with clear sections (purpose, args, returns) and uses bullet-like formatting. Every sentence earns its place: the purpose statement is essential, parameter explanations are necessary given 0% schema coverage, and the return statement clarifies output. It could be slightly more concise by integrating defaults into the parameter descriptions more efficiently, but overall it's appropriately sized and front-loaded.

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 moderate complexity (search across academic papers), no annotations, and an output schema exists (though unspecified here), the description is minimally complete. It covers the basic operation and parameters but lacks important context: search scope, result format, limitations, and when to use versus siblings. The existence of an output schema means the description doesn't need to detail return values, but it should provide more behavioral context for effective use.

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 the description must compensate. It provides basic semantics for all three parameters: query is for 'search query for text snippets', limit specifies 'maximum number of results' with default/max values, and offset indicates 'number of results to skip' with default. However, it doesn't explain query syntax (exact matching? boolean operators?), what constitutes a 'result' (snippet length, paper context), or how offset interacts with pagination. The description adds value but doesn't fully compensate for the schema coverage gap.

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 as 'Search for text snippets across academic papers' with a specific verb ('search') and resource ('text snippets across academic papers'). It distinguishes itself from siblings like search_papers (which searches papers, not snippets) and get_citation_context (which retrieves specific citation contexts rather than searching across papers). However, it doesn't explicitly contrast with all siblings, keeping it at 4 rather than 5.

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. It doesn't mention when to prefer search_snippets over search_papers (for finding specific text passages versus paper metadata) or get_citation_context (for broader search versus focused citation retrieval). There's no discussion of prerequisites, limitations, or typical use cases beyond the basic purpose statement.

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/fegizii/SemanticScholarMCP'

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