list_models
List AI models from OpenRouter, filter by modality and sort by price, context length, or name.
Instructions
List models available on OpenRouter.
Args: modality: Filter by output type. Options: text, image, audio, embeddings, all sort_by: Sort by: name, created, price, context_length
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| modality | No | text | |
| sort_by | No | name |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
| result | Yes |
Implementation Reference
- src/openrouter_mcp/server.py:88-118 (handler)The list_models MCP tool handler. Fetches models from OpenRouter (with caching), filters by modality, sorts by the chosen key, and returns a formatted string of up to 100 models.
@mcp.tool() def list_models( modality: str = "text", sort_by: str = "name", ) -> str: """List models available on OpenRouter. Args: modality: Filter by output type. Options: text, image, audio, embeddings, all sort_by: Sort by: name, created, price, context_length """ models = fetch_models() if modality and modality != "all": models = [ m for m in models if modality in m.get("arch_modality", ["text"]) ] key_map = { "name": lambda m: m.get("name", "").lower(), "created": lambda m: m.get("created", 0), "price": lambda m: float(m.get("pricing", {}).get("prompt", 0)), "context_length": lambda m: m.get("context_length", 0), } key_fn = key_map.get(sort_by, key_map["name"]) reverse = sort_by in ("created", "context_length") models = sorted(models, key=key_fn, reverse=reverse) header = f"# OpenRouter Models — {len(models)} results ({modality}, sorted by {sort_by})\n" return header + "\n\n".join(_format_model(m) for m in models[:100]) - src/openrouter_mcp/server.py:88-88 (registration)The list_models function is registered as an MCP tool via the @mcp.tool() decorator on line 88.
@mcp.tool() - src/openrouter_mcp/server.py:34-52 (helper)The fetch_models helper function is called by list_models to retrieve model data from the OpenRouter API with in-memory caching (300s TTL).
def fetch_models(force=False) -> list[dict]: """Fetch model list from OpenRouter with caching.""" now = time.time() if _cache["data"] is not None and (now - _cache["ts"]) < CACHE_TTL and not force: return _cache["data"] headers = {"Accept": "application/json"} if OR_API_KEY: headers["Authorization"] = f"Bearer {OR_API_KEY}" req = Request(OR_MODELS_URL, headers=headers) try: with urlopen(req, timeout=30) as resp: body = json.loads(resp.read()) _cache["data"] = body.get("data", []) _cache["ts"] = now return _cache["data"] except URLError as e: raise RuntimeError(f"Failed to fetch OpenRouter models: {e}") - src/openrouter_mcp/server.py:61-83 (helper)The _format_model helper formats a single model dictionary into a human-readable string (used by list_models for its output).
def _format_model(m: dict, detail=False) -> str: pricing = m.get("pricing", {}) input_p = float(pricing.get("prompt", 0)) output_p = float(pricing.get("completion", 0)) ctx = m.get("context_length", "?") name = m.get("name", m["id"]) provider = m["id"].split("/")[0] supported = m.get("supported_parameters", []) lines = [ f"**{m['id']}**", f" Provider: {provider} | Context: {ctx:,}" if isinstance(ctx, (int, float)) else f" Provider: {provider} | Context: {ctx}", f" Pricing — Input: {_price_str(input_p)} | Output: {_price_str(output_p)}", ] if supported: lines.append(f" Features: {', '.join(supported)}") if detail and m.get("description"): lines.append(f" {m['description'][:150]}") if detail and m.get("architecture", {}).get("modality"): lines.append(f" Modality: {m['architecture']['modality']}") if detail and m.get("top_provider"): lines.append(f" Top provider: {m['top_provider']}") return "\n".join(lines) - src/openrouter_mcp/__init__.py:5-7 (registration)The list_models function is exported from the package in __init__.py, making it publicly accessible.
from .server import main, fetch_models, list_models, get_model, search_models, compare_models, refresh_cache __all__ = ["main", "fetch_models", "list_models", "get_model", "search_models", "compare_models", "refresh_cache"]