Skip to main content
Glama

bcb_variacao

Calculate percentage variation for Brazilian Central Bank economic time series between two dates or over recent periods to analyze trends.

Instructions

Calcula a variação percentual de uma série entre duas datas ou nos últimos N períodos. Útil para análise de tendências.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codigoYesCódigo da série no SGS/BCB
dataInicialNoData inicial (yyyy-MM-dd ou dd/MM/yyyy). Se não informada, usa o primeiro valor disponível.
dataFinalNoData final (yyyy-MM-dd ou dd/MM/yyyy). Se não informada, usa o último valor disponível.
periodosNoAlternativa: calcular variação dos últimos N períodos (ignora datas se informado)

Implementation Reference

  • The handleVariacao function calculates the percentage variation of a series based on the provided inputs (data range or number of periods).
    export async function handleVariacao(
      args: { codigo: number; dataInicial?: string; dataFinal?: string; periodos?: number },
      timeoutMs?: number,
      maxRetries?: number
    ): Promise<ToolResult> {
      try {
        let data: SerieValor[];
    
        if (args.periodos && args.periodos > 1) {
          const url = `${BCB_API_BASE}.${args.codigo}/dados/ultimos/${args.periodos}?formato=json`;
          data = await fetchBcbApi(url, timeoutMs, maxRetries) as SerieValor[];
        } else {
          let url = `${BCB_API_BASE}.${args.codigo}/dados?formato=json`;
          if (args.dataInicial) url += `&dataInicial=${formatDateForApi(args.dataInicial)}`;
          if (args.dataFinal) url += `&dataFinal=${formatDateForApi(args.dataFinal)}`;
          data = await fetchBcbApi(url, timeoutMs, maxRetries) as SerieValor[];
        }
    
        if (!Array.isArray(data) || data.length < 2) {
          return {
            content: [{ type: "text" as const, text: `Dados insuficientes para calcular variação. São necessários pelo menos 2 valores.` }]
          };
        }
    
        const serieInfo = SERIES_POPULARES.find(s => s.codigo === args.codigo);
        const valorInicial = parseFloat(data[0].valor);
        const valorFinal = parseFloat(data[data.length - 1].valor);
        const variacao = calculateVariation(valorInicial, valorFinal);
        const diferencaAbsoluta = valorFinal - valorInicial;
        const valores = data.map(d => parseFloat(d.valor));
        const maximo = Math.max(...valores);
        const minimo = Math.min(...valores);
        const media = valores.reduce((a, b) => a + b, 0) / valores.length;
    
        const result = {
          serie: { codigo: args.codigo, nome: serieInfo?.nome || `Série ${args.codigo}`, categoria: serieInfo?.categoria || "Desconhecida" },
          periodo: { dataInicial: data[0].data, dataFinal: data[data.length - 1].data, totalPeriodos: data.length },
          analise: {
            valorInicial, valorFinal,
            diferencaAbsoluta: Number(diferencaAbsoluta.toFixed(4)),
            variacaoPercentual: Number(variacao.toFixed(4)),
            variacaoFormatada: `${variacao >= 0 ? "+" : ""}${variacao.toFixed(2)}%`
          },
          estatisticas: {
            maximo: Number(maximo.toFixed(4)),
            minimo: Number(minimo.toFixed(4)),
            media: Number(media.toFixed(4)),
            amplitude: Number((maximo - minimo).toFixed(4))
          }
        };
    
        return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };
      } catch (error) {
        return {
          content: [{ type: "text" as const, text: `Erro ao calcular variação: ${error instanceof Error ? error.message : String(error)}` }],
          isError: true
        };
      }
    }
    
    export async function handleComparar(
      args: { codigos: number[]; dataInicial: string; dataFinal: string },
      timeoutMs?: number,
      maxRetries?: number
    ): Promise<ToolResult> {
      try {
        const resultados = await Promise.all(
          args.codigos.map(async (codigo) => {
            try {
              let url = `${BCB_API_BASE}.${codigo}/dados?formato=json`;
              url += `&dataInicial=${formatDateForApi(args.dataInicial)}`;
              url += `&dataFinal=${formatDateForApi(args.dataFinal)}`;
  • The registration definition for the 'bcb_variacao' tool, including its description and input schema.
    {
      name: "bcb_variacao",
      description: "Calcula a variação percentual de uma série entre duas datas ou nos últimos N períodos. Útil para análise de tendências.",
      inputSchema: {
        type: "object" as const,
        properties: {
          codigo: { type: "number" as const, description: "Código da série no SGS/BCB" },
          dataInicial: { type: "string" as const, description: "Data inicial (yyyy-MM-dd ou dd/MM/yyyy)" },
          dataFinal: { type: "string" as const, description: "Data final (yyyy-MM-dd ou dd/MM/yyyy)" },
          periodos: { type: "number" as const, description: "Alternativa: calcular variação dos últimos N períodos (ignora datas se informado)" }
        },
        required: ["codigo"]
      }
    },
  • src/tools.ts:861-862 (registration)
    The tool dispatcher in src/tools.ts handles the 'bcb_variacao' command by calling the handleVariacao function.
    case "bcb_variacao":
      return handleVariacao(args as { codigo: number; dataInicial?: string; dataFinal?: string; periodos?: number }, timeoutMs, maxRetries);
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the tool calculates percentage variation, which implies a read-only operation, but doesn't specify if it requires authentication, has rate limits, or details about error handling. The description is minimal and lacks behavioral traits beyond the basic function.

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

Conciseness4/5

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

The description is concise and front-loaded, consisting of two sentences that directly state the purpose and usage. There's no wasted text, and it efficiently communicates the core function. However, it could be slightly more structured by explicitly separating purpose from guidelines.

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

Completeness2/5

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

Given the complexity of a calculation tool with 4 parameters and no output schema or annotations, the description is incomplete. It doesn't explain the return values (e.g., format of the variation result), error cases, or dependencies on other tools like 'bcb_buscar_serie' for series codes. This leaves gaps for an AI agent to correctly invoke and interpret results.

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

Parameters3/5

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

The input schema has 100% description coverage, providing clear details for all 4 parameters. The description adds no additional parameter semantics beyond what's in the schema. It mentions 'entre duas datas ou nos últimos N períodos' (between two dates or over the last N periods), which aligns with the schema but doesn't elaborate further. With high schema coverage, the baseline score of 3 is appropriate.

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

Purpose4/5

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

The description clearly states the tool's purpose: 'Calcula a variação percentual de uma série entre duas datas ou nos últimos N períodos' (Calculates the percentage variation of a series between two dates or over the last N periods). It specifies the verb (calculates) and resource (percentage variation of a series), but doesn't explicitly differentiate it from sibling tools like 'bcb_comparar' or 'bcb_serie_valores', which might also involve series analysis.

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

Usage Guidelines3/5

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

The description provides implied usage context: 'Útil para análise de tendências' (Useful for trend analysis). This suggests when to use it, but doesn't explicitly state when not to use it or mention alternatives among the sibling tools. For example, it doesn't clarify if this is for single-series variation vs. multi-series comparison handled by 'bcb_comparar'.

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/SidneyBissoli/bcb-br-mcp'

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