Skip to main content
Glama
vparlapalli490

ServiceNow MCP Server

list_categories

Retrieve and filter knowledge base categories in ServiceNow to organize and navigate content effectively.

Instructions

List categories in a knowledge base

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
knowledge_baseNoFilter by knowledge base ID
parent_categoryNoFilter by parent category ID
limitNoMaximum number of categories to return
offsetNoOffset for pagination
activeNoFilter by active status
queryNoSearch query for categories

Implementation Reference

  • Core handler function that implements the logic for listing categories from ServiceNow's kb_category table, including query building, API call, response parsing, and transformation into structured output.
    def list_categories(
        config: ServerConfig,
        auth_manager: AuthManager,
        params: ListCategoriesParams,
    ) -> Dict[str, Any]:
        """
        List categories in a knowledge base.
    
        Args:
            config: Server configuration.
            auth_manager: Authentication manager.
            params: Parameters for listing categories.
    
        Returns:
            Dictionary with list of categories and metadata.
        """
        api_url = f"{config.api_url}/table/kb_category"
    
        # Build query parameters
        query_params = {
            "sysparm_limit": params.limit,
            "sysparm_offset": params.offset,
            "sysparm_display_value": "all",
        }
    
        # Build query string
        query_parts = []
        if params.knowledge_base:
            # Try different query format to ensure we match by sys_id value
            query_parts.append(f"kb_knowledge_base.sys_id={params.knowledge_base}")
        if params.parent_category:
            query_parts.append(f"parent.sys_id={params.parent_category}")
        if params.active is not None:
            query_parts.append(f"active={str(params.active).lower()}")
        if params.query:
            query_parts.append(f"labelLIKE{params.query}^ORdescriptionLIKE{params.query}")
    
        if query_parts:
            query_string = "^".join(query_parts)
            logger.debug(f"Constructed query string: {query_string}")
            query_params["sysparm_query"] = query_string
        
        # Log the query parameters for debugging
        logger.debug(f"Listing categories with query params: {query_params}")
    
        # Make request
        try:
            response = requests.get(
                api_url,
                params=query_params,
                headers=auth_manager.get_headers(),
                timeout=config.timeout,
            )
            response.raise_for_status()
    
            # Get the JSON response
            json_response = response.json()
            
            # Safely extract the result
            if isinstance(json_response, dict) and "result" in json_response:
                result = json_response.get("result", [])
            else:
                logger.error("Unexpected response format: %s", json_response)
                return {
                    "success": False,
                    "message": "Unexpected response format",
                    "categories": [],
                    "count": 0,
                    "limit": params.limit,
                    "offset": params.offset,
                }
    
            # Transform the results
            categories = []
            
            # Handle either string or list
            if isinstance(result, list):
                for category_item in result:
                    if not isinstance(category_item, dict):
                        logger.warning("Skipping non-dictionary category item: %s", category_item)
                        continue
                        
                    # Safely extract values
                    category_id = category_item.get("sys_id", "")
                    title = category_item.get("label", "")
                    description = category_item.get("description", "")
                    
                    # Extract knowledge base - handle both dictionary and string cases
                    knowledge_base = ""
                    kb_field = category_item.get("kb_knowledge_base")
                    if isinstance(kb_field, dict):
                        knowledge_base = kb_field.get("display_value", "")
                    elif isinstance(kb_field, str):
                        knowledge_base = kb_field
                    # Also check if kb_knowledge_base is missing but there's a separate value field
                    elif "kb_knowledge_base_value" in category_item:
                        knowledge_base = category_item.get("kb_knowledge_base_value", "")
                    elif "kb_knowledge_base.display_value" in category_item:
                        knowledge_base = category_item.get("kb_knowledge_base.display_value", "")
                    
                    # Extract parent category - handle both dictionary and string cases
                    parent = ""
                    parent_field = category_item.get("parent")
                    if isinstance(parent_field, dict):
                        parent = parent_field.get("display_value", "")
                    elif isinstance(parent_field, str):
                        parent = parent_field
                    # Also check alternative field names
                    elif "parent_value" in category_item:
                        parent = category_item.get("parent_value", "")
                    elif "parent.display_value" in category_item:
                        parent = category_item.get("parent.display_value", "")
                    
                    # Convert active to boolean - handle string or boolean types
                    active_field = category_item.get("active")
                    if isinstance(active_field, str):
                        active = active_field.lower() == "true"
                    elif isinstance(active_field, bool):
                        active = active_field
                    else:
                        active = False
                    
                    created = category_item.get("sys_created_on", "")
                    updated = category_item.get("sys_updated_on", "")
                    
                    categories.append({
                        "id": category_id,
                        "title": title,
                        "description": description,
                        "knowledge_base": knowledge_base,
                        "parent_category": parent,
                        "active": active,
                        "created": created,
                        "updated": updated,
                    })
                    
                    # Log for debugging purposes
                    logger.debug(f"Processed category: {title}, KB: {knowledge_base}, Parent: {parent}")
            else:
                logger.warning("Result is not a list: %s", result)
    
            return {
                "success": True,
                "message": f"Found {len(categories)} categories",
                "categories": categories,
                "count": len(categories),
                "limit": params.limit,
                "offset": params.offset,
            }
    
        except requests.RequestException as e:
            logger.error(f"Failed to list categories: {e}")
            return {
                "success": False,
                "message": f"Failed to list categories: {str(e)}",
                "categories": [],
                "count": 0,
                "limit": params.limit,
                "offset": params.offset,
            } 
  • Pydantic model defining the input parameters for the list_categories tool, including filters and pagination options.
    class ListCategoriesParams(BaseModel):
        """Parameters for listing categories in a knowledge base."""
        
        knowledge_base: Optional[str] = Field(None, description="Filter by knowledge base ID")
        parent_category: Optional[str] = Field(None, description="Filter by parent category ID")
        limit: int = Field(10, description="Maximum number of categories to return")
        offset: int = Field(0, description="Offset for pagination")
        active: Optional[bool] = Field(None, description="Filter by active status")
        query: Optional[str] = Field(None, description="Search query for categories")
  • Tool registration entry in get_tool_definitions() where 'list_categories' is mapped to its aliased implementation function, input schema (ListKBCategoriesParams), return type, description, and serialization hint.
    "list_categories": (
        list_kb_categories_tool_impl,  # Use passed function
        ListKBCategoriesParams,
        Dict[str, Any],  # Expects dict
        "List categories in a knowledge base",
        "raw_dict",  # Tool returns raw dict
    ),
  • In the ServiceNowMCP class initializer, calls get_tool_definitions with the aliased list_categories function (imported as list_kb_categories_tool), loading the tool definitions for registration in the MCP server.
    self.tool_definitions = get_tool_definitions(
        create_kb_category_tool, list_kb_categories_tool
    )
  • Import alias for the list_categories function from knowledge_base.py, passed to tool definitions for registration under the tool name 'list_categories'.
    list_categories as list_kb_categories_tool,
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. The description only states what the tool does ('List categories') without mentioning any behavioral traits such as whether it's read-only, if it requires authentication, rate limits, pagination behavior (implied by parameters but not described), or what the output looks like. This leaves significant gaps for an agent to understand how to use it effectively.

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 ('List categories in a knowledge base') that is front-loaded and wastes no words. It directly communicates the core purpose without unnecessary elaboration, making it easy 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 6 parameters, no annotations, and no output schema, the description is insufficiently complete. It doesn't explain the tool's behavior, output format, or usage context, leaving the agent to rely solely on the schema for details. For a listing tool with multiple filtering options, more contextual information would be helpful.

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 schema description coverage is 100%, with all 6 parameters well-documented in the input schema (e.g., 'knowledge_base' for filtering by ID, 'limit' for maximum returns). The description adds no additional parameter information beyond what's in the schema, so it meets the baseline of 3 where the schema does the heavy lifting without compensating for any gaps.

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 verb ('List') and resource ('categories in a knowledge base'), making the purpose immediately understandable. However, it doesn't distinguish this tool from sibling tools like 'list_catalog_categories' or 'list_articles', which also list different types of entities, so it doesn't fully differentiate from alternatives.

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. With sibling tools like 'list_catalog_categories' and 'list_articles' available, there's no indication of whether this tool is for knowledge base categories specifically or how it differs from other listing tools. No exclusions or prerequisites are mentioned.

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/vparlapalli490/MCP'

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