Menu

Integrations / Frameworks & SDKs

DSPy

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

Copy as MarkdownOpen in ChatGPT (opens in a new tab)Open in Claude (opens in a new tab)

RecipePythonNothing of ours to installWorks with no keyChecked 2026-11-19

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 lists them), the MCP Python SDK connects to it and dspy.Tool.from_mcp_tool converts them.

1Install

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; an agent can ask for a trial key by itself.

2Minimal example

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

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)

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

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

ModeHowWhat the agent gets
API keySend Authorization: Bearer ms-YOUR_API_KEYEvery tool, at your plan's limits; calls use your credits
No keySend no Authorization headersearch, 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 you choose to add. Over MCP, the agent gets the server's tools:

ToolWhat it doesWithout a keyCost
searchSearches the web and the specialist sources, with the popularity, domain, page-type, topic, site and date filtersYes: one source, up to 5 results1 credit per source searched, first 10 results
get_domain_infoPopularity and risk for up to 25 sitesNo1 credit
list_sourcesThe sources, page types and topics search acceptsYes: source namesFree
The tools of the other endpointsextract, map, crawl, places and more: the MCP page lists themA few, such as placesWhat the API call behind each costs

Settings

VariableMeaning
MILLIONSHORT_API_KEYYour 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 has the numbers.

When it fails

What you seeWhyFix
401 AUTH_MISSING_KEY or AUTH_INVALID_KEYThe key is missing or wrongSet MILLIONSHORT_API_KEY; keys start with ms-
400 INVALID_PARAMA field name or value the API does not takeThe message names the field; the search reference lists them all
429 RATE_LIMITED or CAPACITYToo many calls a minute, or no free capacity right nowWait the Retry-After seconds, then retry
429 INSUFFICIENT_CREDITSThe plan's credits are used upStop 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 clientPut the header on httpx2.AsyncClient and pass it as http_client, as above
An MCP tool call fails with a read timeoutThe httpx2.AsyncClient was built without a timeout and kept the 5-second defaultPass timeout=httpx2.Timeout(30.0, read=300.0)
The agent runs, but MCP tools fail or never returnThe agent was called with react(...), or after the async with block closedCall await react.acall(...) inside the block

This page as Markdown ยท llms.txt