Skip to main content
Glama
lumishoang

OpenRouter MCP Server

by lumishoang

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

TableJSON Schema
NameRequiredDescriptionDefault
modalityNotext
sort_byNoname

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • 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])
  • The list_models function is registered as an MCP tool via the @mcp.tool() decorator on line 88.
    @mcp.tool()
  • 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}")
  • 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)
  • 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"]
Behavior3/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 discloses the filtering and sorting parameters, implying a read-only listing operation. However, it does not mention rate limits, pagination, result limits, or any side effects. For a simple list tool, basic behavioral traits are partially covered but not comprehensively.

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 concise, with a clear one-liner purpose followed by parameter details in a readable arg list. No unnecessary words. However, the parameter list could be formatted more clearly (e.g., bullet points) for machine parsing, though it remains human-readable.

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

Completeness3/5

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

Given the tool's simplicity (2 optional params, output schema exists), the description is functionally sufficient but lacks context about when to invoke it relative to siblings. It does not mention that it returns a full list or the default behavior (e.g., all modalities). The output schema likely covers return format, but usage context is minimal.

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?

The schema description coverage is 0%, so the description adds meaning by listing possible values for 'modality' (text, image, audio, embeddings, all) and 'sort_by' (name, created, price, context_length). However, it does not explain what each sort option means (e.g., alphabetical, date, cost, token limit), leaving some ambiguity. The added value compensates for schema gaps but is still minimal.

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: 'List models available on OpenRouter.' This directly distinguishes it from siblings like 'compare_models' (comparison), 'get_model' (specific model), and 'search_models' (search). The verb 'List' plus resource 'models' is specific and unambiguous.

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 does not provide any guidance on when to use this tool versus alternatives (e.g., search_models, compare_models). It only describes the parameters, leaving the agent to infer the use case. Without explicit context, the agent may struggle to choose the appropriate tool.

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/lumishoang/openrouter-mcp'

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