Skip to main content
Glama
Rudra-ravi

Wikipedia MCP Server

by Rudra-ravi

wikipedia_summarize_article_for_query

Read-onlyIdempotent

Retrieve a summary snippet from a Wikipedia article that is anchored to a specific query, with adjustable length for precision.

Instructions

Get a summary of a Wikipedia article tailored to a specific query.

The summary is a snippet around the query within the article text or summary. The max_length parameter controls the length of the snippet.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
titleYes
queryYes
max_lengthNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
titleYes
queryYes
summaryYes

Implementation Reference

  • The handler function that executes the summarize_article_for_query tool logic. Registers the tool, extracts title/query/max_length params, and calls wikipedia_client.summarize_for_query().
    @register_tool("summarize_article_for_query", model_output_schema(QuerySummaryResponse))
    def summarize_article_for_query(
        title: str,
        query: str,
        max_length: Annotated[int, Field(title="Max Length")] = 250,
    ):
        """
        Get a summary of a Wikipedia article tailored to a specific query.
    
        The summary is a snippet around the query within the article text or
        summary. The max_length parameter controls the length of the snippet.
        """
        logger.info("Tool: Getting query-focused summary for article: %s, query: %s", title, query)
        summary = wikipedia_client.summarize_for_query(title, query, max_length=max_length)
        return {"title": title, "query": query, "summary": summary}
  • The WikipediaClient.summarize_for_query() method — core helper logic that fetches the page text, finds the query in the text, and returns a snippet around it. Falls back to page summary if query not found.
    def summarize_for_query(self, title: str, query: str, max_length: int = 250) -> str:
        """
        Get a summary of a Wikipedia article tailored to a specific query.
    
        This is a simplified implementation that returns a snippet around the query.
    
        Args:
            title: The title of the Wikipedia article.
            query: The query to focus the summary on.
            max_length: The maximum length of the summary.
    
        Returns:
            A query-focused summary.
        """
        try:
            page = self.wiki.page(title)
            if not page.exists():
                return f"No Wikipedia article found for '{title}'."
    
            text_content = page.text
            query_lower = query.lower()
            text_lower = text_content.lower()
    
            start_index = text_lower.find(query_lower)
            if start_index == -1:
                # If query not found, return the beginning of the summary or article text
                summary_part = page.summary[:max_length]
                if not summary_part:
                    summary_part = text_content[:max_length]
                return summary_part + "..." if len(summary_part) >= max_length else summary_part
    
            # Try to get context around the query
            context_start = max(0, start_index - (max_length // 2))
            context_end = min(len(text_content), start_index + len(query) + (max_length // 2))
    
            snippet = text_content[context_start:context_end]
    
            if len(snippet) > max_length:
                snippet = snippet[:max_length]
    
            return snippet + "..." if len(snippet) >= max_length or context_end < len(text_content) else snippet
    
        except Exception as e:
            logger.error(f"Error generating query-focused summary for '{title}': {e}")
            return f"Error generating query-focused summary for '{title}': {str(e)}"
  • The QuerySummaryResponse Pydantic model defining the output schema for the tool (title, query, summary fields).
    class QuerySummaryResponse(MCPBaseModel):
        title: str
        query: str
        summary: str
  • The register_tool decorator function that registers the tool under both the short name and the prefixed 'wikipedia_' name.
    def register_tool(name: str, output_schema: dict[str, Any]):
        def decorator(func):
            server.tool(
                func,
                name=name,
                annotations=_READ_ONLY_TOOL_ANNOTATIONS,
                output_schema=output_schema,
            )
            server.tool(
                func,
                name=f"wikipedia_{name}",
                annotations=_READ_ONLY_TOOL_ANNOTATIONS,
                output_schema=output_schema,
            )
            return func
  • LRU cache wrapping applied to summarize_for_query method for performance.
    self.summarize_for_query = functools.lru_cache(maxsize=128)(  # type: ignore[method-assign]
        self.summarize_for_query
    )

Schema Changelog

Changes observed during successful MCP inspections.

  1. Addedv2.0.1

TDQS

A4.4/5.0
Behavior4/5

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

Annotations already declare read-only and idempotent behavior. The description adds useful context: the output is a snippet around the query, and max_length controls snippet length. No contradictions with annotations.

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?

Two short sentences front-load the purpose and add one functional detail. Every sentence earns its place with no redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a read-only tool with output schema and good annotations, the description covers purpose, snippet mechanics, and the length control. It doesn't address edge cases like missing articles, but that is not critical given the annotations.

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?

With 0% schema description coverage, the description compensates by explaining max_length explicitly and clarifying that title identifies the article and query determines the snippet location. This goes beyond the raw schema.

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's function: 'Get a summary of a Wikipedia article tailored to a specific query.' This specifies a concrete verb, resource, and distinguishes it from siblings like get_summary by emphasizing query-tailored output.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies when to use the tool: when a query-specific summary or snippet is needed. It explains the snippet behavior but does not explicitly name alternatives or exclusions, so it falls short of a 5.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.