Skip to main content
Glama
vinimeurer

orcamento

by vinimeurer

Conversational Budget — Core Pipeline

Natural language expense recording system via Telegram, using Google Gemini (official API, model configurable via .env, by default gemini-3.6-flash) as the language model, orchestrated by Nanobot, with data saved in Postgres.

This document assumes you have never run Docker before and explains each step, each command, and what to expect as a result of each one.


Table of Contents

  1. What you need to have installed

  2. Getting the bot token on Telegram

  3. Getting the Gemini API key

  4. Configuring the .env file

  5. Bringing everything up with Docker

  6. Testing on Telegram

  7. Day-to-day commands

  8. Common problems and how to solve them

  9. What each project file does

  10. Alternative: local installation (without Docker)

  11. Next steps for the project


Related MCP server: Expense Tracker MCP Server

1. What you need to have installed

Only one thing on your machine. You do not need to install Python, Postgres, or Nanobot separately — all of that runs inside the containers.

Docker Desktop (Windows/Mac) or Docker Engine (Linux)

Check that everything is fine

Open a terminal (PowerShell on Windows, Terminal on Mac/Linux) and run:

docker --version
docker compose version

You should see two version lines, with no error.


2. Getting the bot token on Telegram

  1. Open Telegram (mobile or desktop) and search for @BotFather in the search. It is the official Telegram bot for creating other bots — make sure it has the verified badge.

  2. Send it: /newbot

  3. It will ask for a name for your bot. It can be anything, e.g., Conversational Budget.

  4. Then it asks for a username. This must be unique across all of Telegram and must end in "bot", e.g., orcamento_seunome_bot.

  5. If it works, BotFather replies with a message like this:

    Done! Congratulations on your new bot. You will find it at
    t.me/orcamento_seunome_bot. You can now add a description...
    
    Use this token to access the HTTP API:
    7123456789:AAHxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    
    Keep your token secure and store it safely...
  6. Copy the entire token line (the format is numbers:letters_and_numbers). You will paste this into the .env file in the next step.

Keep this token.


3. Getting the Gemini API key

Nanobot uses the official Google Gemini API as the language model.

  1. Go to https://aistudio.google.com/api-keys and log in with your Google account.

  2. Click Create API key (Google creates a project automatically).

  3. Copy the key and paste it into .env in the next step.

About costs: no card required. The free tier covers the Flash/Flash-Lite models with request limits per minute/day (~10 req/min and ~250–1,500 req/day depending on the model) — plenty for this project. The Pro models are paid. Official table: https://ai.google.dev/gemini-api/docs/pricing


4. Configuring the .env file

The project already comes with a file called .env at the root of the folder (orcamento-conversacional/.env). It is read automatically by Docker Compose — you don't need to rename anything.

Note: files that start with a dot (.env) are "hidden" by default in Windows File Explorer, Mac Finder, and in ls without flags on Linux/Mac. Use ls -la to see it in the terminal, or open the folder with a text editor.

Inside .env, replace these two lines with the real values:

TELEGRAM_TOKEN=coloque_seu_token_aqui      ← token do BotFather (seção 2)
GEMINI_API_KEY=coloque_sua_chave_aqui      ← chave do AI Studio (seção 3)

The GEMINI_MODEL variable defines which model to use (default: gemini-3.6-flash). Only change it if you want to switch to another valid ID from the official list: https://ai.google.dev/gemini-api/docs/models

The other variables (POSTGRES_PASSWORD, DATABASE_URL) already come with values that work — you don't need to touch them to run in Docker.

Save the file.


5. Bringing everything up with Docker

With the terminal open inside the orcamento-conversacional folder (the one that has the docker-compose.yml file), run:

docker compose up -d --build

What this command does, in order:

Step

What happens

Approximate time

1

Downloads the base images (Postgres) from the internet

1–3 min (first time)

2

Builds (--build) the Nanobot image (includes the embedded MCP server)

2–4 min (first time)

3

Starts Postgres and applies schema.sql automatically

a few seconds

4

Starts Nanobot, waiting for Postgres to be ready

a few seconds

There is no download or execution of a model on your machine: Gemini runs in Google's cloud.

The -d flag ("detached") makes everything run in the background. The next times you run docker compose up -d (without --build), it comes up in seconds.

How to know if everything went well

Run:

docker compose ps

You should see 2 services:

NAME                    IMAGE                    STATUS
orcamento_postgres      postgres:16-alpine       Up (healthy)
orcamento_nanobot       ...nanobot               Up

Also check the Nanobot logs — the MCP should appear connected:

docker compose logs nanobot

Look for lines like:

MCP: registered tool 'mcp_orcamento_registrar_despesa' from server 'orcamento'
MCP server 'orcamento': connected, 3 capabilities registered
✓ Health endpoint: http://127.0.0.1:18790/health
bot @seubot connected

If orcamento_nanobot appears as "Restarting" or disappears from the list, see the Common problems section.


