Metadata-Version: 2.5
Name: brave-client
Version: 0.1.0
Summary: Unofficial async Python client for Brave Ask & Search, driven through a real anti-detect browser, with a built-in MCP server.
Project-URL: Homepage, https://github.com/Coding-Doctor-Omar/brave-client
Project-URL: Repository, https://github.com/Coding-Doctor-Omar/brave-client
Project-URL: Issues, https://github.com/Coding-Doctor-Omar/brave-client/issues
Project-URL: Changelog, https://github.com/Coding-Doctor-Omar/brave-client/blob/main/CHANGELOG.md
Author: Omar Abdelhamid
License-Expression: MIT
License-File: LICENSE
Keywords: ai,async,brave,brave-search,browser,client,mcp,search
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: pillow>=12.2.0
Requires-Dist: pydantic>=2.11.0
Requires-Dist: shardx>=2.1.7
Provides-Extra: mcp
Requires-Dist: fastmcp<4,>=3.4.3; extra == 'mcp'
Description-Content-Type: text/markdown

# brave-client

<p align="center">
  <a href="https://pypi.org/project/brave-client/">
    <img src="https://img.shields.io/pypi/v/brave-client.svg?color=fe7039" alt="PyPI version" />
  </a>
  <a href="https://pypi.org/project/brave-client/">
    <img src="https://img.shields.io/pypi/pyversions/brave-client.svg?color=fe7039" alt="Python versions" />
  </a>
  <a href="https://github.com/Coding-Doctor-Omar/brave-client/actions/workflows/ci.yml">
    <img src="https://img.shields.io/github/actions/workflow/status/Coding-Doctor-Omar/brave-client/ci.yml?color=fe7039&label=CI" alt="CI" />
  </a>
  <a href="LICENSE">
    <img src="https://img.shields.io/badge/license-MIT-fe7039" alt="MIT license" />
  </a>
</p>

<p align="center">
An async Python client for <a href="https://search.brave.com">Brave Search</a>, 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.
</p>

> **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](https://github.com/iqbalmh18/brave-api)** 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](https://pypi.org/project/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/`](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+.

```bash
uv add brave-client
```

For MCP support:

```bash
uv add "brave-client[mcp]"
```

With pip:

```bash
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:

```bash
brave-client install
```

The command:

1. runs `shardx install` to download the browser engine
2. launches the browser once on a temporary profile for your OS
3. loads `https://httpbin.org/headers` to prove the browser works
4. 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:

```bash
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

```python
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

```python
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:

```python
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:

```python
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

```python
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

```python
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

```python
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`](examples/errors.py) for handling each of them.

## MCP server

Install the optional MCP dependency:

```bash
uv add "brave-client[mcp]"
```

Run locally over stdio:

```bash
brave-client-mcp
```

Or run an HTTP server:

```bash
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

1. Replace the package: `pip uninstall brave-api-python && pip install brave-client`
2. Change imports from `brave_api` to `brave_client`. Class and exception names
   are unchanged (`BraveClient`, `ClientConfig`, `BraveAPIError`, ...).
3. Run `brave-client install` once on every machine or image.
4. Rename the MCP command from `brave-api-mcp` to `brave-client-mcp`. The
   environment variables are the same, plus `BRAVE_HEADLESS`.
5. Remove `impersonate` and `user_agent` from your config (they are no longer
   accepted), and replace any `socks4` proxy.

## Examples

Runnable examples are available in [`examples/`](examples/):

- [`quickstart.py`](examples/quickstart.py) — minimal ask
- [`search_verticals.py`](examples/search_verticals.py) — all search verticals and pagination
- [`search_suggest.py`](examples/search_suggest.py) — web search and autocomplete
- [`streaming.py`](examples/streaming.py) — streaming events
- [`multi_turn.py`](examples/multi_turn.py) — resume, follow-up and regenerate
- [`multimodal.py`](examples/multimodal.py) — image input
- [`configuration.py`](examples/configuration.py) — configuration and proxies
- [`errors.py`](examples/errors.py) — the exception hierarchy
- [`concurrency.py`](examples/concurrency.py) — parallel queries on one client

The examples call the live Brave endpoints. Run one with:

```bash
uv run python examples/search_verticals.py
```

## Development

```bash
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](CONTRIBUTING.md) for the project layout and guidelines.

## Credits

brave-client builds on [brave-api-python](https://github.com/iqbalmh18/brave-api)
by iqbalmh18, released under the MIT license, and on
[ShardX](https://pypi.org/project/shardx/) for the browser.

## License

MIT. See [LICENSE](LICENSE). The original copyright notice is kept as the
license requires.
