Skip to main content
The Hugging Face Hub exposes an MCP server for searching models, datasets, Spaces, and papers. It works anonymously; adding a free token raises rate limits and exposes tools that touch your own account. That makes it the example for the optional auth pattern: the same agent works with or without a key, and only attaches the Bearer token when one is present. A missing environment variable should degrade to anonymous access, not crash on startup.

Prerequisites

A small, fast model is a deliberate choice here. The task is search-and-report, not reasoning; the intelligence lives in the Hub’s index.

Build it

1

Install and set your LLM key

2

Make the token optional, not required

The conditional comes later, at the mcp_api_key argument — pass "env:HF_TOKEN" when a token exists and None when it does not.
3

Write a prompt that forbids recalled repo ids

Model names are exactly the kind of thing an LLM will produce from memory, confidently and wrongly. Half of this prompt exists to stop that:
4

Attach the token only if it exists

mcp_api_key="env:HF_TOKEN" sends Authorization: Bearer <token>, reading the value from the environment at connection time so the secret stays out of your source.
5

Ask a question with real constraints

Constraints — size, license, commercial use — are what make this worth a search. “Recommend an embedding model” would get you an answer from memory.

The complete script

Why the optional-auth shape is worth copying

Most integrations treat a credential as required and exit if it is missing. For a server that serves anonymous traffic, that turns a working demo into a broken one for anyone who has not signed up yet. The pattern generalizes to any server with a free anonymous tier:
Tell the user which mode they are in — the one-line print above — so a rate-limit error later is not a mystery.

Next