6. Testing on Telegram

  1. On Telegram, search for the bot username you created with BotFather (e.g., @orcamento_seunome_bot) and open a conversation with it.

  2. Send /start. On the first conversation, Nanobot may ask for a pairing code — it appears in the logs (docker compose logs -f nanobot, line "Generated pairing code ..."). Send that code to the bot.

  3. Send something like:

    Gastei 35 no almoço hoje
  4. Within a few seconds, the bot should reply confirming the record, something like:

    Registrado: R$ 35,00 em alimentação (almoço).

If the bot doesn't reply at all, see the common problems section below.


7. Day-to-day commands

All run inside the orcamento-conversacional folder.

View logs of everything, in real time:

docker compose logs -f

(Ctrl+C to exit — this only stops showing the logs; the containers keep running.)

View logs only for Nanobot (the most useful for debugging conversations):

docker compose logs -f nanobot

Stop everything (keeping saved data):

docker compose down

Bring it back up after stopping:

docker compose up -d

After editing SOUL.md, config.docker.json, or .env (no need to rebuild the image; config and prompts are mounted directly into the container):

docker compose up -d nanobot    # recria o container aplicando o novo .env

After editing mcp_server/expense_tools.py or db/connection.py (needs a rebuild, because the MCP venv is created in the image):

docker compose up -d --build nanobot

Delete absolutely everything, including the database data (useful if something got corrupted and you want to start from scratch):

docker compose down -v

Enter the database to see recorded expenses manually:

docker exec -it orcamento_postgres psql -U orcamento -d orcamento

Inside psql, try:

SELECT * FROM despesas ORDER BY criado_em DESC LIMIT 10;

To exit psql: type \q and Enter.

Optional shortcut: if you have make installed (standard on Mac/Linux), the project includes a Makefile with the most used commands: make up, make down, make logs, make restart, make ps.


8. Common problems and how to solve them

Error: Environment variable 'GEMINI_API_KEY' referenced in config is not set

The .env does not have the GEMINI_API_KEY variable defined. Open .env, make sure the line exists (even with a temporary value), and run docker compose up -d nanobot again.

401, unauthorized, or invalid api key in Nanobot logs

The GEMINI_API_KEY is wrong, revoked, or has an extra space. Generate a new key at https://aistudio.google.com/api-keys and update .env.

429 or rate limit / quota errors

You hit the Gemini free tier limit (requests per minute or per day). Options: wait a few minutes, change GEMINI_MODEL in .env to a Flash-Lite model (higher limits, e.g., gemini-3.1-flash-lite) and bring it back up, or enable billing on your Google Cloud account.

model not found in logs

The GEMINI_MODEL value is not a valid Gemini API ID. Check the official list at https://ai.google.dev/gemini-api/docs/models and fix .env.

The bot doesn't call the tools / says it can't record

Run docker compose logs nanobot and look for:

  • MCP server 'orcamento': connected — if it doesn't appear, there was a failure starting the embedded MCP server; see errors just above that line;

  • Max iterations (...) reached — means the model entered a tool-call loop; the configurable limit is in agents.defaults.maxToolIterations of the config.

The bot doesn't reply anything on Telegram

  • Check docker compose logs -f nanobot while sending a message — some activity should appear in the log at the same moment.

  • Make sure you completed the pairing (section 6, step 2).

docker compose version says "unknown flag" or doesn't exist

You have the old Docker Compose (v1, with a hyphen: docker-compose). Update Docker Desktop, or install the docker-compose-plugin plugin separately (Linux).


9. What each project file does

orcamento-conversacional/
├── .env                         # SUAS credenciais (token do Telegram, chave
│                                #   do Gemini, senha do banco). Lido
│                                #   automaticamente pelo docker compose.
├── .env.example                 # Modelo de referência do .env, sem credenciais reais.
├── docker-compose.yml           # Define os containers (postgres, nanobot) e
│                                #   a ordem de inicialização.
├── Makefile                     # Atalhos opcionais (make up, make logs, etc).
├── requirements.txt             # Dependências Python do servidor MCP (mcp, psycopg2-binary).
│
├── db/
│   ├── schema.sql               # Cria as tabelas usuarios, categorias, despesas.
│   │                            #   Aplicado automaticamente na 1ª subida do Postgres.
│   └── connection.py            # Código Python que conecta no Postgres (pool de conexões)
│                                #   e resolve o usuário do Telegram para um id interno.
│
├── mcp_server/
│   ├── expense_tools.py         # As "ferramentas" que o agente de IA usa:
│   │                            #   registrar_despesa, listar_despesas, resumo_por_categoria.
│   │                            #   Roda via stdio DENTRO do container do Nanobot.
│   └── Dockerfile               # Imagem standalone opcional do MCP server (modo HTTP).
│
└── nanobot_config/
    ├── config.json              # Config do Nanobot para rodar FORA do Docker
    │                            #   (instalação local — ver seção 10). MCP via stdio
    │                            #   relativo à raiz do projeto.
    ├── config.docker.json       # Config do Nanobot para rodar DENTRO do Docker —
    │                            #   é este que está ativo quando você usa `docker compose up`.
    │                            #   MCP via stdio em /opt/mcpvenv (venv isolado).
    ├── Dockerfile               # Como construir a imagem do Nanobot. Instala o
    │                            #   nanobot + um venv isolado (/opt/mcpvenv) com as
    │                            #   dependências do servidor MCP.
    ├── SOUL.md                  # As instruções que dizem ao agente COMO se comportar:
    │                            #   como extrair valor/categoria/data de uma mensagem,
    │                            #   quando pedir confirmação, o que ele NÃO deve fazer ainda.
    ├── AGENTS.md                # Regras gerais de comportamento (idioma, uso de tools,
    │                            #   tratamento de erro). Complementa o SOUL.md.
    └── USER.md                  # Perfil do usuário — começa vazio, o Nanobot vai
                                  preenchendo automaticamente com o tempo.

