Skip to main content
Glama
JLKmach

ServiceNow MCP Server

by JLKmach

list_knowledge_bases

Retrieve and filter ServiceNow knowledge bases to find relevant information using search queries, status filters, and pagination controls.

Instructions

List knowledge bases from ServiceNow

Input Schema

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

Implementation Reference

  • The handler function that implements the list_knowledge_bases tool by querying the ServiceNow kb_knowledge_base table API with pagination and filters, transforming the response into a structured dictionary.
    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 model defining the input parameters for the list_knowledge_bases tool, including limit, offset, active filter, and query.
    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")
  • Registration of the list_knowledge_bases tool in the get_tool_definitions dictionary, mapping name to (handler, schema, return_type, description, serialization).
    "list_knowledge_bases": (
        list_knowledge_bases_tool,
        ListKnowledgeBasesParams,
        Dict[str, Any],  # Expects dict
        "List knowledge bases from ServiceNow",
        "raw_dict",  # Tool returns raw dict
    ),
  • Import alias for the handler function used in tool registration.
        list_knowledge_bases as list_knowledge_bases_tool,
    )
  • Re-export of the list_knowledge_bases function in the tools module __init__.
    list_knowledge_bases,
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. 'List knowledge bases' implies a read-only operation, but it doesn't mention pagination behavior (implied by parameters), rate limits, authentication requirements, or what the return format looks like. For a tool with 4 parameters and no output schema, this leaves significant behavioral gaps.

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 straightforward list operation and front-loads the essential information without unnecessary elaboration.

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 tool with 4 parameters, no annotations, and no output schema, the description is insufficiently complete. It doesn't explain the return format, pagination behavior, or how filtering works despite having active and query parameters. The description should provide more context about what 'listing' entails in this specific ServiceNow context.

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 fully documents all 4 parameters (limit, offset, active, query). The description adds no parameter information beyond what's in the schema, meeting the baseline of 3 when schema coverage is complete.

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 ('knowledge bases from ServiceNow'), making the purpose immediately understandable. However, it doesn't differentiate from sibling tools like 'list_articles' or 'list_categories' beyond specifying the resource type, missing explicit distinction that would warrant a score of 5.

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. There are many sibling list tools (e.g., list_articles, list_categories), but no indication of when this specific knowledge base listing is appropriate or what distinguishes it from other listing operations.

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

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