Skip to main content
Glama
joelgombin

MCP Wikidata Server

by joelgombin

get_relations

Retrieve incoming or outgoing relations for any Wikidata entity, with options to filter by property type and limit results for focused data exploration.

Instructions

Get relations of a Wikidata entity

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
entity_idYesWikidata entity ID
relation_typeNoType of relations to retrieveoutgoing
property_filterNoFilter by specific properties
limitNoMaximum number of relations

Implementation Reference

  • The main handler function that executes the get_relations tool logic. It constructs a SPARQL query based on relation_type (incoming or outgoing), executes it via sparql_query, processes the results into a structured list of relations, and returns them.
    async def get_relations(
        self,
        entity_id: str,
        relation_type: str = "outgoing",
        property_filter: Optional[List[str]] = None,
        limit: int = 20
    ) -> Dict[str, Any]:
        if relation_type == "outgoing":
            query = f"""
            SELECT ?property ?propertyLabel ?target ?targetLabel WHERE {{
              wd:{entity_id} ?property ?target .
              ?prop wikibase:directClaim ?property .
              SERVICE wikibase:label {{ bd:serviceParam wikibase:language "en" . }}
            }}
            LIMIT {limit}
            """
        elif relation_type == "incoming":
            query = f"""
            SELECT ?property ?propertyLabel ?source ?sourceLabel WHERE {{
              ?source ?property wd:{entity_id} .
              ?prop wikibase:directClaim ?property .
              SERVICE wikibase:label {{ bd:serviceParam wikibase:language "en" . }}
            }}
            LIMIT {limit}
            """
        else:
            raise ValueError(f"Invalid relation_type: {relation_type}")
    
        result = await self.sparql_query(query)
        
        relations = []
        for binding in result.get("results", {}).get("bindings", []):
            relation = {
                "property": binding.get("property", {}).get("value", "").split("/")[-1],
                "property_label": binding.get("propertyLabel", {}).get("value", ""),
                "direction": relation_type
            }
            
            if relation_type == "outgoing":
                relation["target"] = {
                    "id": binding.get("target", {}).get("value", "").split("/")[-1],
                    "label": binding.get("targetLabel", {}).get("value", "")
                }
            else:
                relation["source"] = {
                    "id": binding.get("source", {}).get("value", "").split("/")[-1],
                    "label": binding.get("sourceLabel", {}).get("value", "")
                }
            
            relations.append(relation)
    
        return {"relations": relations}
  • The tool schema definition including input validation (inputSchema) for get_relations, specifying parameters like entity_id, relation_type, property_filter, and limit.
    Tool(
        name="get_relations",
        description="Get relations of a Wikidata entity",
        inputSchema={
            "type": "object",
            "properties": {
                "entity_id": {
                    "type": "string",
                    "description": "Wikidata entity ID"
                },
                "relation_type": {
                    "type": "string",
                    "description": "Type of relations to retrieve",
                    "enum": ["incoming", "outgoing", "all"],
                    "default": "outgoing"
                },
                "property_filter": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Filter by specific properties"
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum number of relations",
                    "default": 20,
                    "maximum": 100
                }
            },
            "required": ["entity_id"]
        }
  • Registration in the call_tool dispatcher method, which routes the tool call to the WikidataClient's get_relations method.
    elif name == "get_relations":
        result = await self.client.get_relations(**arguments)
  • The get_tool_definitions method registers the get_relations tool by including it in the returned list of Tool objects, making it available to the MCP server.
        ]
    
    async def call_tool(self, name: str, arguments: Dict[str, Any]) -> List[TextContent]:
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states what the tool does but doesn't cover critical aspects like whether it's read-only, potential rate limits, error handling, or the format of returned relations. This is a significant gap for a tool with multiple parameters and no output schema.

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 appropriately sized and front-loaded, making it easy for an agent to parse quickly.

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 4 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain what 'relations' entail in Wikidata context, the structure of returned data, or any behavioral traits, leaving the agent with insufficient information for optimal tool selection and invocation.

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?

The input schema has 100% description coverage, providing clear details for all parameters including defaults and enums. The description adds no additional parameter semantics beyond what's in the schema, so it meets the baseline score of 3 without compensating or detracting.

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 ('Get relations') and target ('Wikidata entity'), making the purpose understandable. However, it doesn't differentiate from sibling tools like 'get_entity' or 'find_by_property', which might also retrieve entity-related information, so it doesn't reach the highest score.

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 is provided on when to use this tool versus alternatives such as 'get_entity' or 'sparql_query'. The description implies usage for retrieving relations but lacks explicit context or exclusions, leaving the agent to infer based on tool names 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

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