# Gemini

MillionShort search for Gemini models, as a function tool in the Google Gen AI SDK, in Python and TypeScript.

Recipe · Python and TypeScript · Nothing of ours to install · Works with no key · Checked 2026-11-19

> **For agents.** Read the API key from the `MILLIONSHORT_API_KEY` environment variable. Never print it; where a client needs it in a settings file, use a file that is not committed.
> The MCP address is https://mcp.millionshort.com/mcp (streamable HTTP; send `Authorization: Bearer <key>`, or no header for the no-key mode).
> On `INSUFFICIENT_CREDITS` stop and ask a person; on `RATE_LIMITED` or `CAPACITY` wait the `Retry-After` seconds, then retry once.
> Set-up steps written for agents: https://millionshort.com/docs/auth.md. Every integration: https://millionshort.com/docs/integrations.md.

The Gemini API has no remote MCP tool of its own: your code runs the search. In Python, pass a plain function as a tool and the SDK calls it for the model (automatic function calling). In TypeScript, declare the function and run the loop yourself. The SDKs can also take an MCP session you open to our server; Google marks that support experimental.

## 1. Install

```bash Python
pip install google-genai requests mcp httpx2
export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
```

```bash TypeScript
npm install @google/genai @modelcontextprotocol/sdk zod
export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
```

The SDK reads your Gemini key from GEMINI_API_KEY (or GOOGLE_API_KEY). Get a MillionShort key in the [dashboard](https://millionshort.com/app/); an agent can ask for a [trial key](https://millionshort.com/docs/api-reference/agent-key) by itself. The MCP packages (`mcp` and `httpx2`, `@modelcontextprotocol/sdk` and `zod`) are only for the MCP section further down.

## 2. Minimal example

```python Python
import json
import os

import requests
from google import genai
from google.genai import types


def millionshort_search(query: str) -> str:
    """Search the web with MillionShort, leaving out the 1,000 most popular sites.

    Args:
        query: What to search for.
    """
    r = requests.post(
        "https://api.millionshort.com/v1/search",
        headers={"Authorization": f"Bearer {os.environ['MILLIONSHORT_API_KEY']}"},
        json={"query": query, "remove_top_sites": 1000, "num_results": 5},
        timeout=30,
    )
    r.raise_for_status()
    return json.dumps([{"title": x["title"], "url": x["url"], "snippet": x.get("snippet")} for x in r.json()["data"]["results"]])


client = genai.Client()
response = client.models.generate_content(
    model="gemini-4-hydrogen",
    contents="Find independent blogs about home espresso.",
    config=types.GenerateContentConfig(tools=[millionshort_search]),
)
print(response.text)
```

```ts TypeScript
import { GoogleGenAI, type Content } from '@google/genai';

async function millionshortSearch(query: string): Promise<string> {
  const res = await fetch('https://api.millionshort.com/v1/search', {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ query, remove_top_sites: 1000, num_results: 5 }),
  });
  if (!res.ok) throw new Error(`search failed: ${res.status}`);
  const { data } = (await res.json()) as { data: { results: { title: string; url: string; snippet?: string }[] } };
  return JSON.stringify(data.results.map(({ title, url, snippet }) => ({ title, url, snippet })));
}

const config = { tools: [{ functionDeclarations: [{
  name: 'millionshort_search',
  description: 'Search the web with MillionShort, leaving out the 1,000 most popular sites.',
  parametersJsonSchema: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] },
}] }] };
const ai = new GoogleGenAI({});
const contents: Content[] = [{ role: 'user', parts: [{ text: 'Find independent blogs about home espresso.' }] }];
while (true) {
  const response = await ai.models.generateContent({ model: 'gemini-4-hydrogen', contents, config });
  const calls = response.functionCalls ?? [];
  if (calls.length === 0 || !response.candidates?.[0]?.content) {
    console.log(response.text);
    break;
  }
  contents.push(response.candidates[0].content);
  const parts = [];
  for (const call of calls) {
    const result = await millionshortSearch(String(call.args?.query));
    parts.push({ functionResponse: { name: call.name, id: call.id, response: { result } } });
  }
  contents.push({ role: 'user', parts });
}
```

The Python SDK builds the tool's schema from the type hints and the docstring, so keep both.

## 3. Tell it when to search

Google Search is a separate tool that runs only when you add it to `tools`, so leave it out. Then put a line like this in the system instruction (`system_instruction` in `GenerateContentConfig`, `systemInstruction` in the TypeScript config):

> Use the MillionShort `search` tool for anything recent, niche, or that needs a source. To reach lesser-known sites, set `remove_top_sites` (for example 1000). Cite the URLs it returns.

## 4. Check it works

Run the example, then ask:

> Search MillionShort for forum threads about restoring a cast iron skillet, with the 1,000 most popular sites removed. List the five most useful with their links.

In TypeScript, `response.functionCalls` on the first turn names `millionshort_search` with a `query`. In Python, `response.automatic_function_calling_history` holds the calls the SDK made for the model.

## With MCP: the hosted server

Open an MCP session to our server and pass it in `tools`; the SDK lists the tools and calls them for the model. Google marks this experimental. With MCP Python SDK 2.x, the headers go on the `httpx2` client. Without a key, leave the headers out.

```python Python
import asyncio
import os

import httpx2
from google import genai
from google.genai import types
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client


async def main():
    headers = {"Authorization": f"Bearer {os.environ['MILLIONSHORT_API_KEY']}"}
    async with httpx2.AsyncClient(headers=headers, timeout=httpx2.Timeout(30.0, read=300.0)) as http:
        async with streamable_http_client("https://mcp.millionshort.com/mcp", http_client=http) as (read, write):
            async with ClientSession(read, write) as session:
                await session.initialize()
                response = await genai.Client().aio.models.generate_content(
                    model="gemini-4-hydrogen",
                    contents="Find independent blogs about home espresso.",
                    config=types.GenerateContentConfig(tools=[session]),
                )
                print(response.text)


asyncio.run(main())
```

```ts TypeScript
import { GoogleGenAI, mcpToTool } from '@google/genai';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';

const transport = new StreamableHTTPClientTransport(new URL('https://mcp.millionshort.com/mcp'), {
  requestInit: { headers: { Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}` } },
});
const mcp = new Client({ name: 'millionshort-example', version: '1.0.0' });
await mcp.connect(transport);

