# LiveKit Agents

MillionShort search inside a LiveKit voice agent, through the hosted MCP server or a function tool, in Python and Node.js.

MCP · Python and Node.js · 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.

LiveKit Agents connects to the MillionShort MCP server itself: wrap the server in an `MCPToolset` and pass it in the agent's `tools`. The voice agent then gets the server's tools ([the MCP page](https://millionshort.com/docs/mcp#tools) lists them). With no MCP at all, a function tool that calls the API does the same job.

Spoken answers work best with few results: ask for `num_results` 3 and `max_highlights` 1, so the model reads short passages rather than long text. Each search also adds a little latency to the turn it runs in.

## 1. Install

```bash Python
pip install "livekit-agents[mcp]~=1.8" httpx
export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
```

```bash TypeScript
npm install @livekit/agents @modelcontextprotocol/client zod
export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
```

`httpx` is only for the function tool further down. The Node.js MCP client needs Node.js 20 or later. Start from LiveKit's own starter project (`lk agent init`) for the rest of the agent: the room, the speech models and the LiveKit keys. 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.

## 2. Connect the server

Pass an `MCPToolset` to the agent. Without a key, leave the headers out.

```python Python
import os

from livekit import agents
from livekit.agents import Agent, AgentServer, AgentSession, inference, mcp


class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(
            instructions="You are a voice assistant. For anything recent or niche, call the millionshort search tool "
            "with num_results 3 and max_highlights 1, then answer in two or three short sentences.",
            tools=[
                mcp.MCPToolset(
                    id="millionshort",
                    mcp_server=mcp.MCPServerHTTP(
                        "https://mcp.millionshort.com/mcp",
                        transport_type="streamable_http",
                        headers={"Authorization": f"Bearer {os.environ['MILLIONSHORT_API_KEY']}"},
                    ),
                )
            ],
        )


server = AgentServer()


@server.rtc_session(agent_name="my-agent")
async def my_agent(ctx: agents.JobContext):
    session = AgentSession(
        stt=inference.STT(model="assemblyai/assemblyai-stt-3-7-realtime-agent", language="en"),
        llm=inference.LLM(model="google/gemma-4-31b-it"),
        tts=inference.TTS(model="fishaudio/s2.1-pro", voice="fa4c9eb3dccc4806b382b40d61c6b10a"),
    )
    await session.start(room=ctx.room, agent=Assistant())


if __name__ == "__main__":
    agents.cli.run_app(server)
```

```ts TypeScript
import { llm, voice } from '@livekit/agents';

// agent.ts in LiveKit's Node.js starter: the session in main.ts starts this agent.
export function createAgent() {
  return voice.Agent.create({
    instructions:
      'You are a voice assistant. For anything recent or niche, call the millionshort search tool ' +
      'with num_results 3 and max_highlights 1, then answer in two or three short sentences.',
    tools: [
      new llm.MCPToolset({
        id: 'millionshort',
        mcpServer: new llm.MCPServerHTTP({
          url: 'https://mcp.millionshort.com/mcp',
          transportType: 'streamable_http',
          headers: { Authorization: `Bearer ${process.env.MILLIONSHORT_API_KEY}` },
        }),
      }),
    ],
  });
}
```

The speech and language models are the ones in LiveKit's quickstart; any model that can call tools works. LiveKit picks streamable HTTP for an address that ends in `/mcp`; `transport_type` says so explicitly.

## 3. Give the tools to every agent in a session

A toolset on an `Agent` closes when the session hands over to another agent. To keep search across handoffs, put the same `MCPToolset` in the `tools` of the `AgentSession` instead. To offer only `search`, add `allowed_tools=["search"]` to `MCPServerHTTP` (`allowedTools` in Node.js).

## 4. Check it works

Run the agent with `lk agent dev`, open the Agent Console link it prints, and ask a question that needs the web. The console's tool panes show each tool call: you should see `search`, and the answer should name pages it found. If one MCP server fails to connect, LiveKit logs the error and starts the agent without its tools, so read the log when no tool call appears.

If the model answers from memory, say when to search in its instructions:

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

## Without MCP: a function tool

A function tool that calls `POST /v1/search` pins the result count and the highlights, so the model cannot ask for more than a spoken answer needs:

```python Python
import os
from typing import Any

import httpx
from livekit.agents import Agent, RunContext, function_tool


class Assistant(Agent):
    def __init__(self) -> None:
        super().__init__(instructions="You are a voice assistant. Use millionshort_search for anything recent or niche.")

    @function_tool()
    async def millionshort_search(self, context: RunContext, query: str) -> dict[str, Any]:
        """Search the web with MillionShort, leaving out the 1,000 most popular sites.

        Args:
            query: What to search for.
        """
        async with httpx.AsyncClient(timeout=15) as http:
            response = await http.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": 3, "max_highlights": 1},
            )
            response.raise_for_status()
        results = response.json()["data"]["results"]
        return {"results": [{"title": r["title"], "url": r["url"], "highlights": r.get("highlights")} for r in results]}
```

```ts TypeScript
import { llm, voice } from '@livekit/agents';
import { z } from 'zod';

const millionshortSearch = llm.tool({
  name: 'millionshort_search',
  description: 'Search the web with MillionShort, leaving out the 1,000 most popular sites.',
  parameters: z.object({ query: z.string().describe('What to search for.') }),
  execute: async ({ query }) => {
    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: 3, max_highlights: 1 }),
    });
    if (!res.ok) throw new Error(`search failed: ${res.status}`);
    const { data } = (await res.json()) as { data: { results: { title: string; url: string; highlights?: string[] }[] } };
    return data.results.map(({ title, url, highlights }) => ({ title, url, highlights }));
  },
});

export const agent = voice.Agent.create({
  instructions: 'You are a voice assistant. Use millionshort_search for anything recent or niche.',
  tools: [millionshortSearch],
});
```

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

## 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 agent talks but never searches, and the log shows a connection error | A server that fails to connect does not stop the agent; it starts without those tools | Check the address and the key in the log line, then restart the agent |
| Node.js refuses the address | `MCPServerHTTP` in Node.js takes `https:` addresses only | Use `https://mcp.millionshort.com/mcp` exactly as written |
| Long pauses before spoken answers | Many results or long text for the model to read | Ask for `num_results` 3 and `max_highlights` 1, or use the function tool, which pins both |

## Related

- [Pipecat](https://millionshort.com/docs/integrations/pipecat), [Vapi](https://millionshort.com/docs/integrations/vapi) and [ElevenLabs Agents](https://millionshort.com/docs/integrations/elevenlabs): the same server in other voice agents.
- [Agent tool use](https://millionshort.com/docs/search/guides/agent-tool-use): when to give a model tools, and what to tell it.
- [MCP server](https://millionshort.com/docs/mcp) and [Filters for agents](https://millionshort.com/docs/search/filters).
- LiveKit's own documentation, read on 2026-11-19: [Model Context Protocol](https://docs.livekit.io/agents/logic/tools/mcp/), [Function tools](https://docs.livekit.io/agents/logic/tools/definition/), [Voice AI quickstart](https://docs.livekit.io/agents/start/voice-ai-quickstart/).
