Skip to main content
Glama
guilhermelirio

Brazilian CEP MCP

consultar-cep

Query Brazilian postal codes (CEP) to retrieve detailed address information including street names, neighborhoods, cities, states, and IBGE codes.

Instructions

Query address information from a Brazilian postal code (CEP)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
cepYesPostal code to be queried (only numbers, 8 digits)

Implementation Reference

  • Handler function that executes the CEP lookup using ViaCEP API, handles errors, and formats the address response.
    async ({ cep }) => {
      try {
        console.error(`Consulting postal code: ${cep}`);
        
        const url = `https://viacep.com.br/ws/${cep}/json/`;
        const response = await axios.get(url);
        
        // Verificando se houve erro na resposta da API
        if (response.data.erro) { 
          return {
            content: [{ 
              type: "text", 
              text: "Postal code not found in the database." 
            }],
            isError: true
          };
        }
        
        // Formatando a resposta para exibição
        const endereco = response.data;
        return {
          content: [{ 
            type: "text", 
            text: `
    Endereço encontrado:
    CEP: ${endereco.cep}
    Logradouro: ${endereco.logradouro}
    Complemento: ${endereco.complemento || "N/A"}
    Bairro: ${endereco.bairro}
    Cidade: ${endereco.localidade}
    Estado: ${endereco.uf} (${endereco.estado})
    Região: ${endereco.regiao}
    DDD: ${endereco.ddd}
    IBGE: ${endereco.ibge}
            ` 
          }]
        };
        
      } catch (erro: any) {
        console.error(`Error querying postal code: ${erro.message}`);
        
        // Verificando se o erro é devido a formato inválido (status 400)
        if (erro.response && erro.response.status === 400) {
          return {
            content: [{ 
              type: "text", 
              text: "Invalid postal code format. Use only numbers (8 digits)." 
            }],
            isError: true
          };
        }
        
        return {
          content: [{ 
            type: "text", 
            text: `Error querying postal code: ${erro.message}` 
          }],
          isError: true
        };
      }
    }
  • Zod schema for input validation of the 'cep' parameter, ensuring 8 digits.
    {
      cep: z.string()
        .length(8, "Postal code must have exactly 8 digits")
        .regex(/^\d+$/, "Postal code must contain only numbers")
        .describe("Postal code to be queried (only numbers, 8 digits)")
    },
  • src/index.ts:18-88 (registration)
    Registration of the 'consultar-cep' tool on the MCP server with description, schema, and handler.
    server.tool(
      "consultar-cep",
      "Query address information from a Brazilian postal code (CEP)",
      {
        cep: z.string()
          .length(8, "Postal code must have exactly 8 digits")
          .regex(/^\d+$/, "Postal code must contain only numbers")
          .describe("Postal code to be queried (only numbers, 8 digits)")
      },
      async ({ cep }) => {
        try {
          console.error(`Consulting postal code: ${cep}`);
          
          const url = `https://viacep.com.br/ws/${cep}/json/`;
          const response = await axios.get(url);
          
          // Verificando se houve erro na resposta da API
          if (response.data.erro) { 
            return {
              content: [{ 
                type: "text", 
                text: "Postal code not found in the database." 
              }],
              isError: true
            };
          }
          
          // Formatando a resposta para exibição
          const endereco = response.data;
          return {
            content: [{ 
              type: "text", 
              text: `
      Endereço encontrado:
      CEP: ${endereco.cep}
      Logradouro: ${endereco.logradouro}
      Complemento: ${endereco.complemento || "N/A"}
      Bairro: ${endereco.bairro}
      Cidade: ${endereco.localidade}
      Estado: ${endereco.uf} (${endereco.estado})
      Região: ${endereco.regiao}
      DDD: ${endereco.ddd}
      IBGE: ${endereco.ibge}
              ` 
            }]
          };
          
        } catch (erro: any) {
          console.error(`Error querying postal code: ${erro.message}`);
          
          // Verificando se o erro é devido a formato inválido (status 400)
          if (erro.response && erro.response.status === 400) {
            return {
              content: [{ 
                type: "text", 
                text: "Invalid postal code format. Use only numbers (8 digits)." 
              }],
              isError: true
            };
          }
          
          return {
            content: [{ 
              type: "text", 
              text: `Error querying postal code: ${erro.message}` 
            }],
            isError: true
          };
        }
      }
    );
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/guilhermelirio/brazilian-cep-mcp'

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