# xAI

MillionShort search for Grok models, as a remote MCP tool in the xAI API or a function tool, in Python and TypeScript.

MCP · 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 xAI API connects to the MillionShort MCP server for you: list it as an `mcp` tool and xAI lists and calls the server's tools (`search`, `get_domain_info`, `list_sources` and the tools of the other endpoints; [the MCP page](https://millionshort.com/docs/mcp#tools) lists them all) while Grok works. It works through the OpenAI SDK pointed at xAI, and through xAI's own Python SDK. For a loop you run yourself, a function tool that calls our API does the same job.

## 1. Install

```bash Python
pip install openai xai-sdk requests
export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
```

```bash TypeScript
npm install openai
export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
```

The examples read your xAI key from XAI_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. `xai-sdk` is only for step 4 and `requests` only for the function tool.

## 2. Connect the server

The key goes in the tool's `headers` as a bearer header. xAI also has an `authorization` field that sets the `Authorization` header, but its docs do not say whether it adds `Bearer ` itself, so the header is written out here. The key travels with each request to xAI: use one you can revoke. Without a key, leave `headers` out.

```python Python
import os

from openai import OpenAI

client = OpenAI(api_key=os.environ["XAI_API_KEY"], base_url="https://api.x.ai/v1")
response = client.responses.create(
    model="grok-4.7",
    input="Find independent blogs about home espresso, without the 1,000 most popular sites.",
    tools=[
        {
            "type": "mcp",
            "server_label": "millionshort",
            "server_description": "Web search that can leave out the most popular sites.",
            "server_url": "https://mcp.millionshort.com/mcp",
            "headers": {"Authorization": f"Bearer {os.environ['MILLIONSHORT_API_KEY']}"},
        }
    ],
)
print(response.output_text)
```

```ts TypeScript
import OpenAI from 'openai';

const client = new OpenAI({ apiKey: process.env.XAI_API_KEY, baseURL: 'https://api.x.ai/v1' });
const response = await client.responses.create({
  model: 'grok-4.7',
  input: 'Find independent blogs about home espresso, without the 1,000 most popular sites.',
  tools: [
    {
      type: 'mcp',
      server_label: 'millionshort',
      server_description: 'Web search that can leave out the most popular sites.',
      server_url: 'https://mcp.millionshort.com/mcp',
      headers: { Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}` },
    },
  ],
});
console.log(response.output_text);
```

xAI does not support `require_approval` (or `connector_id`), so leave it out: calls run without asking. Most of the tools only read; `crawl` spends credits, `crawl_cancel` stops a crawl and `create_space` saves a Space, so tell the model in its instructions when it may use those. xAI makes the calls from its own servers, over streamable HTTP, so our server must be reachable from the internet, which it is.

## 3. Tell it when to search

Grok's web search and X search are server-side tools that run only when you list them in `tools`, so leave them out. Then add a line like this to the conversation as a system message:

> 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.

To offer only some of the tools, add `"allowed_tools": ["search", "list_sources"]` to the `mcp` tool (`allowed_tool_names` in xAI's own SDK).

## 4. Check it works

xAI's own SDK shows each server-side tool call as it happens. The same server, with the key in `extra_headers`:

```python Python
import os

from xai_sdk import Client
from xai_sdk.chat import user
from xai_sdk.tools import mcp

client = Client(api_key=os.environ["XAI_API_KEY"])
server = mcp(
    server_url="https://mcp.millionshort.com/mcp",
    server_label="millionshort",
    extra_headers={"Authorization": f"Bearer {os.environ['MILLIONSHORT_API_KEY']}"},
)
chat = client.chat.create(model="grok-4.7", tools=[server])
chat.append(user("Search MillionShort for home espresso blogs."))
for response, chunk in chat.stream():
    for call in chunk.tool_calls:
        print("calling", call.function.name, call.function.arguments)
    print(chunk.content, end="")
