Skip to main content
Glama
avivshafir

abstractapi-mcp-server

validate_phone

Validate phone numbers globally to verify format, country, location, type, and carrier details for accurate contact information.

Instructions

Validates a phone number using Abstract API's Phone Validation service.

This function checks the validity and other details of phone numbers from over 190 countries.
It returns detailed information about the phone number including format, country, location,
type, and carrier information.

Args:
    phone (str): The phone number to validate and verify.
    country (str, optional): The country's ISO code to indicate the phone number's country.
                            This helps the API append the corresponding country code to its analysis.
                            For example, use "US" for United States numbers.

Returns:
    dict[str, Any]: A dictionary containing detailed validation results. The dictionary
    includes the following keys:
        - "phone" (str): The phone number submitted for validation.
        - "valid" (bool): True if the phone number is valid, False otherwise.
        - "format" (dict): Object containing international and local formats.
            - "international" (str): International format with country code and "+" prefix.
            - "local" (str): Local/national format without international formatting.
        - "country" (dict): Object containing country details.
            - "code" (str): Two-letter ISO 3166-1 alpha-2 country code.
            - "name" (str): Name of the country where the phone number is registered.
            - "prefix" (str): Country's calling code prefix.
        - "location" (str): Location details (region, state/province, sometimes city).
        - "type" (str): Type of phone number. Possible values: "Landline", "Mobile",
                       "Satellite", "Premium", "Paging", "Special", "Toll_Free", "Unknown".
        - "carrier" (str): The carrier that the number is registered with.

Example:
    >>> await validate_phone("14152007986")
    {
        "phone": "14152007986",
        "valid": true,
        "format": {
            "international": "+14152007986",
            "local": "(415) 200-7986"
        },
        "country": {
            "code": "US",
            "name": "United States",
            "prefix": "+1"
        },
        "location": "California",
        "type": "mobile",
        "carrier": "T-Mobile USA, Inc."
    }

    >>> await validate_phone("2007986", "US")
    # Will validate with US country context

Raises:
    ValueError: If the API key is not found in the environment variables.
    requests.exceptions.HTTPError: If the API request fails (e.g., 4xx or 5xx error).
    Exception: For any other unexpected errors.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
phoneYes
countryNo

Implementation Reference

  • The handler function for the 'validate_phone' tool. It is decorated with @mcp.tool(), which registers it as an MCP tool. The function validates phone numbers by calling the Abstract API phone validation endpoint, handling the request, parsing the response, and raising appropriate errors.
    @mcp.tool()
    async def validate_phone(phone: str, country: str | None = None) -> dict[str, Any]:
        """
        Validates a phone number using Abstract API's Phone Validation service.
    
        This function checks the validity and other details of phone numbers from over 190 countries.
        It returns detailed information about the phone number including format, country, location,
        type, and carrier information.
    
        Args:
            phone (str): The phone number to validate and verify.
            country (str, optional): The country's ISO code to indicate the phone number's country.
                                    This helps the API append the corresponding country code to its analysis.
                                    For example, use "US" for United States numbers.
    
        Returns:
            dict[str, Any]: A dictionary containing detailed validation results. The dictionary
            includes the following keys:
                - "phone" (str): The phone number submitted for validation.
                - "valid" (bool): True if the phone number is valid, False otherwise.
                - "format" (dict): Object containing international and local formats.
                    - "international" (str): International format with country code and "+" prefix.
                    - "local" (str): Local/national format without international formatting.
                - "country" (dict): Object containing country details.
                    - "code" (str): Two-letter ISO 3166-1 alpha-2 country code.
                    - "name" (str): Name of the country where the phone number is registered.
                    - "prefix" (str): Country's calling code prefix.
                - "location" (str): Location details (region, state/province, sometimes city).
                - "type" (str): Type of phone number. Possible values: "Landline", "Mobile",
                               "Satellite", "Premium", "Paging", "Special", "Toll_Free", "Unknown".
                - "carrier" (str): The carrier that the number is registered with.
    
        Example:
            >>> await validate_phone("14152007986")
            {
                "phone": "14152007986",
                "valid": true,
                "format": {
                    "international": "+14152007986",
                    "local": "(415) 200-7986"
                },
                "country": {
                    "code": "US",
                    "name": "United States",
                    "prefix": "+1"
                },
                "location": "California",
                "type": "mobile",
                "carrier": "T-Mobile USA, Inc."
            }
    
            >>> await validate_phone("2007986", "US")
            # Will validate with US country context
    
        Raises:
            ValueError: If the API key is not found in the environment variables.
            requests.exceptions.HTTPError: If the API request fails (e.g., 4xx or 5xx error).
            Exception: For any other unexpected errors.
        """
        # Check if the API key is available
        if not ABSTRACT_API_KEY:
            raise ValueError("API key not found in environment variables.")
    
        # Construct the API URL
        api_url = f"{PHONE_VALIDATION_API_URL}?api_key={ABSTRACT_API_KEY}&phone={phone}"
    
        # Add country parameter if provided
        if country:
            api_url += f"&country={country}"
    
        try:
            # Make the API request (ignoring SSL verification)
            response = requests.get(api_url, verify=False)
            response.raise_for_status()  # Raise an error for bad responses (4xx, 5xx)
    
            # Parse the JSON response
            result = response.json()
    
            # Return the validation results
            return result
    
        except requests.exceptions.HTTPError as http_err:
            # Handle HTTP errors (e.g., 4xx, 5xx)
            raise requests.exceptions.HTTPError(f"HTTP error occurred: {http_err}")
        except Exception as err:
            # Handle any other errors
            raise Exception(f"An error occurred: {err}")
  • server.py:130-130 (registration)
    The @mcp.tool() decorator registers the validate_phone function as a tool in the FastMCP server, automatically handling schema inference from type hints and docstring.
    @mcp.tool()
  • Input schema defined by function parameters (phone: str required, country: str optional). Output schema described in detail in the docstring as a dict with keys like 'phone', 'valid', 'format', 'country', etc.
    async def validate_phone(phone: str, country: str | None = None) -> dict[str, Any]:
Behavior5/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 and does so comprehensively. It explains what the tool returns (detailed validation results), includes error handling information (raises section), describes the external API dependency, and provides a complete example of the return format. This goes well beyond basic functional description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections (purpose, parameters, returns, example, raises) but is somewhat lengthy. Every section adds value, though some information could be more concise. The front-loaded purpose statement is clear, and the structure helps with comprehension despite the length.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with no annotations, no output schema, and 0% schema description coverage, the description provides exceptional completeness. It covers purpose, parameters, return values with detailed structure, examples, error handling, and external dependencies. The return value documentation effectively substitutes for a missing output schema, making this description highly complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description fully compensates by providing detailed parameter documentation. It explains both parameters thoroughly: 'phone' is the number to validate, and 'country' is an optional ISO code that helps with analysis. The description includes examples showing how both parameters work, adding significant value beyond the bare schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Validates a phone number using Abstract API's Phone Validation service.' It specifies the exact action (validate), resource (phone number), and service provider, distinguishing it from sibling email tools. The description goes beyond the tool name by explaining it checks validity and returns detailed information.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context about when to use this tool: for validating phone numbers from over 190 countries. It doesn't explicitly mention when not to use it or compare with alternatives, but the context is sufficiently clear given the tool's specialized function. The examples show usage patterns with and without the optional country parameter.

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/avivshafir/abstractapi-mcp-server'

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