const response = await new GoogleGenAI({}).models.generateContent({
  model: 'gemini-4-hydrogen',
  contents: 'Find independent blogs about home espresso.',
  config: { tools: [mcpToTool(mcp)] },
});
console.log(response.text);
await mcp.close();
```

The TypeScript SDK's README says automatic function calling from `generateContent` will move to its `Chats` module in a future major version; if this stops calling tools after an upgrade, use `ai.chats.create` with the same `config`.

## MCP configuration

The same address for every client: `https://mcp.millionshort.com/mcp`, streamable HTTP.

| Mode | How | What the agent gets |
|---|---|---|
| API key | Send `Authorization: Bearer ms-YOUR_API_KEY` | Every tool, at your plan's limits; calls use your credits |
| No key | Send no `Authorization` header | `search`, `list_sources` and a few more; one source and up to 5 results a search, 10 free searches a day |

## Tools

| Tool | What it does | Without a key | Cost |
|---|---|---|---|
| `search` | Searches the web and the specialist sources, with the popularity, domain, page-type, topic, site and date filters | Yes: one source, up to 5 results | 1 credit per source searched, first 10 results |
| `get_domain_info` | Popularity and risk for up to 25 sites | No | 1 credit |
| `list_sources` | The sources, page types and topics `search` accepts | Yes: source names | Free |
| The tools of the other endpoints | `extract`, `map`, `crawl`, `places` and more: [the MCP page](https://millionshort.com/docs/mcp#tools) lists them | A few, such as `places` | What the API call behind each costs |

The function tool in step 2 is `search` alone; the MCP session gives the model every tool of the server.

## Settings

| Variable | Meaning |
|---|---|
| `MILLIONSHORT_API_KEY` | Your key, read by the examples above |
| GEMINI_API_KEY | Your Gemini key, read by the SDK |

## Costs and limits

A tool call costs what the API call behind it costs: 1 credit per source searched for the first 10 results, 1 credit for a domain lookup, nothing for the list of sources, the price of the endpoint for the other tools, and nothing at all in the no-key mode. An agent that loops can make many calls: give it a step limit, and ask for fewer results when a few will do. [Credits and limits](https://millionshort.com/docs/credits-and-limits) has the numbers.

## When it fails

| What you see | Why | Fix |
|---|---|---|
| `401 AUTH_MISSING_KEY` or `AUTH_INVALID_KEY` | The key is missing or wrong | Set `MILLIONSHORT_API_KEY`; keys start with `ms-` |
| `400 INVALID_PARAM` | A field name or value the API does not take | The `message` names the field; the [search reference](https://millionshort.com/docs/search/parameters) lists them all |
| `429 RATE_LIMITED` or `CAPACITY` | Too many calls a minute, or no free capacity right now | Wait the `Retry-After` seconds, then retry |
| `429 INSUFFICIENT_CREDITS` | The plan's credits are used up | Stop and add credits; do not retry |
| The model answers without calling the tool | Nothing told it when to search, or the function has no docstring for the Python SDK to read | Add the line from step 3, and keep the docstring |
| `streamable_http_client()` rejects `headers` | MCP Python SDK 2.x moved headers to the `httpx2` client | Pass `http_client=` as in the MCP example |

## Related

- [Agent tool use](https://millionshort.com/docs/search/guides/agent-tool-use): when to give a model tools, and what to tell it.
- [Gemini CLI](https://millionshort.com/docs/integrations/gemini-cli) and [Antigravity](https://millionshort.com/docs/integrations/antigravity): the same server in Google's agents.
- Other model APIs: [OpenAI](https://millionshort.com/docs/integrations/openai), [Anthropic](https://millionshort.com/docs/integrations/anthropic), [OpenRouter](https://millionshort.com/docs/integrations/openrouter), [Ollama](https://millionshort.com/docs/integrations/ollama).
- [Search API reference](https://millionshort.com/docs/search/parameters) and [MCP server](https://millionshort.com/docs/mcp).
- Google's own documentation, read on 2026-11-19: [Function calling](https://aistudio.google.com/docs/function-calling?generate-content=true), [Google Gen AI Python SDK](https://github.com/googleapis/python-genai), [Google Gen AI JavaScript SDK](https://github.com/googleapis/js-genai).