```

Expect a call to `search` before the answer. To try it, 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.

## Without MCP: a function tool

Your code runs the search; each round sends the results back with `previous_response_id`, until the model stops asking.

```python Python
import json
import os

import requests
from openai import OpenAI


def millionshort_search(query: str) -> str:
    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"]])


tools = [{
    "type": "function",
    "name": "millionshort_search",
    "description": "Search the web with MillionShort, leaving out the 1,000 most popular sites.",
    "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]},
}]
client = OpenAI(api_key=os.environ["XAI_API_KEY"], base_url="https://api.x.ai/v1")
response = client.responses.create(model="grok-4.7", input="Find independent blogs about home espresso.", tools=tools)
while calls := [item for item in response.output if item.type == "function_call"]:
    outputs = [{"type": "function_call_output", "call_id": c.call_id, "output": millionshort_search(**json.loads(c.arguments))} for c in calls]
    response = client.responses.create(model="grok-4.7", input=outputs, tools=tools, previous_response_id=response.id)
print(response.output_text)
```

```ts TypeScript
import OpenAI from 'openai';

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 tools: OpenAI.Responses.Tool[] = [{
  type: 'function',
  name: 'millionshort_search',
  description: 'Search the web with MillionShort, leaving out the 1,000 most popular sites.',
  parameters: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] },
  strict: false,
}];
const client = new OpenAI({ apiKey: process.env.XAI_API_KEY, baseURL: 'https://api.x.ai/v1' });
let response = await client.responses.create({ model: 'grok-4.7', input: 'Find independent blogs about home espresso.', tools });
for (;;) {
  const calls = response.output.filter((item) => item.type === 'function_call');
  if (calls.length === 0) break;
  const input: OpenAI.Responses.ResponseInput = [];
  for (const call of calls) {
    input.push({ type: 'function_call_output', call_id: call.call_id, output: await millionshortSearch(JSON.parse(call.arguments).query) });
  }
  response = await client.responses.create({ model: 'grok-4.7', input, tools, previous_response_id: response.id });
}
console.log(response.output_text);
```

## 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 |

## Settings

| Variable | Meaning |
|---|---|
| `MILLIONSHORT_API_KEY` | Your key, read by the examples above. Leave the header out for the no-key mode |
| XAI_API_KEY | Your xAI key, read by the examples above |

## 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 |
|---|---|---|
| The server does not connect, or no tools are listed | The address or the transport is not the one the server speaks | Use exactly `https://mcp.millionshort.com/mcp` and the streamable HTTP transport (often called `http`), not SSE |
| `401` or "unauthorized" | The key is wrong, or it was sent without `Bearer ` | Send `Authorization: Bearer ms-...`, or leave the header out to use the no-key mode |
| "10 free searches a day without a key" | The no-key mode's daily searches are used up | Add a key: it is free in the [dashboard](https://millionshort.com/app/) |
| `INSUFFICIENT_CREDITS` | The plan's credits are used up | Stop and add credits; retrying does not help |
| The agent answers from memory, or uses another search | Nothing told it when to use this one | Turn off its own search where it can be (this page says how), and add the line for its instructions |
| The MCP tool fails, the function tool works | xAI's servers could not reach ours | Try again, or use the function tool |

## Related

- [Agent tool use](https://millionshort.com/docs/search/guides/agent-tool-use): when to give a model tools, and what to tell it.
- [Grok Build](https://millionshort.com/docs/integrations/grok-build): the same server in xAI's coding agent.
- Other model APIs: [OpenAI](https://millionshort.com/docs/integrations/openai) (the same `mcp` tool), [Groq](https://millionshort.com/docs/integrations/groq), [Anthropic](https://millionshort.com/docs/integrations/anthropic).
- [MCP server](https://millionshort.com/docs/mcp) and [Filters for agents](https://millionshort.com/docs/search/filters).
- xAI's own documentation, read on 2026-11-19: [Remote MCP Tools](https://docs.x.ai/developers/tools/remote-mcp), [Function Calling](https://docs.x.ai/developers/tools/function-calling).
