Skip to main content
Glama
alanpcf

brasil-data-mcp

consultar_banco

Retrieve a Brazilian bank's short name, full name, and ISPB using its COMPE/Febraban code. Ideal for obtaining bank identifiers needed for PIX or TED.

Instructions

Consulta os dados de um banco brasileiro pelo código COMPE/Febraban via BrasilAPI (fonte: BACEN). Retorna em JSON: nome curto, nome completo, código, ISPB (identificador no SPB). Use quando o usuário fornecer um código de banco e quiser saber o nome, ou quando precisar do ISPB pra montar um PIX/TED. NÃO use para: buscar banco por nome (use listar_bancos e filtre), validar conta corrente, ou consultar agência/conta. Códigos comuns: 001=BB, 104=CEF, 237=Bradesco, 341=Itaú, 260=Nubank, 077=Inter.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codigoYesCódigo COMPE/Febraban do banco (1 a 4 dígitos). Aceita string ou número. Ex: 341 (Itaú), 260 (Nubank), 237 (Bradesco).

Implementation Reference

  • Handler function for the 'consultar_banco' tool. Validates the numeric bank code input, calls the BrasilAPI endpoint /banks/v1/{code}, and returns the bank info as formatted JSON. On error, translates API errors to user-friendly Portuguese messages.
    export async function consultarBancoHandler(
      input: ConsultarBancoInput,
    ): Promise<CallToolResult> {
      const codigo = normalizarCodigo(input.codigo);
    
      if (!codigo) {
        return {
          content: [
            {
              type: "text",
              text: `Código de banco inválido: '${input.codigo}'. Deve ser numérico, de 1 a 4 dígitos.`,
            },
          ],
          isError: true,
        };
      }
    
      try {
        const dados = await brasilApi.get<unknown>(`/banks/v1/${codigo}`);
        return {
          content: [{ type: "text", text: JSON.stringify(dados, null, 2) }],
        };
      } catch (err) {
        return {
          content: [
            {
              type: "text",
              text: traduzirErroBrasilApi(err, {
                notFound: `Banco com código ${codigo} não encontrado no cadastro do BACEN.`,
                contextoErro: "Erro ao consultar banco",
              }),
            },
          ],
          isError: true,
        };
      }
    }
  • Zod schema for 'consultar_banco' input. Accepts a 'codigo' field as string or number (1-4 digit COMPE/Febraban bank code).
    export const consultarBancoSchema = z.object({
      codigo: z
        .union([z.string(), z.number()])
        .describe(
          "Código COMPE/Febraban do banco (1 a 4 dígitos). Aceita string ou número. Ex: 341 (Itaú), 260 (Nubank), 237 (Bradesco).",
        ),
    });
  • src/index.ts:99-106 (registration)
    Registration of the 'consultar_banco' tool with the MCP server via server.registerTool(), using the tool name, description, input schema, and a wrapped handler.
    server.registerTool(
      consultarBancoTool.name,
      {
        description: consultarBancoTool.description,
        inputSchema: consultarBancoSchema.shape,
      },
      wrapHandler(consultarBancoTool.name, consultarBancoHandler),
    );
  • Helper function 'normalizarCodigo' that validates and normalizes a bank code (1-4 digits), stripping leading zeros and returning an empty string if invalid.
    function normalizarCodigo(codigo: string | number): string {
      const s = String(codigo).trim();
      // Códigos COMPE têm de 1 a 4 dígitos. Normaliza removendo zeros à esquerda
      // só pra validar — a BrasilAPI aceita tanto "1" quanto "001".
      if (!/^\d{1,4}$/.test(s)) return "";
      return s;
    }
  • Helper function 'traduzirErroBrasilApi' used by the handler to translate BrasilApiError exceptions into user-friendly Portuguese messages based on HTTP status codes.
    export function traduzirErroBrasilApi(
      err: unknown,
      mapa: MapeamentoErro,
    ): string {
      const ctx = mapa.contextoErro ?? "Erro ao consultar dados";
    
      if (err instanceof BrasilApiError) {
        if (err.status === 404) return mapa.notFound;
        if (err.status === 400) {
          return `${ctx}: dados inválidos enviados ao serviço.`;
        }
        if (err.status === 429) {
          return `${ctx}: limite de requisições temporariamente atingido. Tente novamente em alguns segundos.`;
        }
        if (err.status >= 500) {
          return `${ctx}: serviço temporariamente indisponível. Tente novamente em alguns instantes.`;
        }
        // status === 0 é o sinal que usamos no cliente pra erro de rede / abort.
        if (err.status === 0) {
          return `${ctx}: falha de rede ao alcançar o serviço.`;
        }
        return `${ctx}: o serviço retornou erro inesperado (${err.status}).`;
      }
    
      const msg = err instanceof Error ? err.message : String(err);
      return `${ctx}: ${msg}`;
    }
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, so description carries full burden. States it's a read-only query returning JSON with specific fields, sourced from BrasilAPI/BACEN. Lacks details on error handling or rate limits, but for a simple query tool this is adequate.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two concise sentences plus a compact list of common codes. No filler, front-loaded with purpose and usage. Every sentence adds value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given low complexity (1 param, no output schema), the description covers purpose, input format, return fields, usage boundaries, and examples. No obvious gaps for the intended use case.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100% and description adds value with examples (341 for Itaú, 260 for Nubank) and clarifies the parameter is the COMPE code. Slightly above baseline 3 due to concrete examples.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Describes specific verb 'consulta' and resource 'banco brasileiro pelo código COMPE/Febraban via BrasilAPI'. Clearly distinguishes from sibling tools like listar_bancos (which lists all banks) and consultar_cep/CNPJ (different domains).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly states when to use (user provides bank code, wants name or ISPB for PIX/TED) and when not to use (search by name, validate account, consult agência/conta). Mentions alternative tool listar_bancos for name-based search.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/alanpcf/brasil-data-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server