brave-client
An async Python client for Brave Search, providing streaming AI answers and structured web search in a single, typed interface - with a built-in Model Context Protocol (MCP) server. Requests are made by a real anti-detect browser.
Unofficial. brave-client is not affiliated with or endorsed by Brave Software. It talks to the web endpoints behind search.brave.com, which are undocumented and can change without notice. Use it in line with Brave's terms of service. If you need a supported interface, see Brave's official Search API.
About this project
brave-client is a re-implementation of brave-api-python by iqbalmh18 (MIT). The public API, the typed models, the conversation and streaming logic, and the MCP server come from that project and keep the same names and behavior. What changed is how requests reach Brave.
Why it exists. The original client sends its requests with curl_cffi
and a Chrome TLS fingerprint. At the time of writing, Brave answers that
client with HTTP 403 on the /ask/__data.json endpoint, which the client needs to get
started, so every call fails. The same request made from inside a real browser
page succeeds. brave-client therefore runs every request as fetch() inside a
ShardX anti-detect browser.
What is different
| brave-api-python | brave-client | |
|---|---|---|
| HTTP engine | curl_cffi AsyncSession |
fetch() inside a ShardX browser page |
| Fingerprint | Chrome TLS profile imitated by curl_cffi |
A real browser profile, matched to the host OS and its network |
| Extra setup | none | one-off browser download: brave-client install |
| Dependencies | curl-cffi |
shardx (brings patchright) |
| Proxies | rotated per request | rotated per browser session (one proxy per launch) |
| On a 4xx response | the error is raised after retries | a fresh session (new profile, next proxy) is started and the request is retried, up to max_retries times |
| Headers | a fixed set of browser-like headers is sent | none are forced; the browser sends its own |
impersonate, user_agent options |
used | removed (passing them raises a validation error) |
| New option | none | headless (default True) |
| Proxy schemes | http, https, socks4, socks4a, socks5, socks5h |
http, https, socks5 (socks5h is treated as socks5); socks4 is rejected |
| Start-up and memory | negligible | a browser is launched per session (a few seconds, more memory) |
| Package, import and commands | brave-api-python, brave_api, brave-api-mcp |
brave-client, brave_client, brave-client-mcp |
| Documentation | Read the Docs site | this README and examples/ |
A few details worth knowing:
- Each browser session uses a temporary profile for the OS it runs on (Windows, macOS or Linux), and the profile is deleted when the session ends.
- A proxy that fails to start or fails mid-request is dropped from the rotation. When none is left, or none is configured, a direct connection is used.
- Only 4xx responses and transport failures trigger a new session. A 5xx response or a failure after a stream has already produced data is raised as it is, so a streamed answer is never silently replayed.
- Exceptions, models and method signatures are unchanged.
Features
- Async Brave Ask client with blocking and streaming responses
- Multi-turn conversations and multimodal image input
- Structured search for web, images, news, videos, and Brave Goggles
- Pagination, autocomplete suggestions, and typed Pydantic models
- Configurable language, region, safe search, timeout, retries, and proxies
- Real-browser transport with automatic session and proxy rotation
- FastMCP server with stdio and HTTP transports
Installation
Requires Python 3.11+.
uv add brave-client
For MCP support:
uv add "brave-client[mcp]"
With pip:
pip install brave-client
Install the browser engine
The client drives the ShardX browser, which is downloaded separately. Run this once after installing the package:
brave-client install
The command:
- runs
shardx installto download the browser engine - launches the browser once on a temporary profile for your OS
- loads
https://httpbin.org/headersto prove the browser works - prints the result and deletes the profile
It exits with a non-zero status if any step fails, so it also works as a check in CI or a Dockerfile.
From source:
git clone https://github.com/Coding-Doctor-Omar/brave-client.git
cd brave-client
uv sync --group dev
uv run brave-client install
Quick start
Ask
import asyncio
from brave_client import BraveClient
async def main() -> None:
async with BraveClient() as client:
result = await client.ask("What is quantum computing?")
print(result.text)
print(f"Sources: {len(result.urls)}")
asyncio.run(main())
Search
async with BraveClient() as client:
result = await client.search("Python asyncio tutorial")
for item in result.web[:3]:
print(item.title, item.url)
All public methods are asynchronous and should normally be used inside
async with BraveClient(). The browser starts when the client opens and is
closed (and its profile deleted) when the block exits.
Search verticals
Every search method returns the same SearchResult response envelope:
async with BraveClient() as client:
web = await client.search("Python asyncio")
images = await client.search_images("Python logo")
news = await client.search_news("Python release")
videos = await client.search_videos("Python tutorial")
goggles = await client.search_goggles("privacy search")
print(web.web)
print(images.images)
print(news.news)
print(videos.videos)
print(goggles.web)
Pagination uses Brave's page-based offset value, where 0 is the first page:
async with BraveClient() as client:
first_page = await client.search_news("Python release", offset=0)
second_page = await client.search_news("Python release", offset=1)
Use spellcheck=False for exact keyword matching. Use client.suggest() for
autocomplete suggestions.
Streaming
from brave_client import BraveClient, StreamEventType
async with BraveClient() as client:
async for event in client.ask_stream("Explain WebAssembly"):
if event.type is StreamEventType.TEXT_DELTA:
print(event.delta, end="", flush=True)
Configuration
from brave_client import BraveClient, ClientConfig
config = ClientConfig(
language="id",
ui_lang="id-id",
country="id",
safesearch="moderate",
timeout=60.0,
max_retries=3,
proxies=["http://user:password@proxy.example:8080"],
)
async with BraveClient(config) as client:
result = await client.search("berita teknologi")
ClientConfig is immutable and validates its values.
| Option | Default | Description |
|---|---|---|
base_url |
https://search.brave.com |
Base URL of Brave Search |
language |
en |
Response language code (BCP-47) |
ui_lang |
en-us |
UI language |
country |
us |
ISO 3166-1 alpha-2 country code |
geoloc |
0x0 |
Location as lat x lng, e.g. -6.2x106.8 |
safesearch |
moderate |
off, moderate or strict |
force_safesearch |
False |
Force safe search regardless of user settings |
units_of_measurement |
metric |
metric or imperial |
use_location |
True |
Use the configured location for results |
source |
home |
Traffic source hint sent to Brave |
enable_research |
False |
Enable deep research mode |
premium_cookie_name |
__Secure-sku#brave-search-premium |
Cookie name for Brave Premium |
timeout |
120.0 |
Timeout of each non-streaming request, in seconds |
stream_timeout |
None |
Timeout of a streaming request; None means unlimited |
max_retries |
3 |
Retries for failed requests, and the maximum number of session rotations per call |
retry_backoff |
1.5 |
Base retry backoff in seconds (grows exponentially) |
retry_jitter |
True |
Add random jitter to each backoff delay |
max_concurrent |
5 |
Maximum number of concurrent requests |
extra_headers |
{} |
Extra headers for every request; headers the browser controls (User-Agent, Origin, Sec-*, ...) are ignored by it |
proxies |
[] |
Proxy URLs, one per browser session (see below) |
headless |
True |
Run the browser without a visible window |
Proxies
config = ClientConfig(
proxies=[
"http://user:password@proxy-1.example:8080",
"socks5://proxy-2.example:1080",
]
)
A browser is bound to one proxy when it starts, so proxies rotate when a
new session starts: on a 4xx response, when the browser is lost, or when a
proxy fails. Failed proxies are removed from the rotation, and a direct
connection is the last resort. Supported schemes are http, https and
socks5; each URL needs a host and a port.
Running headless, or not
headless=True (the default) needs no display, so it suits servers and
containers. headless=False shows the window; on a Linux server it needs a
virtual display such as xvfb.
Errors
All exceptions derive from BraveAPIError:
| Exception | Raised when |
|---|---|
TransportError |
a network-level failure: connection refused or reset, timeout, DNS, TLS, or a lost browser |
HTTPStatusError |
the server responded with a non-2xx status; carries status_code and response_text |
ResponseParseError |
the response body was not valid JSON or had an unexpected shape |
TokenExtractionError |
the auth token could not be found in the payload |
ConversationError |
the conversation endpoint did not return a usable conversation id |
StreamAbortedError |
the server sent an error event while the stream was being consumed |
ChallengeRequiredError |
the server raised a CAPTCHA challenge that must be solved manually |
See examples/errors.py for handling each of them.
MCP server
Install the optional MCP dependency:
uv add "brave-client[mcp]"
Run locally over stdio:
brave-client-mcp
Or run an HTTP server:
brave-client-mcp --http --host 127.0.0.1 --port 8000
Available search tools include search, search_images, search_news,
search_videos, search_goggles, and suggest, in addition to ask.
The server is configured with environment variables: BRAVE_BASE_URL,
BRAVE_COUNTRY, BRAVE_LANGUAGE, BRAVE_UI_LANG, BRAVE_GEOLOC,
BRAVE_SAFESEARCH, BRAVE_ENABLE_RESEARCH, BRAVE_REQUEST_TIMEOUT,
BRAVE_STREAM_TIMEOUT, BRAVE_MAX_RETRIES, BRAVE_MAX_CONCURRENT,
BRAVE_HEADLESS and BRAVE_PROXY_LIST (comma-separated proxy URLs).
Migrating from brave-api-python
- Replace the package:
pip uninstall brave-api-python && pip install brave-client - Change imports from
brave_apitobrave_client. Class and exception names are unchanged (BraveClient,ClientConfig,BraveAPIError, ...). - Run
brave-client installonce on every machine or image. - Rename the MCP command from
brave-api-mcptobrave-client-mcp. The environment variables are the same, plusBRAVE_HEADLESS. - Remove
impersonateanduser_agentfrom your config (they are no longer accepted), and replace anysocks4proxy.
Examples
Runnable examples are available in examples/:
quickstart.py— minimal asksearch_verticals.py— all search verticals and paginationsearch_suggest.py— web search and autocompletestreaming.py— streaming eventsmulti_turn.py— resume, follow-up and regeneratemultimodal.py— image inputconfiguration.py— configuration and proxieserrors.py— the exception hierarchyconcurrency.py— parallel queries on one client
The examples call the live Brave endpoints. Run one with:
uv run python examples/search_verticals.py
Development
uv sync --group dev --extra mcp
uv run pytest # unit tests; integration tests are opt-in
uv run pytest -m integration # live tests, need the browser engine and network
uv run ruff check .
uv run ruff format --check .
uv run pyright
See CONTRIBUTING.md for the project layout and guidelines.
Credits
brave-client builds on brave-api-python by iqbalmh18, released under the MIT license, and on ShardX for the browser.
License
MIT. See LICENSE. The original copyright notice is kept as the license requires.
Metadata
Release files for brave-client 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| brave_client-0.1.0.tar.gz | 227.3 kB | Without provenance | Details for brave_client-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| brave_client-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for brave_client-0.1.0-py3-none-any.whl |
Total release size: 294.5 kB
Release files / brave_client-0.1.0.tar.gz
| Download URL | brave_client-0.1.0.tar.gz |
|---|---|
| Size | 227.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
b95b026c069ffa9e82f9a9fb3839cb598b3313072eae187e51d9ea616cabb504
|
|
BLAKE2b-256 checksum How to use checksums |
90c5cb8cc829795e959634a960e07c8c597949f917ff9af7409a00bfbe650493
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.1
|
Release files / brave_client-0.1.0-py3-none-any.whl
| Download URL | brave_client-0.1.0-py3-none-any.whl |
|---|---|
| Size | 67.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a4436a836a8eff92a659d3bc3728f79080fc5ab4626e9f150f596fd6dcc96e97
|
|
BLAKE2b-256 checksum How to use checksums |
be3604d1cf298740956a85cd5a93f58b9d1b3fd28937c46ac3edd7585f1db476
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.1
|
Security for brave-client 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.