Skip to main content
Glama
Sivan22

Sefaria Jewish Library MCP Server

search_texts

Search Jewish texts in Sefaria Library using custom queries, filters, and word proximity settings to retrieve specific results efficiently.

Instructions

search for jewish texts in the Sefaria library

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filtersNoFilters to apply to the text path in English (Examples: "Shulkhan Arukh", "maimonides", "talmud").[]
queryYesThe search query
sizeNoNumber of results to return.
slopNoThe maximum distance between each query word in the resulting document. 0 means an exact match must be found.

Implementation Reference

  • Core handler function that executes the search_texts tool by making a POST request to Sefaria's /api/search-wrapper endpoint, processing hits, extracting highlights and references, and formatting the results as a string.
    async def search_texts(query: str, slop: int =2, filters=None, size=10):
        """
        Search for texts in the Sefaria library.
        
        Args:
            query (str): The search query
            slop (int, optional): The maximum distance between each query word in the resulting document. 0 means an exact match must be found. defaults to 2
            filters (list, optional): Filters to apply to the text path in English (Examples: "Shulkhan Arukh", "maimonides", "talmud").
            size (int, optional): Number of results to return. defaults to 10.
            
        Returns:
            str: Formatted search results
        """
        # Use the www subdomain as specified in the documentation
        url = "https://www.sefaria.org/api/search-wrapper"
        
        # Build the request payload
        payload = {
            "query": query,
            "type": "text",
            "field":  "naive_lemmatizer",
            "size": size,
      "source_proj": True,
            "sort_fields": [
        "pagesheetrank"
      ],
      "sort_method": "score",
            "slop": slop,
         
        }
        if filters:
            payload["filters"] = filters
    
        
        # Make the POST request
        try:
            response = requests.post(url, json=payload)
            response.raise_for_status()
            
            logging.debug(f"Sefaria's Search API response: {response.text}")
            
            # Parse JSON response
            data = response.json()
            
            print(data)
            
            # Format the results
            results = []
            
            # Check if we have hits in the response
            if "hits" in data and "hits" in data["hits"]:
                # Get the actual total hits count
                total_hits = data["hits"].get("total", 0)
                # Handle different response formats
                if isinstance(total_hits, dict) and "value" in total_hits:
                    total_hits = total_hits["value"]
             
                # Process each hit
                for hit in data["hits"]["hits"]:
                    source = hit["_source"]
                    ref = source["ref"]
                    heRef = source["heRef"]
                    
                    # Get the content snippet
                    text_snippet = ""
                    
                    # Get highlighted text if available (this contains the search term highlighted)
                    if "highlight" in hit:
                        for field_name, highlights in hit["highlight"].items():
                            if highlights and len(highlights) > 0:
                                # Join multiple highlights with ellipses
                                text_snippet = " [...] ".join(highlights)
                                break
                    
                    # If no highlight, use content from the source
                    if not text_snippet:
                        # Try different fields that might contain content
                        for field_name in ["naive_lemmatizer", "exact"]:
                            if field_name in source and source[field_name]:
                                content = source[field_name]
                                if isinstance(content, str):
                                    # Limit to a reasonable snippet length
                                    text_snippet = content[:300] + ("..." if len(content) > 300 else "")
                                    break
                 
                    # Add the formatted result
                    results.append(f"Reference: {ref}\n Hebrew Reference: {heRef}\n Highlight: {text_snippet}\n")
            
            # Return a message if no results were found
            if len(results) <= 1:
                return f"No results found for '{query}'."
            logging.debug(f"formated results: {results}")
            return "\n".join(results)
        
        except json.JSONDecodeError as e:
            return f"Error: Failed to parse JSON response: {str(e)}"
        except requests.exceptions.RequestException as e:
            return f"Error during search API request: {str(e)}"
  • Tool registration in list_tools(), defining the name, description, and input JSON schema for the search_texts tool.
    types.Tool(
        name="search_texts",
        description="search for jewish texts in the Sefaria library",
        inputSchema={
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "The search query",
                },
                "slop":{
                    "type": "integer",
                    "description": "The maximum distance between each query word in the resulting document. 0 means an exact match must be found.",
                    "default": 2
                },
             
                "filters":{
                    "type": "list",
                    "description": 'Filters to apply to the text path in English (Examples: "Shulkhan Arukh", "maimonides", "talmud").',
                    "default" : "[]"
    
                },                        
                "size": {
                    "type": "integer",
                    "description": "Number of results to return.",
                    "default": 10
                }
            },
            "required": ["query"],
        },
    ),
  • MCP tool dispatcher logic in handle_call_tool() that validates input arguments, calls the core search_texts handler, and returns TextContent or error.
    elif name == "search_texts":
        try:
            query = arguments.get("query")
            if not query:
                raise ValueError("Missing query parameter")
                
            slop = arguments.get("slop")
            if not slop : # Use 'is None' to distinguish between explicitly provided null and missing key
                slop = 2
            filters = arguments.get("filters")
            if not filters:
                filters = None
            size = arguments.get("size")
            if not size:
                size = 10
            
            logger.debug(f"handle_search_texts: {query}")
            results = await search_texts(query, slop, filters, size)
            
            return [types.TextContent(
                type="text",
                text=results
            )]
        except Exception as err:
            logger.error(f"search texts error: {err}", exc_info=True)
            return [types.TextContent(
                type="text",
                text=f"Error: {str(err)}"
            )]
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 states the tool searches texts but doesn't explain key behaviors: whether it's read-only (implied but not confirmed), how results are returned (e.g., pagination, format), error handling, or performance aspects like rate limits. This leaves significant gaps for an agent to understand operational traits.

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 directly states the tool's purpose without unnecessary words. It's front-loaded with the core action ('search') and resource, making it easy to parse quickly. There's no redundancy or fluff, earning its place as a model of conciseness.

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?

Given the complexity of a search tool with 4 parameters, no annotations, and no output schema, the description is incomplete. It doesn't cover behavioral aspects (e.g., result format, pagination), usage guidelines relative to siblings, or output details. While the schema handles parameters well, the overall context for an agent to use this tool effectively is lacking.

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 100%, so the schema already documents all parameters (query, filters, size, slop) with clear descriptions. The tool description adds no additional parameter semantics beyond what's in the schema, such as explaining how 'filters' interact with 'query' or providing examples beyond the schema's examples. This meets the baseline for high 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 ('search') and resource ('jewish texts in the Sefaria library'), making the purpose immediately understandable. However, it doesn't explicitly differentiate this search tool from sibling tools like 'get_text' (which likely retrieves specific texts) or 'get_commentaries' (which might fetch commentary materials), leaving some ambiguity about when to choose one over another.

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 sibling tools like 'get_text' (for direct retrieval) or 'get_commentaries' (for commentary-specific queries), nor does it specify use cases like broad searches versus precise lookups. Without this context, users must infer usage from the tool 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

Related 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/Sivan22/mcp-sefaria-server'

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