shorturl_create
Convert long URLs into short, shareable links for social media, marketing, and messaging. This tool creates compact URLs that redirect to original destinations.
Instructions
Create a short URL from a long URL.
Converts a long URL into a short, easy-to-share URL using the ShortURL API. The short URL redirects to the original long URL when visited.
This is useful for:
Sharing links on social media with character limits
Creating clean, memorable links for marketing
Tracking link clicks and engagement
Making long URLs more manageable in documents and messages
Args: url: The long URL to shorten. Must be a valid HTTP or HTTPS URL.
Returns: JSON response containing the shortened URL.
Example: shorturl_create(url="https://platform.acedata.cloud/documents/a2303356-6672-4eb8-9778-75f55c998fe9")
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| url | Yes | The long URL to shorten. Must be a valid HTTP or HTTPS URL. Required. |
Implementation Reference
- tools/shorturl_tools.py:13-64 (handler)Main handler function for shorturl_create tool. Decorated with @mcp.tool() for registration. Takes a URL parameter, validates it (must start with http:// or https://), calls client.shorten() API, and returns JSON response with the shortened URL or error details.
@mcp.tool() async def shorturl_create( url: Annotated[ str, Field(description="The long URL to shorten. Must be a valid HTTP or HTTPS URL. Required."), ], ) -> str: """Create a short URL from a long URL. Converts a long URL into a short, easy-to-share URL using the ShortURL API. The short URL redirects to the original long URL when visited. This is useful for: - Sharing links on social media with character limits - Creating clean, memorable links for marketing - Tracking link clicks and engagement - Making long URLs more manageable in documents and messages Args: url: The long URL to shorten. Must be a valid HTTP or HTTPS URL. Returns: JSON response containing the shortened URL. Example: shorturl_create(url="https://platform.acedata.cloud/documents/a2303356-6672-4eb8-9778-75f55c998fe9") """ if not url: return json.dumps({"error": "Validation Error", "message": "URL is required"}) if not url.startswith(("http://", "https://")): return json.dumps( { "error": "Validation Error", "message": "URL must start with http:// or https://", } ) try: result = await client.shorten(content=url) if not result: return json.dumps({"error": "No response received from the API."}) return json.dumps(result, ensure_ascii=False, indent=2) except ShortURLAuthError as e: return json.dumps({"error": "Authentication Error", "message": e.message}) except ShortURLAPIError as e: return json.dumps({"error": "API Error", "message": e.message}) except Exception as e: return json.dumps({"error": "Error creating short URL", "message": str(e)}) - tools/shorturl_tools.py:15-18 (schema)Input schema definition using Pydantic Field and Annotated types. Defines the 'url' parameter with description and type validation (string, required).
url: Annotated[ str, Field(description="The long URL to shorten. Must be a valid HTTP or HTTPS URL. Required."), ], - core/client.py:139-149 (helper)Helper method in ShortURLClient that makes the actual API call to shorten a URL. Calls self.request() with '/shorturl' endpoint and the content payload.
async def shorten(self, content: str) -> dict[str, Any]: """Create a short URL from a long URL. Args: content: The long URL to shorten. Returns: API response dictionary containing the short URL. """ logger.info(f"Shortening URL: {content[:80]}...") return await self.request("/shorturl", {"content": content}) - tools/__init__.py:1-10 (registration)Tool registration import module. Imports shorturl_tools which triggers the @mcp.tool() decorator registration when the module is loaded.
"""Tools module for MCP ShortURL server.""" # Import all tools to register them with the MCP server from tools import info_tools, shorturl_tools __all__ = [ "shorturl_tools", "info_tools", ] - core/client.py:60-138 (helper)Core HTTP request method that handles authentication, makes POST requests to the ShortURL API, and handles various error conditions (401, 403, timeouts, etc.). Used by the shorten() method.
async def request( self, endpoint: str, payload: dict[str, Any], timeout: float | None = None, ) -> dict[str, Any]: """Make a POST request to the ShortURL API. Args: endpoint: API endpoint path (e.g., "/shorturl") payload: Request body as dictionary timeout: Optional timeout override Returns: API response as dictionary Raises: ShortURLAuthError: If authentication fails ShortURLAPIError: If the API request fails ShortURLTimeoutError: If the request times out """ url = f"{self.base_url}{endpoint}" request_timeout = timeout or self.timeout logger.info(f"POST {url}") logger.debug(f"Request payload: {json.dumps(payload, ensure_ascii=False, indent=2)}") logger.debug(f"Timeout: {request_timeout}s") async with httpx.AsyncClient() as http_client: try: response = await http_client.post( url, json=payload, headers=self._get_headers(), timeout=request_timeout, ) logger.info(f"Response status: {response.status_code}") if response.status_code == 401: logger.error("Authentication failed: Invalid API token") raise ShortURLAuthError("Invalid API token") if response.status_code == 403: logger.error("Access denied: Check API permissions") raise ShortURLAuthError("Access denied. Check your API permissions.") response.raise_for_status() result = response.json() logger.success("Request successful!") if result.get("success") and "data" in result: short_url = result["data"].get("url", "") logger.info(f"Short URL created: {short_url}") return result # type: ignore[no-any-return] except httpx.TimeoutException as e: logger.error(f"Request timeout after {request_timeout}s: {e}") raise ShortURLTimeoutError( f"Request to {endpoint} timed out after {request_timeout}s" ) from e except ShortURLAuthError: raise except httpx.HTTPStatusError as e: logger.error(f"HTTP error {e.response.status_code}: {e.response.text}") raise ShortURLAPIError( message=e.response.text, code=f"http_{e.response.status_code}", status_code=e.response.status_code, ) from e except Exception as e: logger.error(f"Request error: {e}") raise ShortURLAPIError(message=str(e)) from e