concept_lookup
Query ConceptNet's knowledge graph to retrieve all relationships and properties for a specific concept. Explore semantic information, related concepts, and cross-language data with customizable output formats.
Instructions
Look up information about a specific concept in ConceptNet.
This tool queries ConceptNet's knowledge graph to find all relationships
and properties associated with a given concept. By default, it returns
ALL results (not limited to 20) to provide complete information.
Features:
- Complete relationship discovery for any concept
- Language filtering and cross-language exploration
- Summaries and statistics
- Performance optimized with automatic pagination
- Format control: minimal (~96% smaller) vs verbose (full metadata)
Format Options:
- verbose=false (default): Returns minimal format optimized for LLM consumption
- verbose=true: Returns comprehensive format with full ConceptNet metadata
- Backward compatibility maintained with existing tools
Use this when you need to:
- Understand what ConceptNet knows about a concept
- Explore all relationships for a term
- Get semantic information
- Find related concepts and properties
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| language | No | en | |
| limit_results | No | ||
| target_language | No | ||
| term | Yes | ||
| verbose | No |
Implementation Reference
- Core handler function implementing the concept_lookup tool. Handles parameter validation, ConceptNet API queries via ConceptNetClient, response processing with ResponseProcessor, format selection (minimal/verbose), and comprehensive error handling with structured responses.async def concept_lookup( term: str, ctx: Context, language: str = "en", limit_results: bool = False, target_language: Optional[str] = None, verbose: bool = False ) -> Dict[str, Any]: """ Look up all edges for a specific concept in ConceptNet. This tool queries ConceptNet's knowledge graph to find all relationships and properties associated with a given concept. By default, it returns a minimal format optimized for LLM consumption. Args: term: The concept term to look up (e.g., "dog", "artificial intelligence") language: Language code for the concept (default: "en" for English) limit_results: If True, limits to first 20 results for quick queries (default: False) target_language: If specified, filters results to edges involving this language verbose: If True, returns detailed format with full metadata (default: False) Returns: Concept data with relationships grouped by type (minimal format) or comprehensive data with full metadata (verbose format). Examples: - concept_lookup("dog") -> Minimal format with grouped relationships - concept_lookup("dog", verbose=True) -> Full detailed format with metadata - concept_lookup("perro", "es") -> Spanish concept relationships in minimal format """ start_time = datetime.now(timezone.utc) try: # Log the incoming request await ctx.info(f"Looking up concept: '{term}' (language: {language})") # 1. Parameter validation await _validate_parameters(term, language, target_language, ctx) # 2. Normalize the input term normalized_term = normalize_concept_text(term, language) if normalized_term != term: await ctx.debug(f"Normalized term: '{term}' -> '{normalized_term}'") # 3. Query ConceptNet API await ctx.info(f"Querying ConceptNet API for concept '{normalized_term}'...") async with ConceptNetClient() as client: try: response = await client.get_concept( term=normalized_term, language=language, get_all_pages=not limit_results, target_language=target_language ) except ConceptNotFoundError: return _create_not_found_response(term, language, normalized_term) except ConceptNetAPIError as e: return _create_api_error_response(term, language, str(e)) # 4. Apply default language filtering if target_language not specified effective_target_language = target_language if target_language is not None else language # 5. Process and normalize the response processor = ResponseProcessor(default_language=language) processed_response = processor.process_concept_response( response, target_language=effective_target_language ) # 6. Return appropriate format based on verbose parameter if verbose: # Return detailed format with full metadata (existing behavior) enhanced_response = await _create_enhanced_response( processed_response, term, normalized_term, language, effective_target_language, limit_results, start_time, ctx ) total_edges = enhanced_response.get("summary", {}).get("total_edges", 0) await ctx.info(f"Successfully retrieved {total_edges} edges for concept '{term}' (verbose format)") return enhanced_response else: # Return minimal format optimized for LLMs minimal_response = processor.create_minimal_concept_response( processed_response, term ) total_relationships = minimal_response.get("summary", {}).get("total_relationships", 0) await ctx.info(f"Successfully retrieved {total_relationships} relationships for concept '{term}' (minimal format)") return minimal_response except MCPValidationError as e: # Handle validation errors specifically return { "error": "validation_error", "message": f"Validation error for field '{e.field}': {e.value} (expected: {e.expected})", "field": e.field, "value": e.value, "expected": e.expected, "term": term, "language": language, "query_time": start_time.isoformat() + "Z" } except ConceptNotFoundError: return _create_not_found_response(term, language, term) except ConceptNetAPIError as e: return _create_api_error_response(term, language, str(e)) except Exception as e: logger.error(f"Unexpected error in concept_lookup: {e}") return { "error": "unexpected_error", "message": f"An unexpected error occurred: {str(e)}", "term": term, "language": language, "query_time": start_time.isoformat() + "Z" }
- src/conceptnet_mcp/server.py:131-192 (registration)MCP tool registration using FastMCP @mcp.tool decorator. Wraps the core concept_lookup handler with error handling and registers it with name, description, and tags.@mcp.tool( name="concept_lookup", description=""" Look up information about a specific concept in ConceptNet. This tool queries ConceptNet's knowledge graph to find all relationships and properties associated with a given concept. By default, it returns ALL results (not limited to 20) to provide complete information. Features: - Complete relationship discovery for any concept - Language filtering and cross-language exploration - Summaries and statistics - Performance optimized with automatic pagination - Format control: minimal (~96% smaller) vs verbose (full metadata) Format Options: - verbose=false (default): Returns minimal format optimized for LLM consumption - verbose=true: Returns comprehensive format with full ConceptNet metadata - Backward compatibility maintained with existing tools Use this when you need to: - Understand what ConceptNet knows about a concept - Explore all relationships for a term - Get semantic information - Find related concepts and properties """, tags={"conceptnet", "knowledge", "lookup"} ) async def concept_lookup_tool( term: str, ctx: Context, language: str = "en", limit_results: bool = False, target_language: Optional[str] = None, verbose: bool = False ) -> Dict[str, Any]: """ MCP tool wrapper for concept lookup functionality. Args: term: The concept term to look up (e.g., "dog", "artificial intelligence") language: Language code for the concept (default: "en" for English) limit_results: If True, limits to first 20 results for quick queries (default: False) target_language: If specified, filters results to edges involving this language verbose: If True, returns detailed format with full metadata (default: False) Returns: Concept relationships grouped by type (minimal format) or comprehensive data with full metadata (verbose format) """ try: return await concept_lookup( term=term, ctx=ctx, language=language, limit_results=limit_results, target_language=target_language, verbose=verbose ) except Exception as e: return await handle_server_error(e, "concept_lookup")
- Pydantic schema/model for concept_lookup query parameters, providing input validation, type hints, and serialization utilities like to_concept_uri().class ConceptLookupQuery(BaseModel): """ Query model for looking up a specific concept. This model defines parameters for retrieving information about a specific concept from the ConceptNet API. """ term: str = Field( description="The concept term to look up" ) language: str = Field( default="en", description="Language code for the concept (e.g., 'en', 'es', 'fr')" ) limit_results: bool = Field( default=False, description="Whether to limit results to first page (20 items)" ) target_language: Optional[str] = Field( default=None, description="Filter results to specific language" ) @field_validator('language', 'target_language') @classmethod def validate_language_codes(cls, v: Optional[str]) -> Optional[str]: """Validate language codes are reasonable.""" if v is not None and (len(v) < 2 or len(v) > 3 or not v.isalpha()): raise ValueError("Language code must be 2-3 alphabetic characters") return v.lower() if v else v def to_concept_uri(self) -> str: """Convert term and language to ConceptNet URI format.""" # Replace spaces with underscores and construct URI normalized_term = self.term.replace(' ', '_').lower() return f"/c/{self.language}/{normalized_term}" def __str__(self) -> str: """Return a human-readable string representation.""" return f"ConceptLookup('{self.term}' in {self.language})"
- cloudflare-workers/src/main.py:266-288 (handler)Simplified handler for concept_lookup in Cloudflare Workers deployment. Directly constructs ConceptNet API endpoint and fetches data using custom CloudflareHTTPClient.async def _concept_lookup(self, term: str, language: str = "en", limit_results: bool = False, target_language: Optional[str] = None, verbose: bool = False) -> Dict[str, Any]: """Implement concept lookup tool.""" endpoint = f"/c/{language}/{normalize_concept_text(term, language)}" params = {} if target_language: params['filter'] = f'/c/{target_language}/' if limit_results: params['limit'] = '20' response_data = await self.http_client.request("GET", endpoint, params=params) # Add Workers-specific metadata response_data['deployment'] = { 'platform': 'cloudflare-workers-python', 'transport': 'dual-http-sse', 'edge_location': 'global' } return response_data
- cloudflare-workers/src/main.py:138-152 (registration)Tool registration in Cloudflare Workers MCPProtocol._register_tools() dictionary, including inputSchema for validation."concept_lookup": { "name": "concept_lookup", "description": "Look up information about a specific concept in ConceptNet. Returns minimal format (~96% smaller) by default or verbose format with full metadata when verbose=true.", "inputSchema": { "type": "object", "properties": { "term": {"type": "string", "description": "The concept term to look up"}, "language": {"type": "string", "default": "en", "description": "Language code"}, "limit_results": {"type": "boolean", "default": False, "description": "Limit to first page of results"}, "target_language": {"type": "string", "description": "Filter to specific target language"}, "verbose": {"type": "boolean", "default": False, "description": "Return detailed format with full metadata (default: false for minimal format)"} }, "required": ["term"] } },