Skip to main content
Glama

Search Questions

search_questions
Read-onlyIdempotent

Search past-paper questions with optional filters for subject, paper, year, session, and chapter. Returns ranked results with compact metadata including marks, relevance score, and links to full question details.

Instructions

Search past-paper questions with optional filters.

Returns ranked questions with compact metadata. Each result includes:

  • Paper identification (paper, year, session, variant, paper_label)

  • Question number, marks, relevance score

  • Whether it's image-based (if so, question_image_url and ms_image_url are provided)

  • topic_signal: exam frequency and importance summary

  • question_url: link to full question page

NEXT STEP: Call get_questions(question_ids_list=[...]) with the recommended_ids to get full question text, mark scheme key points, and images.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
subjectNo
paperNo
yearNo
sessionNo
chapterNo
modeNohybrid
limitNo
offsetNo
expandNo

Implementation Reference

  • mcp_server.py:512-516 (registration)
    Tool registration for search_questions using the @mcp.tool decorator with title 'Search Questions', tags {'search', 'core'}, and readOnly/idempotent annotations.
    @mcp.tool(
        title="Search Questions",
        tags={"search", "core"},
        annotations={"readOnlyHint": True, "idempotentHint": True},
    )
  • Schema/type signature for search_questions defining its parameters: query (required), subject, paper, year, session, chapter, mode (default hybrid), limit (default 20), offset (default 0), expand (default True). Returns ToolResult.
    def search_questions(
        query: str,
        subject: Optional[str] = DEFAULT_SUBJECT,
        paper: Optional[int] = None,
        year: Optional[int] = None,
        session: Optional[str] = None,
        chapter: Optional[int] = None,
        mode: str = "hybrid",
        limit: int = 20,
        offset: int = 0,
        expand: bool = True,
    ) -> ToolResult:
  • Full handler implementation of search_questions. Validates mode, applies spell correction, calls the /search API endpoint with filters (subject, paper, year, session, chapter), processes results into card items with metadata, and returns a ToolResult containing both a human-readable summary and structured_content payload with recommended_ids for follow-up get_questions calls.
    def search_questions(
        query: str,
        subject: Optional[str] = DEFAULT_SUBJECT,
        paper: Optional[int] = None,
        year: Optional[int] = None,
        session: Optional[str] = None,
        chapter: Optional[int] = None,
        mode: str = "hybrid",
        limit: int = 20,
        offset: int = 0,
        expand: bool = True,
    ) -> ToolResult:
        """Search past-paper questions with optional filters.
    
        Returns ranked questions with compact metadata. Each result includes:
        - Paper identification (paper, year, session, variant, paper_label)
        - Question number, marks, relevance score
        - Whether it's image-based (if so, question_image_url and ms_image_url are provided)
        - topic_signal: exam frequency and importance summary
        - question_url: link to full question page
    
        NEXT STEP: Call get_questions(question_ids_list=[...]) with the recommended_ids
        to get full question text, mark scheme key points, and images.
        """
        if not _validate_mode(mode):
            raise ToolError(
                "INVALID_MODE: mode must be one of 'hybrid', 'keyword', or 'semantic'."
            )
    
        capped_limit = max(1, min(limit, MAX_SEARCH_LIMIT))
        safe_offset = max(0, offset)
        normalized_session = _normalize_session_filter(session)
    
        original_query = query
        effective_query, was_corrected = _spell_correct(query)
    
        params: dict[str, Any] = {
            "q": effective_query,
            "mode": mode,
            "limit": capped_limit,
            "offset": safe_offset,
            "expand": expand,
            "has_answer": True,
        }
        if subject:
            params["subject"] = subject
        if paper is not None:
            params["paper"] = paper
        if year is not None:
            params["year"] = year
        if normalized_session:
            params["session"] = normalized_session
        if chapter is not None:
            params["chapter"] = chapter
    
        try:
            data = _api_get("/search", params)
        except Exception as exc:
            logger.error("search_questions failed: %s", exc, exc_info=True)
            error_payload = _error_from_exception(exc, "/search")
            message = error_payload.get("error", {}).get("message", "Search failed.")
            raise ToolError(message)
    
        raw_results = data.get("results", []) if isinstance(data, dict) else []
        if not isinstance(raw_results, list):
            raw_results = []
    
        visible_results = raw_results[:capped_limit]
        cards = [_result_item(r, i + 1) for i, r in enumerate(visible_results) if isinstance(r, dict)]
        all_result_ids = [r["id"] for r in cards if isinstance(r.get("id"), int)]
        recommended_ids = all_result_ids[: min(len(all_result_ids), MAX_RECOMMENDED_IDS)]
    
        payload = {
            "ok": True,
            "query": original_query,
            "effective_query": effective_query,
            "was_corrected": was_corrected,
            "filters": {
                "subject": subject,
                "paper": paper,
                "year": year,
                "session": normalized_session,
                "chapter": chapter,
                "mode": mode,
                "expand": expand,
                "limit": capped_limit,
                "offset": safe_offset,
            },
            "meta": {
                "total": data.get("total", len(raw_results)) if isinstance(data, dict) else len(raw_results),
                "returned": len(cards),
                "query_time_ms": data.get("query_time_ms") if isinstance(data, dict) else None,
            },
            "results": cards,
            "recommended_ids": recommended_ids,
            "next_step": {
                "tool": "get_questions",
                "question_ids_list": recommended_ids[:15],
                "example": "get_questions(question_ids_list=[1615,1684])",
            },
        }
    
        query_note = None
        if was_corrected and effective_query != original_query:
            query_note = f"Query corrected from '{original_query}' to '{effective_query}'."
    
        summary_text = _build_search_summary(
            title=f"Search results for '{original_query}'",
            query_note=query_note,
            total=payload["meta"]["total"],
            returned=payload["meta"]["returned"],
            cards=cards,
            recommended_ids=recommended_ids[:15],
        )
    
        return ToolResult(content=summary_text, structured_content=payload)
  • Helper function used by search_questions to spell-correct the query before sending to the /search API endpoint.
    def _spell_correct(query: str) -> tuple[str, bool]:
        try:
            data = _api_get("/spellcheck", {"q": query})
            if isinstance(data, dict) and data.get("was_corrected") and data.get("corrected"):
                return str(data["corrected"]), True
        except Exception as exc:
            logger.debug("Spellcheck unavailable, continuing without correction: %s", exc)
        return query, False
  • Helper function that transforms a raw API result row into a structured card item with paper identification, question metadata, image URLs, topic signal, and variant info. Called by search_questions to build each result entry.
    def _result_item(raw: dict[str, Any], index: int, matched_topics: Optional[list[str]] = None) -> dict[str, Any]:
        paper = raw.get("paper") or {}
        session_short = _short_session(paper.get("session_name"))
        paper_number = paper.get("paper_number")
        year = paper.get("year")
        variant = paper.get("variant")
    
        paper_label_parts: list[str] = []
        if paper_number is not None:
            paper_label_parts.append(f"P{paper_number}")
        if session_short and year is not None:
            paper_label_parts.append(f"{session_short}{year}")
        elif year is not None:
            paper_label_parts.append(str(year))
        if variant is not None:
            paper_label_parts.append(f"v{variant}")
    
        is_image_based = bool(raw.get("is_image_based"))
    
        item: dict[str, Any] = {
            "rank": index,
            "id": raw.get("id"),
            "paper": paper_number,
            "year": year,
            "session": session_short,
            "variant": variant,
            "paper_label": " ".join(paper_label_parts),
            "question_number": raw.get("question_number"),
            "marks": raw.get("marks"),
            "relevance_score": raw.get("relevance_score"),
            "snippet": _clean_text(raw.get("question_text"), max_len=200),
            "is_image_based": is_image_based,
            "question_url": f"{QUESTION_URL_BASE}/{raw.get('id')}" if raw.get("id") else None,
        }
    
        # Include image URLs for image-based questions
        if is_image_based:
            item["question_image_url"] = _to_image_url(raw.get("image_path"))
            item["ms_image_url"] = _to_image_url(raw.get("ms_image_path"))
    
        # Curated topic intelligence: just the one-line signal
        ti = raw.get("topic_intelligence")
        if isinstance(ti, dict) and ti.get("signal"):
            item["topic_signal"] = ti["signal"]
    
        # Variant info: count + IDs only, not full copies
        variants = raw.get("duplicate_variants", [])
        if isinstance(variants, list) and len(variants) > 0:
            item["variants_count"] = raw.get("duplicate_group_size", 1)
            item["variant_ids"] = [v.get("id") for v in variants if isinstance(v, dict) and v.get("id")]
    
        if matched_topics:
            item["matched_topics"] = matched_topics
        return item
Behavior4/5

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

Annotations already indicate readOnly and idempotent. Description adds value by detailing output structure (ranked results, compact metadata, image URLs, topic_signal).

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?

Very concise; front-loads purpose, uses bullet points for output details, and callout for next step. Every sentence adds value.

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?

Output is well described, but input parameters are nearly undocumented. Given 10 params with 0% schema coverage, the description is incomplete for correct invocation.

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

Parameters2/5

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

Schema coverage is 0%, but description only mentions 'optional filters' without explaining any of the 10 parameters (query, subject, paper, etc.). Leaves agent guessing.

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 it searches past-paper questions with filters, but does not explicitly differentiate from siblings like search_multi or search_examiner_reports.

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?

No guidance on when to use this tool versus alternatives; no context on prerequisites or exclusions. Only a next-step suggestion to call get_questions.

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/Pixel2075/searchcaie-mcp'

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