# brapi.dev API authentication

This guide covers API tokens and OAuth for the brapi.dev MCP server.

## Discover

Read the protected-resource metadata at https://brapi.dev/.well-known/oauth-protected-resource/api/mcp/mcp.
Then read the authorization-server metadata at https://brapi.dev/.well-known/oauth-authorization-server.
The metadata names the supported endpoints, scope, and PKCE method.

## Pick a method

Use a Bearer API token for deterministic REST calls and server-side integrations.
Use OAuth when an MCP client cannot safely store a brapi API token.
Use PETR4, VALE3, MGLU3, or ITUB4 for sandbox requests without credentials.

## Register

MCP clients can register a public OAuth client at https://brapi.dev/oauth/register.
The authorization metadata calls this endpoint `register_uri` and `registration_endpoint`.
Send the client redirect URIs and keep the returned client identifier.

## Claim

Create an authorization URL at https://brapi.dev/oauth/authorize.
Use response type `code`, the `mcp:read` scope, and PKCE with `S256`.
Exchange the authorization code at https://brapi.dev/oauth/token.
The token response supplies a Bearer access token for https://brapi.dev/api/mcp/mcp.

## Use credential

Send an API token in the `Authorization` header.

```bash
curl 'https://brapi.dev/api/v2/stocks/quote?symbols=PETR4' \
  -H 'Authorization: Bearer YOUR_TOKEN'
```

For MCP, send the OAuth access token to the Streamable HTTP endpoint.
Read `RateLimit-Limit`, `RateLimit-Remaining`, and `RateLimit-Reset` on every API response.

## Errors

HTTP 401 means the credential is missing, expired, or invalid.
HTTP 403 means the account lacks the required feature or plan.
HTTP 429 means the request limit is reached.
Wait for `Retry-After` after HTTP 429 before retrying.
Use https://brapi.dev/llms.txt when a client needs the current resource index.

## Revocation

Delete or rotate API tokens from https://brapi.dev/dashboard.
OAuth access and refresh tokens expire automatically.
Discard expired OAuth tokens and start a new authorization flow.
