Skip to main content
Glama
alanpcf

brasil-data-mcp

consultar_cep

Look up a Brazilian address by CEP code. Returns state, city, neighborhood, street, and geographic coordinates when available.

Instructions

Consulta endereço completo a partir de um CEP brasileiro via BrasilAPI v2 (agrega ViaCEP, Postmon e outros provedores com fallback automático). Retorna em JSON: estado (UF), cidade, bairro, logradouro e, quando disponível, coordenadas geográficas. Use quando o usuário pedir o endereço de um CEP, validar um CEP, ou descobrir cidade/UF a partir de um CEP. NÃO use para: códigos postais de outros países, descobrir CEP a partir de endereço (a operação é só CEP → endereço, não inversa). Aceita CEP com ou sem hífen.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
cepYesCEP brasileiro com ou sem hífen. Aceita '01310-100' ou '01310100'. Deve ter 8 dígitos.

Implementation Reference

  • Main handler function for consultar_cep. Cleans the CEP (removes non-digits), validates it (8 digits, not all same), calls brasilApi.get('/cep/v2/{cep}'). Returns JSON stringified address data on success, or translated error messages on failure.
    export async function consultarCepHandler(
      input: ConsultarCepInput,
    ): Promise<CallToolResult> {
      const cepLimpo = limparCep(input.cep);
    
      if (!validarCep(cepLimpo)) {
        return {
          content: [
            {
              type: "text",
              text: `CEP inválido: '${input.cep}'. Deve conter 8 dígitos (com ou sem hífen) e não pode ser uma sequência repetida.`,
            },
          ],
          isError: true,
        };
      }
    
      try {
        const dados = await brasilApi.get<unknown>(`/cep/v2/${cepLimpo}`);
        return {
          content: [{ type: "text", text: JSON.stringify(dados, null, 2) }],
        };
      } catch (err) {
        return {
          content: [
            {
              type: "text",
              text: traduzirErroBrasilApi(err, {
                notFound: `CEP ${cepLimpo} não encontrado. Verifique se está correto — alguns CEPs muito específicos só existem em provedores pagos.`,
                contextoErro: "Erro ao consultar CEP",
              }),
            },
          ],
          isError: true,
        };
      }
    }
  • Zod schema for consultar_cep input. Accepts a single 'cep' field: string with 8 digits, with or without hyphen.
    export const consultarCepSchema = z.object({
      cep: z
        .string()
        .describe(
          "CEP brasileiro com ou sem hífen. Aceita '01310-100' ou '01310100'. Deve ter 8 dígitos.",
        ),
    });
  • src/index.ts:90-97 (registration)
    Registration of the consultar_cep tool on the MCP server via server.registerTool(), using the tool's name, description, schema shape, and the wrapped handler.
    server.registerTool(
      consultarCepTool.name,
      {
        description: consultarCepTool.description,
        inputSchema: consultarCepSchema.shape,
      },
      wrapHandler(consultarCepTool.name, consultarCepHandler),
    );
  • src/tools/cep.ts:24-36 (registration)
    Tool metadata definition: name ('consultar_cep'), description (natural language prompt instructions), and inputSchema reference.
    export const consultarCepTool = {
      name: "consultar_cep",
      description: [
        "Consulta endereço completo a partir de um CEP brasileiro via BrasilAPI v2 (agrega ViaCEP, Postmon e outros provedores com fallback automático).",
        "",
        "Retorna em JSON: estado (UF), cidade, bairro, logradouro e, quando disponível, coordenadas geográficas.",
        "",
        "Use quando o usuário pedir o endereço de um CEP, validar um CEP, ou descobrir cidade/UF a partir de um CEP.",
        "",
        "NÃO use para: códigos postais de outros países, descobrir CEP a partir de endereço (a operação é só CEP → endereço, não inversa). Aceita CEP com ou sem hífen.",
      ].join(" "),
      inputSchema: consultarCepSchema,
    };
  • Helper function that strips all non-digit characters from the CEP string.
    function limparCep(s: string): string {
      return s.replace(/\D/g, "");
    }
Behavior4/5

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

No annotations provided, so description carries full burden. It discloses the use of multiple providers with automatic fallback, return format (JSON with state, city, neighborhood, street, and coordinates when available). However, it does not mention rate limits, authentication needs, or error handling. Still, the core behavioral traits are well covered.

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 concise with a clear front-loaded statement of purpose, followed by usage guidance and constraints. Every sentence adds value, no fluff.

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 no output schema, the description explains the return format and fields. It also covers the fallback behavior and usage scope. For a simple tool with one parameter, it is fully complete.

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

Parameters5/5

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

Schema coverage is 100% for the single parameter 'cep'. The description adds that it accepts CEP with or without hyphen, provides examples, and specifies the 8-digit format requirement, adding value beyond the 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 it consults a complete Brazilian address from a CEP using BrasilAPI v2 with automatic fallback. It specifies the return fields and distinguishes itself from sibling tools like consultar_banco and consultar_cnpj by focusing solely on CEP lookup.

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: when user asks for address from CEP, validates CEP, or discovers city/state from CEP. Also clearly states what NOT to use for: other countries' postal codes and reverse lookup (address to CEP).

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