Skip to main content
Glama
joelgombin

MCP Wikidata Server

by joelgombin

sparql_query

Execute SPARQL queries to retrieve structured data from Wikidata, supporting JSON, CSV, and XML formats with configurable result limits.

Instructions

Execute a SPARQL query against Wikidata

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSPARQL query
formatNoResponse formatjson
limitNoMaximum number of results (default: 100, max: 1000)

Implementation Reference

  • The main handler function that executes the SPARQL query logic: modifies query if no LIMIT, sends HTTP GET to Wikidata SPARQL endpoint, parses JSON or returns text, handles timeouts, rate limits, errors.
    async def sparql_query(
        self,
        query: str,
        format: str = "json",
        limit: int = 100
    ) -> Dict[str, Any]:
        if "LIMIT" not in query.upper():
            query += f" LIMIT {min(limit, 1000)}"
    
        params = {
            "query": query,
            "format": format
        }
    
        try:
            response = await self.session.get(
                self.config.sparql_endpoint,
                params=params,
                headers={
                    "Accept": f"application/sparql-results+{format}",
                    "User-Agent": self.config.user_agent
                }
            )
            response.raise_for_status()
    
            if format == "json":
                return response.json()
            else:
                return {"result": response.text}
                
        except asyncio.TimeoutError:
            raise Exception(f"SPARQL query timed out after {self.config.timeout} seconds. Try simplifying your query or increasing the timeout.")
        except httpx.TimeoutException:
            raise Exception(f"SPARQL query timed out after {self.config.timeout} seconds. Try simplifying your query or increasing the timeout.")
        except httpx.HTTPStatusError as e:
            if e.response.status_code == 500:
                raise Exception(f"SPARQL server error (500). Your query may have syntax errors or be too complex: {query[:100]}...")
            elif e.response.status_code == 429:
                raise Exception("SPARQL service is rate limiting requests. Please wait and try again.")
            else:
                raise Exception(f"SPARQL HTTP error {e.response.status_code}: {e.response.text[:200]}")
        except httpx.ConnectError:
            raise Exception(f"Cannot connect to SPARQL endpoint {self.config.sparql_endpoint}. Check your internet connection.")
        except Exception as e:
            if "timeout" in str(e).lower():
                raise Exception(f"SPARQL query timed out after {self.config.timeout} seconds. Try simplifying your query or increasing the timeout.")
            raise Exception(f"SPARQL query failed: {str(e)}")
  • Registers the sparql_query tool in MCP by defining its Tool object with name, description, and inputSchema in the WikidataTools.get_tool_definitions() method.
    Tool(
        name="sparql_query",
        description="Execute a SPARQL query against Wikidata",
        inputSchema={
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "SPARQL query"
                },
                "format": {
                    "type": "string",
                    "description": "Response format",
                    "enum": ["json", "csv", "xml"],
                    "default": "json"
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum number of results (default: 100, max: 1000)",
                    "default": 100,
                    "maximum": 1000
                }
            },
            "required": ["query"]
        }
    ),
  • Dispatches execution of sparql_query tool calls to the underlying WikidataClient instance.
    elif name == "sparql_query":
        result = await self.client.sparql_query(**arguments)
  • Defines the JSON schema for input parameters of the sparql_query tool: query (required string), optional format (json/csv/xml), optional limit (int).
    inputSchema={
        "type": "object",
        "properties": {
            "query": {
                "type": "string",
                "description": "SPARQL query"
            },
            "format": {
                "type": "string",
                "description": "Response format",
                "enum": ["json", "csv", "xml"],
                "default": "json"
            },
            "limit": {
                "type": "integer",
                "description": "Maximum number of results (default: 100, max: 1000)",
                "default": 100,
                "maximum": 1000
            }
        },
        "required": ["query"]
    }
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. While 'Execute a SPARQL query' implies a read operation, it doesn't clarify important aspects like rate limits, authentication requirements, timeout behavior, or whether this is a public endpoint. The description lacks behavioral context needed for safe and effective use.

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 extremely concise - a single sentence that directly states the tool's purpose without any wasted words. It's front-loaded with the essential information and earns its place efficiently.

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?

For a query execution tool with no annotations and no output schema, the description is insufficient. It doesn't explain what kind of results to expect, error handling, performance characteristics, or how this differs from sibling tools. The agent lacks critical context for effective tool selection and 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 100%, so the schema already documents all three parameters thoroughly. The description doesn't add any meaningful parameter semantics beyond what's in the schema - it doesn't explain SPARQL query syntax, format implications, or practical limit considerations.

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 ('Execute') and target ('SPARQL query against Wikidata'), making the purpose immediately understandable. However, it doesn't differentiate this from sibling tools like 'search_entities' or 'get_entity' which might also query Wikidata data, leaving some ambiguity about when to choose this specific tool.

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 like 'search_entities' or 'get_entity'. There's no mention of prerequisites, appropriate use cases, or limitations that would help an agent decide between this and sibling tools.

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/joelgombin/mcp-wikidata'

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