Skip to main content
Glama

buscar_municipios

Find Brazilian municipalities by state to retrieve IBGE codes needed for checking municipal holidays with the feriadosapi server.

Instructions

Busca municípios brasileiros por estado. Retorna nome, UF e código IBGE de cada município. Use esta tool para descobrir o código IBGE de uma cidade antes de consultar feriados municipais com 'feriados_por_cidade'. Pode filtrar por UF para listar apenas municípios de um estado. O Brasil possui mais de 5.500 municípios; use o filtro de UF para resultados mais precisos.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
ufNoSigla do estado para filtrar (ex: SP, RJ). Se omitido, retorna todos os municípios paginados.
pageNoNúmero da página (default: 1)
limitNoItens por página (default: 50, max: 100)

Implementation Reference

  • Main handler function that executes the buscar_municipios tool. It receives uf, page, and limit parameters, makes an API call to the /municipios endpoint, formats the response with emojis, and returns paginated results.
    async ({ uf, page, limit }) => {
        try {
            const data = await feriadosApi<{
                municipios: { ibge: number; nome: string; uf: string }[];
                meta: { total: number; page: number; total_pages: number };
            }>({
                path: "/municipios",
                params: {
                    uf: uf?.toUpperCase(),
                    page: page?.toString(),
                    limit: limit?.toString(),
                },
            });
    
            const list = data.municipios
                .map((m) => `🏘️ ${m.nome} (${m.uf}) — IBGE: ${m.ibge}`)
                .join("\n");
    
            let header = "🏘️ Municípios";
            if (uf) header += ` — ${uf.toUpperCase()}`;
    
            const text =
                header +
                `\n\n${list}` +
                `\n\n📊 Total: ${data.meta.total} | Página ${data.meta.page}/${data.meta.total_pages}`;
            return { content: [{ type: "text" as const, text }] };
        } catch (error) {
            return {
                content: [
                    {
                        type: "text" as const,
                        text: `❌ Erro: ${error instanceof Error ? error.message : String(error)}`,
                    },
                ],
                isError: true,
            };
        }
    }
  • Input schema definition using Zod for the buscar_municipios tool. Defines uf (string, length 2, optional), page (number, int, min 1, optional), and limit (number, int, min 1, max 100, optional) parameters with descriptions.
    inputSchema: z.object({
        uf: z
            .string()
            .length(2)
            .optional()
            .describe(
                "Sigla do estado para filtrar (ex: SP, RJ). Se omitido, retorna todos os municípios paginados."
            ),
        page: z
            .number()
            .int()
            .min(1)
            .optional()
            .describe("Número da página (default: 1)"),
        limit: z
            .number()
            .int()
            .min(1)
            .max(100)
            .optional()
            .describe("Itens por página (default: 50, max: 100)"),
    }),
  • Tool registration in registerMunicipiosTools function. Calls server.registerTool with the tool name 'buscar_municipios', title, description, inputSchema, and handler function.
    export function registerMunicipiosTools(server: McpServer) {
        server.registerTool(
            "buscar_municipios",
            {
                title: "Buscar Municípios",
                description: `Busca municípios brasileiros por estado. Retorna nome, UF e código IBGE de cada município.
    Use esta tool para descobrir o código IBGE de uma cidade antes de consultar feriados municipais com 'feriados_por_cidade'.
    Pode filtrar por UF para listar apenas municípios de um estado.
    O Brasil possui mais de 5.500 municípios; use o filtro de UF para resultados mais precisos.`,
                inputSchema: z.object({
                    uf: z
                        .string()
                        .length(2)
                        .optional()
                        .describe(
                            "Sigla do estado para filtrar (ex: SP, RJ). Se omitido, retorna todos os municípios paginados."
                        ),
                    page: z
                        .number()
                        .int()
                        .min(1)
                        .optional()
                        .describe("Número da página (default: 1)"),
                    limit: z
                        .number()
                        .int()
                        .min(1)
                        .max(100)
                        .optional()
                        .describe("Itens por página (default: 50, max: 100)"),
                }),
            },
  • Central registration file that imports and calls registerMunicipiosTools. This is where all tools are registered with the MCP server.
    import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
    import { registerFeriadosTools } from "./tools/feriados";
    import { registerEstadosTools } from "./tools/estados";
    import { registerMunicipiosTools } from "./tools/municipios";
    
    export function registerAllTools(server: McpServer) {
        registerFeriadosTools(server);
        registerEstadosTools(server);
        registerMunicipiosTools(server);
    }
  • Helper function feriadosApi that handles HTTP requests to the Feriados API. Used by the buscar_municipios handler to fetch municipality data. Includes API key validation, URL construction, error handling, and response parsing.
    export async function feriadosApi<T>(options: ApiRequestOptions): Promise<T> {
        const apiKey = options.apiKey || process.env.FERIADOS_API_KEY;
    
        if (!apiKey) {
            throw new Error(
                "API Key não fornecida. Passe sua chave via parâmetro apiKey na URL ou configure FERIADOS_API_KEY. Obtenha uma gratuita em https://feriadosapi.com/dashboard"
            );
        }
    
        const url = new URL(`${BASE_URL}/api/v1${options.path}`);
    
        // Adicionar query params (ignorar undefined)
        if (options.params) {
            Object.entries(options.params).forEach(([key, value]) => {
                if (value !== undefined) {
                    url.searchParams.set(key, value);
                }
            });
        }
    
        const response = await fetch(url.toString(), {
            headers: {
                "X-API-Key": apiKey,
                "Content-Type": "application/json",
            },
        });
    
        if (!response.ok) {
            const errorBody = await response.json().catch(() => ({}));
            const errorMessage =
                errorBody.error || errorBody.message || response.statusText;
    
            switch (response.status) {
                case 401:
                    throw new Error(
                        "API Key inválida ou ausente. Verifique sua chave em https://feriadosapi.com/dashboard"
                    );
                case 403:
                    throw new Error(`Acesso negado: ${errorMessage}`);
                case 429:
                    throw new Error(
                        "Cota mensal excedida. Faça upgrade em https://feriadosapi.com/dashboard"
                    );
                case 404:
                    throw new Error(`Recurso não encontrado: ${errorMessage}`);
                default:
                    throw new Error(`Erro na API (${response.status}): ${errorMessage}`);
            }
        }
    
        return response.json() as Promise<T>;
    }

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/feriadosapi/feriadosapi'

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