Skip to main content
Glama
aiopnet

MCP Nautobot Server

by aiopnet

get_prefixes

Retrieve network prefixes from Nautobot with filtering by prefix, status, site, role, tenant, VRF, and pagination options.

Instructions

Retrieve network prefixes from Nautobot with filtering options

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
prefixNoSpecific network prefix to search for
statusNoStatus to filter by
siteNoSite to filter by
roleNoRole to filter by
tenantNoTenant to filter by
vrfNoVRF to filter by
limitNoMaximum number of results to return (default: 100, max: 1000)
offsetNoNumber of results to skip for pagination (default: 0)

Implementation Reference

  • The handler logic within @server.call_tool() that processes the 'get_prefixes' tool call, extracts parameters, calls the NautobotClient helper, formats results as JSON, and returns them as TextContent.
    elif name == "get_prefixes":
        # Extract and validate arguments
        prefix = args.get("prefix")
        status = args.get("status")
        site = args.get("site")
        role = args.get("role")
        tenant = args.get("tenant")
        vrf = args.get("vrf")
        limit = min(args.get("limit", 100), 1000)  # Cap at 1000
        offset = args.get("offset", 0)
        
        logger.info(f"Retrieving prefixes with filters: {args}")
        
        # Get prefixes from Nautobot
        prefixes = await client.get_prefixes(
            prefix=prefix,
            status=status,
            site=site,
            role=role,
            tenant=tenant,
            vrf=vrf,
            limit=limit,
            offset=offset
        )
        
        # Format results
        result = {
            "count": len(prefixes),
            "filters_applied": {k: v for k, v in args.items() if v is not None},
            "results": [prefix_obj.model_dump() for prefix_obj in prefixes]
        }
        
        return [
            types.TextContent(
                type="text",
                text=f"Retrieved {len(prefixes)} network prefixes from Nautobot:\n\n"
                     f"```json\n{result}\n```"
            )
        ]
  • Registration of the 'get_prefixes' tool in the @server.list_tools() handler, including name, description, and input schema.
    types.Tool(
        name="get_prefixes",
        description="Retrieve network prefixes from Nautobot with filtering options",
        inputSchema={
            "type": "object",
            "properties": {
                "prefix": {
                    "type": "string",
                    "description": "Specific network prefix to search for"
                },
                "status": {
                    "type": "string",
                    "description": "Status to filter by"
                },
                "site": {
                    "type": "string",
                    "description": "Site to filter by"
                },
                "role": {
                    "type": "string",
                    "description": "Role to filter by"
                },
                "tenant": {
                    "type": "string",
                    "description": "Tenant to filter by"
                },
                "vrf": {
                    "type": "string",
                    "description": "VRF to filter by"
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximum number of results to return (default: 100, max: 1000)",
                    "default": 100,
                    "minimum": 1,
                    "maximum": 1000
                },
                "offset": {
                    "type": "integer",
                    "description": "Number of results to skip for pagination (default: 0)", 
                    "default": 0,
                    "minimum": 0
                }
            },
            "additionalProperties": False
        },
    ),
  • Helper method in NautobotClient that performs the actual API request to retrieve prefixes from Nautobot /ipam/prefixes/ endpoint, applies filters, parses responses into Prefix models.
    async def get_prefixes(
        self,
        prefix: Optional[str] = None,
        status: Optional[str] = None,
        site: Optional[str] = None,
        role: Optional[str] = None,
        tenant: Optional[str] = None,
        vrf: Optional[str] = None,
        limit: int = 100,
        offset: int = 0
    ) -> List[Prefix]:
        """
        Retrieve network prefixes from Nautobot.
        
        Args:
            prefix: Filter by network prefix
            status: Filter by status slug
            site: Filter by site slug
            role: Filter by role slug
            tenant: Filter by tenant slug
            vrf: Filter by VRF name
            limit: Maximum number of results to return
            offset: Number of results to skip
            
        Returns:
            List of Prefix objects
            
        Raises:
            NautobotError: For API or connection errors
        """
        params: Dict[str, Any] = {
            "limit": limit,
            "offset": offset,
        }
        
        # Add optional filters
        if prefix:
            params["prefix"] = prefix
        if status:
            params["status"] = status
        if site:
            params["site"] = site
        if role:
            params["role"] = role
        if tenant:
            params["tenant"] = tenant
        if vrf:
            params["vrf"] = vrf
        
        try:
            response = await self._make_request("GET", "/ipam/prefixes/", params)
            
            # Parse results
            prefixes = []
            for item in response.get("results", []):
                try:
                    prefixes.append(Prefix(**item))
                except Exception as e:
                    logger.warning(f"Failed to parse prefix data: {e}")
                    continue
            
            logger.info(f"Retrieved {len(prefixes)} prefixes")
            return prefixes
            
        except Exception as e:
            logger.error(f"Failed to retrieve prefixes: {e}")
            raise
  • Pydantic model defining the structure for prefix data returned from Nautobot API.
    class Prefix(BaseModel):
        """Pydantic model for Nautobot prefix data."""
        
        id: str
        url: HttpUrl
        prefix: str
        status: Dict[str, Any]
        site: Optional[Dict[str, Any]] = None
        vrf: Optional[Dict[str, Any]] = None
        tenant: Optional[Dict[str, Any]] = None
        vlan: Optional[Dict[str, Any]] = None
        role: Optional[Dict[str, Any]] = None
        is_pool: bool = False
        description: Optional[str] = None
        comments: Optional[str] = None
        tags: List[Dict[str, Any]] = Field(default_factory=list)
        custom_fields: Dict[str, Any] = Field(default_factory=dict)
        created: str
        last_updated: str
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. It mentions 'filtering options' but doesn't disclose key behaviors: whether this is a read-only operation, if it has rate limits, what authentication is required, or what the output format looks like. For a tool with 8 parameters and no annotations, this leaves significant gaps in understanding its behavior.

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 front-loads the core purpose ('Retrieve network prefixes from Nautobot') and adds a useful qualifier ('with filtering options'). There's no wasted verbiage or redundancy, making it appropriately concise for the tool's complexity.

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 tool has 8 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain the return values, error conditions, or behavioral nuances like pagination (implied by 'limit' and 'offset' parameters). For a data retrieval tool with multiple filters, more context is needed to guide effective 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?

Schema description coverage is 100%, so the schema fully documents all 8 parameters with their types, descriptions, and constraints. The description adds minimal value by mentioning 'filtering options' generically, but doesn't provide additional context or meaning beyond what's already in the schema. This meets the baseline for high schema coverage.

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 ('Retrieve') and resource ('network prefixes from Nautobot'), making the purpose understandable. It also mentions 'with filtering options' which adds specificity. However, it doesn't explicitly differentiate from sibling tools like 'get_ip_addresses' or 'search_ip_addresses', which might retrieve similar network data.

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 'get_ip_addresses' and 'search_ip_addresses' available, there's no indication of whether this tool is for broader prefix retrieval, how it differs in scope, or any prerequisites for use.

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/aiopnet/mcp-nautobot'

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