---
title: "Python"
description: "Use the official Python MCP SDK to reach the APIBrasil APIs from your scripts and applications, with async support."
lang: en
canonical: https://doc.apibrasil.io/mcp/programacao/python
markdown: https://doc.apibrasil.io/mcp/programacao/python.md
source: apibrasil-documentation
---

# Python

> Use the official Python MCP SDK to reach the APIBrasil APIs from your scripts and applications, with async support.

- **Category:** Programming languages
- **Difficulty:** Medium
- **Protocol:** connects to the MCP server
- **Updated on:** January 14, 2026

## Prerequisites

- Python 3.10 or newer
- pip installed
- Basic asyncio knowledge
- APIBrasil tokens

## Configuration

- **File:** `main.py`

```python
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def main():
    server_params = StdioServerParameters(
        command="npx",
        args=[
            "-y",
            "@modelcontextprotocol/server-sse-client",
            "--url",
            "https://mcp.apibrasil.cloud/mcp"
        ],
        env={
            "APIBRASIL_BEARER_TOKEN": "seu_bearer_token",
            "APIBRASIL_DEVICE_TOKEN": "seu_device_token"
        }
    )
    
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            
            # Listar ferramentas disponíveis
            tools = await session.list_tools()
            print(f"Ferramentas disponíveis: {tools}")
            
            # Consultar CEP
            result = await session.call_tool(
                "consultar_cep",
                arguments={"cep": "01001000"}
            )
            print(f"Resultado: {result}")

if __name__ == "__main__":
    asyncio.run(main())
```

## Step by step

1. **Install the dependencies** — Install the official MCP SDK for Python
   ```bash
   pip install mcp
   # ou com poetry:
   poetry add mcp
   ```
2. **Create the configuration file** — Create a .env file to keep your tokens somewhere safe
   ```bash
   APIBRASIL_BEARER_TOKEN=seu_bearer_token_aqui
   APIBRASIL_DEVICE_TOKEN=seu_device_token_aqui
   ```
3. **Write a basic client** — Create a Python script that connects to the MCP server
   ```python
   import asyncio
   import os
   from mcp import ClientSession, StdioServerParameters
   from mcp.client.stdio import stdio_client
   from dotenv import load_dotenv
   
   load_dotenv()
   
   async def consultar_cep(cep: str):
       server_params = StdioServerParameters(
           command="npx",
           args=["-y", "@modelcontextprotocol/server-sse-client", "--url", "https://mcp.apibrasil.cloud/mcp"],
           env={
               "APIBRASIL_BEARER_TOKEN": os.getenv("APIBRASIL_BEARER_TOKEN"),
               "APIBRASIL_DEVICE_TOKEN": os.getenv("APIBRASIL_DEVICE_TOKEN")
           }
       )
       
       async with stdio_client(server_params) as (read, write):
           async with ClientSession(read, write) as session:
               await session.initialize()
               result = await session.call_tool("consultar_cep", arguments={"cep": cep})
               return result
   
   if __name__ == "__main__":
       resultado = asyncio.run(consultar_cep("01001000"))
       print(resultado)
   ```
4. **Run the script** — Run your Python script to test the connection
   ```bash
   python main.py
   ```
5. **Handle errors** — Add try/except to deal with connection and authentication failures
   ```python
   try:
       resultado = await session.call_tool("consultar_cep", arguments={"cep": cep})
       print(f"✓ Sucesso: {resultado}")
   except Exception as e:
       print(f"✗ Erro: {e}")
   ```

## Troubleshooting

- **ModuleNotFoundError: No module named 'mcp'** — Install the MCP package with pip: pip install mcp
  ```
  pip install mcp
  ```
- **asyncio.run() never finishes** — Check that you are using async/await correctly and that the MCP server is answering. A timeout makes this easier to debug
  ```
  resultado = await asyncio.wait_for(consultar_cep("01001000"), timeout=10.0)
  ```
- **Authentication error** — Check that the environment variables are actually being loaded
  ```
  import os
  from dotenv import load_dotenv
  
  load_dotenv()
  print(f"Token carregado: {os.getenv('APIBRASIL_BEARER_TOKEN')[:10]}...")
  ```
- **Connection refused** — Make sure Node.js is installed and NPX is on the PATH

## Related links

- [Official MCP Python SDK documentation](https://github.com/modelcontextprotocol/python-sdk)
- [Advanced Python examples](https://doc.apibrasil.io/mcp/exemplos/python.md)
- [Node.js integration](https://doc.apibrasil.io/mcp/programacao/nodejs.md)
- [Python asyncio tutorial](https://docs.python.org/3/library/asyncio.html)

## See also

- MCP guide: [MCP guide](https://doc.apibrasil.io/mcp.md)
- Documentation index: https://doc.apibrasil.io/llms.txt
- HTML version of this page: https://doc.apibrasil.io/mcp/programacao/python
