Skip to main content
Glama
alanpcf

brasil-data-mcp

consultar_cnpj

Fetch Brazilian company registration details by CNPJ. Returns legal name, status, address, CNAE, partners, and financial data in JSON.

Instructions

Consulta dados cadastrais de uma empresa brasileira pelo CNPJ na Receita Federal (via BrasilAPI). Retorna em JSON: razão social, nome fantasia, situação cadastral (ativa/baixada/etc), data de abertura, endereço completo, CNAE principal e secundários, sócios (QSA), capital social, natureza jurídica, porte (MEI/ME/EPP/Demais), telefones, e-mail, simples nacional/MEI. Use quando o usuário pedir informações sobre uma empresa identificada por CNPJ. NÃO use para: CPF (pessoa física), empresas estrangeiras, ou validação local de formato (rejeite formato inválido sem chamar a tool). Aceita CNPJ com ou sem máscara.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
cnpjYesCNPJ da empresa, com ou sem máscara. Aceita '12.345.678/0001-90' ou '12345678000190'. Deve ter 14 dígitos.

Implementation Reference

  • The main function that executes the consultar_cnpj tool logic: validates input, calls BrasilAPI, and returns formatted results or error messages.
    export async function consultarCnpjHandler(
      input: ConsultarCnpjInput,
    ): Promise<CallToolResult> {
      const cnpjLimpo = limparCnpj(input.cnpj);
    
      if (!validarCnpj(cnpjLimpo)) {
        return {
          content: [
            {
              type: "text",
              text: `CNPJ inválido: '${input.cnpj}'. Deve conter 14 dígitos (com ou sem máscara) e não pode ser uma sequência repetida.`,
            },
          ],
          isError: true,
        };
      }
    
      try {
        const dados = await brasilApi.get<unknown>(`/cnpj/v1/${cnpjLimpo}`);
        return {
          content: [
            {
              type: "text",
              // JSON estruturado, não texto livre — o modelo extrai campos com
              // mais confiabilidade quando recebe JSON.
              text: JSON.stringify(dados, null, 2),
            },
          ],
        };
      } catch (err) {
        return {
          content: [
            {
              type: "text",
              text: traduzirErroBrasilApi(err, {
                notFound: `CNPJ ${cnpjLimpo} não encontrado na base da Receita Federal. Verifique se está correto.`,
                contextoErro: "Erro ao consultar CNPJ",
              }),
            },
          ],
          isError: true,
        };
      }
    }
  • Zod schema for the consultar_cnpj tool input, defining the 'cnpj' field with description.
    export const consultarCnpjSchema = z.object({
      cnpj: z
        .string()
        .describe(
          "CNPJ da empresa, com ou sem máscara. Aceita '12.345.678/0001-90' ou '12345678000190'. Deve ter 14 dígitos.",
        ),
    });
  • src/index.ts:81-88 (registration)
    Registration of consultar_cnpj tool into the MCP server via registerTool with name, description, schema, and wrapped handler.
    server.registerTool(
      consultarCnpjTool.name,
      {
        description: consultarCnpjTool.description,
        inputSchema: consultarCnpjSchema.shape,
      },
      wrapHandler(consultarCnpjTool.name, consultarCnpjHandler),
    );
  • Helper function to strip non-digit characters from CNPJ input.
    function limparCnpj(s: string): string {
      return s.replace(/\D/g, "");
    }
  • Helper function to validate CNPJ format: exactly 14 digits and not all repeated digits.
    function validarCnpj(s: string): boolean {
      if (!/^\d{14}$/.test(s)) return false;
      if (/^(\d)\1{13}$/.test(s)) return false;
      return true;
    }
Behavior4/5

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

With no annotations, the description must disclose behavior. It details the output format (JSON with many fields) and source (BrasilAPI/Receita Federal), implying a read operation. It lacks mention of error conditions or latency, but is largely transparent.

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?

The description is thorough yet well-organized: purpose, return fields, usage guidance, and exclusion criteria. No redundant sentences; every line 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 a simple single-parameter tool with good schema coverage, the description covers all essential aspects: purpose, parameters, expected output (list of fields), and usage restrictions. No missing information.

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%, baseline 3. The description adds value by specifying that the tool accepts both masked and unmasked formats and advises to reject invalid formats without calling the tool, enhancing guidance beyond schema.

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?

The description clearly states the tool consults Brazilian company data by CNPJ via BrasilAPI, listing specific return fields like razão social, CNAE, and QSA. This distinguishes it from sibling tools like consultar_cep or consultar_banco.

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 ('quando o usuário pedir informações sobre uma empresa identificada por CNPJ') and when not to use ('NÃO use para: CPF, empresas estrangeiras, ou validação local de formato'). Provides clear boundaries.

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