# DSPy

MillionShort search for DSPy programs, as a function tool for dspy.ReAct or as the MCP server's tools.

Recipe · Python · 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.

DSPy has no MCP client of its own, and needs none: `dspy.ReAct` takes plain Python functions as tools, so a short function that calls the MillionShort API is the simplest way in. If you would rather have the server's own 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), the MCP Python SDK connects to it and `dspy.Tool.from_mcp_tool` converts them.

## 1. Install

```bash Python
pip install "dspy[mcp]"
export MILLIONSHORT_API_KEY=ms-YOUR_API_KEY
```

The `mcp` extra adds the MCP Python SDK, which only the MCP way needs. The examples use an OpenAI model through `dspy.LM`, which reads your OpenAI key from OPENAI_API_KEY; any model DSPy supports works the same way. 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. Minimal example

A plain function is a tool: DSPy reads its name, type hints and docstring to tell the model how to call it.

```python Python
import json
import os
import urllib.request

import dspy

dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))


def millionshort_search(query: str, remove_top_sites: int = 1000, num_results: int = 5) -> str:
    """Search the web with MillionShort. remove_top_sites leaves out the N most popular sites."""
    request = urllib.request.Request(
        "https://api.millionshort.com/v1/search",
        data=json.dumps({"query": query, "remove_top_sites": remove_top_sites, "num_results": num_results}).encode(),
        headers={"Authorization": "Bearer " + os.environ["MILLIONSHORT_API_KEY"], "Content-Type": "application/json"},
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        results = json.load(response)["data"]["results"]
    return json.dumps([{"title": r["title"], "url": r["url"], "snippet": r.get("snippet")} for r in results])


react = dspy.ReAct("question -> answer", tools=[millionshort_search])
print(react(question="Find independent blogs about home espresso, without the 1,000 most popular sites.").answer)
```

## 3. Give the tools to an agent

`dspy.ReAct` takes a signature and a list of tools. The signature can be a string, as above, or a `dspy.Signature` class whose docstring says when to search:

```python Python
import dspy


class Research(dspy.Signature):
    """Use millionshort_search for anything recent or niche, and cite the URLs it returns."""

    question: str = dspy.InputField()
    answer: str = dspy.OutputField(desc="the answer, with the URLs it is based on")
```

Then `dspy.ReAct(Research, tools=[millionshort_search], max_iters=5)`. `max_iters` caps the number of tool-calling turns (20 by default), so a looping program cannot run up many searches. DSPy has no web search of its own: the agent has only the tools you pass.

## 4. Check it works

Run the example: the answer should cite pages. The prediction keeps the run, so you can see the call to `millionshort_search` and what it returned. Add these lines to the end of the example:

```python Python
result = react(question="Find independent blogs about home espresso.")
print(result.termination_reason)  # "submit" when the agent finished normally
print(result.history)  # each turn's tool calls and their results
```

If the model answers from memory, say when to search in the signature's docstring:

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

## With MCP: the server's tools

The MCP Python SDK (version 2) connects to the server. The key goes on the `httpx2.AsyncClient` you hand to the transport, with the SDK's own timeouts. MCP tools are async, so call the agent with `acall`, inside the open connection.

```python Python
import asyncio
import os

import dspy
import httpx2
from mcp import Client
from mcp.client.streamable_http import streamable_http_client

dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))


async def main():
    async with httpx2.AsyncClient(
        headers={"Authorization": f"Bearer {os.environ['MILLIONSHORT_API_KEY']}"},
        timeout=httpx2.Timeout(30.0, read=300.0),
    ) as http_client:
        async with Client(streamable_http_client("https://mcp.millionshort.com/mcp", http_client=http_client)) as client:
            listed = await client.list_tools()
            tools = [dspy.Tool.from_mcp_tool(client, tool) for tool in listed.tools]
            print([tool.name for tool in tools])  # search, get_domain_info, list_sources, ...
            react = dspy.ReAct("question -> answer", tools=tools)
            result = await react.acall(question="Find independent blogs about home espresso.")
            print(result.answer)


asyncio.run(main())
```

Without a key, skip the `httpx2.AsyncClient` and pass the address alone: `Client("https://mcp.millionshort.com/mcp")`. The agent then gets `search` and `list_sources`.

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

The function tool above calls `POST /v1/search` and takes any field of the [search reference](https://millionshort.com/docs/search/parameters) you choose to add. Over MCP, the agent gets the server's 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. Over MCP, 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 |
|---|---|---|
| `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 |
| `streamable_http_client() got an unexpected keyword argument 'headers'` | Version 2 of the MCP Python SDK moved headers and timeouts to the HTTP client | Put the header on `httpx2.AsyncClient` and pass it as `http_client`, as above |
| An MCP tool call fails with a read timeout | The `httpx2.AsyncClient` was built without a timeout and kept the 5-second default | Pass `timeout=httpx2.Timeout(30.0, read=300.0)` |
| The agent runs, but MCP tools fail or never return | The agent was called with `react(...)`, or after the `async with` block closed | Call `await react.acall(...)` inside the block |

## Related

- [Agent tool use](https://millionshort.com/docs/search/guides/agent-tool-use): when to give a model tools, and what to tell it.
- [Search reference](https://millionshort.com/docs/search/parameters): every field the function tool can pass.
- [Haystack](https://millionshort.com/docs/integrations/haystack) and [smolagents](https://millionshort.com/docs/integrations/smolagents): the same search in other Python frameworks.
- [MCP server](https://millionshort.com/docs/mcp) and [Filters for agents](https://millionshort.com/docs/search/filters).
- The products' own documentation, read on 2026-11-19: [DSPy and MCP](https://dspy.ai/tutorials/mcp/), [MCP Python SDK client transports](https://py.sdk.modelcontextprotocol.io/client/transports/).
