Skip to main content
Glama
javerthl

ServiceNow MCP Server

by javerthl

list_knowledge_bases

Retrieve a list of knowledge bases from ServiceNow with filtering options for active status, search queries, and pagination controls.

Instructions

List knowledge bases from ServiceNow

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
activeNoFilter by active status
limitNoMaximum number of knowledge bases to return
offsetNoOffset for pagination
queryNoSearch query for knowledge bases

Implementation Reference

  • Main handler function implementing the list_knowledge_bases tool logic, querying ServiceNow API for knowledge bases.
    def list_knowledge_bases(
        config: ServerConfig,
        auth_manager: AuthManager,
        params: ListKnowledgeBasesParams,
    ) -> Dict[str, Any]:
        """
        List knowledge bases with filtering options.
    
        Args:
            config: Server configuration.
            auth_manager: Authentication manager.
            params: Parameters for listing knowledge bases.
    
        Returns:
            Dictionary with list of knowledge bases and metadata.
        """
        api_url = f"{config.api_url}/table/kb_knowledge_base"
    
        # Build query parameters
        query_params = {
            "sysparm_limit": params.limit,
            "sysparm_offset": params.offset,
            "sysparm_display_value": "true",
        }
    
        # Build query string
        query_parts = []
        if params.active is not None:
            query_parts.append(f"active={str(params.active).lower()}")
        if params.query:
            query_parts.append(f"titleLIKE{params.query}^ORdescriptionLIKE{params.query}")
    
        if query_parts:
            query_params["sysparm_query"] = "^".join(query_parts)
    
        # 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",
                    "knowledge_bases": [],
                    "count": 0,
                    "limit": params.limit,
                    "offset": params.offset,
                }
    
            # Transform the results - create a simpler structure
            knowledge_bases = []
            
            # Handle either string or list
            if isinstance(result, list):
                for kb_item in result:
                    if not isinstance(kb_item, dict):
                        logger.warning("Skipping non-dictionary KB item: %s", kb_item)
                        continue
                        
                    # Safely extract values
                    kb_id = kb_item.get("sys_id", "")
                    title = kb_item.get("title", "")
                    description = kb_item.get("description", "")
                    
                    # Extract nested values safely
                    owner = ""
                    if isinstance(kb_item.get("owner"), dict):
                        owner = kb_item["owner"].get("display_value", "")
                    
                    managers = ""
                    if isinstance(kb_item.get("kb_managers"), dict):
                        managers = kb_item["kb_managers"].get("display_value", "")
                    
                    active = False
                    if kb_item.get("active") == "true":
                        active = True
                    
                    created = kb_item.get("sys_created_on", "")
                    updated = kb_item.get("sys_updated_on", "")
                    
                    knowledge_bases.append({
                        "id": kb_id,
                        "title": title,
                        "description": description,
                        "owner": owner,
                        "managers": managers,
                        "active": active,
                        "created": created,
                        "updated": updated,
                    })
            else:
                logger.warning("Result is not a list: %s", result)
    
            return {
                "success": True,
                "message": f"Found {len(knowledge_bases)} knowledge bases",
                "knowledge_bases": knowledge_bases,
                "count": len(knowledge_bases),
                "limit": params.limit,
                "offset": params.offset,
            }
    
        except requests.RequestException as e:
            logger.error(f"Failed to list knowledge bases: {e}")
            return {
                "success": False,
                "message": f"Failed to list knowledge bases: {str(e)}",
                "knowledge_bases": [],
                "count": 0,
                "limit": params.limit,
                "offset": params.offset,
            }
  • Pydantic input schema defining parameters for the list_knowledge_bases tool.
    class ListKnowledgeBasesParams(BaseModel):
        """Parameters for listing knowledge bases."""
        
        limit: int = Field(10, description="Maximum number of knowledge bases 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 knowledge bases")
  • Tool registration in get_tool_definitions() mapping name to handler, schema, description for MCP server.
    "list_knowledge_bases": (
        list_knowledge_bases_tool,
        ListKnowledgeBasesParams,
        Dict[str, Any],  # Expects dict
        "List knowledge bases from ServiceNow",
        "raw_dict",  # Tool returns raw dict
    ),
  • Export of list_knowledge_bases in tools package __all__ for easy import.
    "list_knowledge_bases",
  • Import alias of the handler function used in tool registration.
        # list_categories aliased in function call
        list_knowledge_bases as list_knowledge_bases_tool,
    )
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 but only states the basic action. It doesn't mention whether this is a read-only operation, if it requires authentication, potential rate limits, pagination behavior beyond the schema, or what the output format looks like. For a list operation with zero annotation coverage, this is inadequate.

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 with zero wasted words. It's appropriately sized for a simple list operation and front-loads the core purpose immediately. Every word earns its place.

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 (a list operation with filtering/pagination), lack of annotations, and no output schema, the description is incomplete. It doesn't explain what a 'knowledge base' entails in ServiceNow context, what fields are returned, or behavioral aspects like error handling. The schema covers parameters well, but overall context is lacking for effective tool 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?

The input schema has 100% description coverage, clearly documenting all four parameters (active, limit, offset, query) with their purposes. 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.

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 ('List') and resource ('knowledge bases from ServiceNow'), providing a specific verb+resource combination. However, it doesn't distinguish this tool from other list tools in the sibling set (like list_articles, list_categories, etc.), which would require mentioning what makes knowledge bases unique or when to prefer this over other list operations.

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. Given the extensive sibling tool list including other list operations (e.g., list_articles, list_categories) and a create_knowledge_base tool, there's no mention of prerequisites, typical use cases, or how this fits into workflows. This leaves the agent without contextual usage information.

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/javerthl/servicenow-mcp'

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