| 
 | 1 | +"""  | 
 | 2 | +import_mapping tool  | 
 | 3 | +
  | 
 | 4 | +This tool is based on (and wraps) logic from:  | 
 | 5 | +`conda_forge_metadata.autotick_bot.import_to_pkg`  | 
 | 6 | +"""  | 
 | 7 | + | 
 | 8 | +from __future__ import annotations  | 
 | 9 | + | 
 | 10 | +import asyncio  | 
 | 11 | +from functools import lru_cache  | 
 | 12 | +from typing import TYPE_CHECKING  | 
 | 13 | + | 
 | 14 | +from fastmcp.exceptions import ToolError  | 
 | 15 | + | 
 | 16 | +if TYPE_CHECKING:  | 
 | 17 | +    from fastmcp import FastMCP  | 
 | 18 | + | 
 | 19 | + | 
 | 20 | +from conda_forge_metadata.autotick_bot.import_to_pkg import (  | 
 | 21 | +    get_pkgs_for_import,  | 
 | 22 | +    map_import_to_package,  | 
 | 23 | +)  | 
 | 24 | + | 
 | 25 | + | 
 | 26 | +@lru_cache(maxsize=1024)  | 
 | 27 | +def _map_import(import_name: str) -> dict:  | 
 | 28 | +    if not import_name or not import_name.strip():  | 
 | 29 | +        raise ValueError("import_name must be a non-empty string")  | 
 | 30 | + | 
 | 31 | +    query = import_name.strip()  | 
 | 32 | + | 
 | 33 | +    # Underlying function truncates to top-level automatically.  | 
 | 34 | +    candidates, normalized = get_pkgs_for_import(query)  | 
 | 35 | + | 
 | 36 | +    if candidates is None or len(candidates) == 0:  | 
 | 37 | +        # No mapping known; identity fallback.  | 
 | 38 | +        return {  | 
 | 39 | +            "query_import": query,  | 
 | 40 | +            "normalized_import": normalized,  | 
 | 41 | +            "best_package": normalized,  | 
 | 42 | +            "candidate_packages": [],  | 
 | 43 | +            "heuristic": "identity",  | 
 | 44 | +        }  | 
 | 45 | + | 
 | 46 | +    best = map_import_to_package(query)  | 
 | 47 | + | 
 | 48 | +    if best == normalized and best in candidates:  | 
 | 49 | +        heuristic = "identity_present"  | 
 | 50 | +    elif best in candidates:  | 
 | 51 | +        heuristic = "ranked_selection"  | 
 | 52 | +    else:  | 
 | 53 | +        heuristic = "fallback"  | 
 | 54 | + | 
 | 55 | +    return {  | 
 | 56 | +        "query_import": query,  | 
 | 57 | +        "normalized_import": normalized,  | 
 | 58 | +        "best_package": best,  | 
 | 59 | +        "candidate_packages": sorted(candidates),  | 
 | 60 | +        "heuristic": heuristic,  | 
 | 61 | +    }  | 
 | 62 | + | 
 | 63 | + | 
 | 64 | +def register_import_mapping(mcp: FastMCP) -> None:  | 
 | 65 | +    @mcp.tool  | 
 | 66 | +    async def import_mapping(import_name: str) -> dict:  | 
 | 67 | +        """  | 
 | 68 | +        Map a (possibly dotted) Python import name to the most likely conda package  | 
 | 69 | +        and expose supporting context.  | 
 | 70 | +
  | 
 | 71 | +        What this does:  | 
 | 72 | +          - Normalizes the import to its top-level module (e.g. "numpy.linalg" -> "numpy")  | 
 | 73 | +          - Retrieves an approximate candidate set of conda packages that may provide it  | 
 | 74 | +          - Applies a heuristic to pick a single "best" package  | 
 | 75 | +          - Returns a structured result with the decision rationale  | 
 | 76 | +
  | 
 | 77 | +        Heuristic labels:  | 
 | 78 | +          - identity:          No candidates known; fallback to normalized import  | 
 | 79 | +          - identity_present:  Candidates exist AND the normalized import name is among them  | 
 | 80 | +          - ranked_selection:  Best package chosen via ranked hubs authorities ordering  | 
 | 81 | +          - fallback:          Best package not in candidates (unexpected edge case)  | 
 | 82 | +
  | 
 | 83 | +        Returned dict schema:  | 
 | 84 | +          {  | 
 | 85 | +            "query_import":      original query string supplied by caller  | 
 | 86 | +            "normalized_import": top-level portion used for lookup  | 
 | 87 | +            "best_package":      chosen conda package name (may equal normalized_import)  | 
 | 88 | +            "candidate_packages": sorted list of possible supplying packages (may be empty)  | 
 | 89 | +            "heuristic":         one of the heuristic labels above  | 
 | 90 | +          }  | 
 | 91 | +
  | 
 | 92 | +        Args:  | 
 | 93 | +          import_name:  | 
 | 94 | +            Import string, e.g. "yaml", "matplotlib.pyplot", "sklearn.model_selection".  | 
 | 95 | +        """  | 
 | 96 | +        try:  | 
 | 97 | +            return await asyncio.to_thread(_map_import, import_name)  | 
 | 98 | +        except ValueError as ve:  | 
 | 99 | +            raise ToolError(f"'import_mapping' invalid input: {ve}") from ve  | 
 | 100 | +        except Exception as e:  # pragma: no cover - generic protection  | 
 | 101 | +            raise ToolError(f"'import_mapping' failed: {e}") from e  | 
0 commit comments