Details of the current architecture

  • Language model: Google Gemini via official API (providers.gemini). The model is chosen by the GEMINI_MODEL variable in .env (default: gemini-3.6-flash). No local model runs.

  • MCP server: runs as a subprocess (stdio) inside Nanobot's own container, using the isolated venv /opt/mcpvenv. Why isolated? The Python SDK mcp 2.x used by the tools conflicts with the version (mcp>=1.26,<2) required by nanobot itself.

  • Loop protection: agents.defaults.maxToolIterations: 6 limits how many consecutive tool calls the agent can make in a single turn.

Why are there two Nanobot config files?

config.json (for running locally, outside Docker) points the MCP server via stdio relative to the project root. config.docker.json (used inside Docker) uses absolute container paths (/opt/mcp_server/...) and the venv /opt/mcpvenv/bin/python3.


10. Alternative: local installation (without Docker)

If you prefer to run Postgres/Nanobot directly on your machine instead of in containers (more annoying to set up, but easier to debug line by line):

10.1. Bring up only Postgres in Docker

docker compose up -d postgres

(This brings up only Postgres. The schema.sql is applied automatically.)

10.2. Install the Python dependencies of the MCP server

python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install -r requirements.txt

Export the environment variables in the same terminal:

export DATABASE_URL=postgresql://orcamento:orcamento@localhost:5432/orcamento
export TELEGRAM_TOKEN=seu_token_aqui
export GEMINI_API_KEY=sua_chave_aqui
export GEMINI_MODEL=gemini-3.6-flash

(On Windows PowerShell, use $env:DATABASE_URL = "...", etc.)

10.3. Install and run Nanobot

pip install -U nanobot-ai

Copy nanobot_config/config.json to ~/.nanobot/config.json, and nanobot_config/SOUL.md to ~/.nanobot/workspace/SOUL.md (create the workspace folder if it doesn't exist).

Run from the root of this project (the MCP server path in config.json is relative to that directory):

nanobot gateway --config nanobot_config/config.json --verbose

Test without Telegram (useful for debugging extraction)

nanobot agent -c nanobot_config/config.json -m "Paguei 120 no mercado no cartão hoje"

11. Next steps for the project

  1. Test the end-to-end flow with real messages and adjust SOUL.md according to the observed extraction errors (informal language, abbreviations, ambiguous values).

  2. Add the full reports tool (comparison between periods, expense evolution).

  3. Implement the recommendations layer: consolidate the data from resumo_por_categoria and send it to an advanced LLM via API.

  4. Automatically link expenses to the authenticated Telegram user (today the telegram_id is passed by the model when calling the tool).


Validation notice

The pipeline was validated in real execution with Docker: containers starting, MCP connected via stdio with the 3 registered tools, and Postgres insertions confirmed via psql. The syntax of docker-compose.yml and config JSONs is checked before each startup.

If something gets stuck exactly at docker compose up, start with section 8. Common problems.

A
license - permissive license
Not graded
quality - not tested
C
maintenance

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables AI assistants to manage personal expenses through natural conversation, supporting expense tracking, categorization, filtering, and financial summaries. Uses SQLite database to store expense records with full CRUD operations for comprehensive personal finance management.
    1
  • F
    license
    C
    quality
    D
    maintenance
    Enables AI assistants to manage personal finances by storing, analyzing, and exporting expense data using a persistent PostgreSQL database. Supports adding/editing expenses, generating spending summaries, detecting top categories, and creating monthly reports.
    12
  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables natural language management of personal expenses, including adding, listing, and summarizing expenses with local SQLite storage.

View all related MCP servers

Related MCP Connectors

  • Personal finance by conversation: expenses, receipts, statement import, budgets, net worth.

  • Multi-tenant Telegram gateway for AI agents — HTTP+stdio, 8 tools, MTProto User API

  • Log, query, and edit expenses, budgets, and accounts in Ledgy from any MCP-compatible AI assistant.

View all MCP Connectors

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/vinimeurer/orcamento-conversasional'

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