Skip to main content
Glama
Woovi MCP Server

Woovi MCP Server

by izaakdias
README.md
# woovi-mcp-server

![CI](https://github.com/izaakdias/woovi-mcp-server/actions/workflows/ci.yml/badge.svg)

An MCP (Model Context Protocol) server that lets AI assistants such as Claude work with the
[Woovi/OpenPix](https://developers.woovi.com) Pix API: create and look up charges, manage
customers, read transactions and balance, issue refunds, and get exact business summaries.

Built for the [Woovi AI Engineer challenge](https://woovibr.github.io/jobs/challenges/mcp-woovi-api/)
in Python with the official MCP SDK (`mcp` 2.x) and Pydantic.

```
You:     Cobra R$ 25,90 da Maria Silva pelo pedido 1042 e me manda o Pix copia e cola.
Claude:  → create_charge(value_cents=2590, correlation_id="order-1042", customer={...})
         Pronto. Cobrança order-1042 de R$ 25,90 criada (expira amanhã às 12h):
         00020101021226950014br.gov.bcb.pix...
```

## What it exposes

**15 tools.** The 10 required ones, plus 5 that compose them:

| Area | Tools |
|---|---|
| Charges | `create_charge`, `get_charge`, `list_charges` |
| Customers | `create_customer`, `get_customer`, `list_customers` |
| Transactions & balance | `get_transactions`, `get_balance` |
| Refunds | `create_refund` (marked destructive), `get_refund` |
| Bonus | `list_accounts`, `get_customer_charges`, `summarize_sales`, `reconcile_payments`, `list_webhook_events` |

**Resources.**

| URI | Content |
|---|---|
| `woovi://balance` | Live balance of the default account (cached briefly) |
| `woovi://accounts/{account}/balance` | Live balance of one configured account |
| `woovi://docs` and `woovi://docs/{tool}` | Endpoint documentation snippets |
| `woovi://webhooks/schemas` and `woovi://webhooks/schemas/{event}` | JSON Schemas of the 8 webhook events |
| `woovi://events/recent` | Last webhook events received; subscribers are notified of updates |

**Prompts:** `daily_summary`, `customer_report`, `reconciliation_check`.

The full catalog, with every parameter and a real input and output for each tool, is in
[docs/TOOLS.md](docs/TOOLS.md). It is generated from the running server, so it cannot drift
from the code.

## Quick start

You need Python 3.11+.

```bash
git clone https://github.com/izaakdias/woovi-mcp-server && cd woovi-mcp-server
python -m venv .venv && .venv/bin/pip install -e .
```

To try it without a Woovi account, run `woovi-mcp --demo`. It serves a seeded, in-memory fake of the
Woovi API: a small store with paid, expired and open charges, a customer, a balance and refunds.
The fake is the same one the tests use. Point your MCP client at it to explore every tool, resource
and prompt with no real money involved.

For the real API, get an AppID from the Woovi **sandbox** (app.woovi-sandbox.com → API/Plugins) and
set it in the client configuration below, or in `.env` (see `.env.example`).

> **Validation status.**
> - The request and response shapes follow Woovi's official SDKs (Node, PHP and n8n) and API docs.
> - They are exercised end to end against the fake in [`src/woovi_mcp/fake.py`](src/woovi_mcp/fake.py).
> - I have not yet run this server against the live sandbox, because the sandbox was not reachable from
>   my network while I built it.
> - Every response envelope is unwrapped defensively (`data.get("charge") or data`), and Woovi's own
>   error messages are passed through. A field-name difference would therefore show up as a clear
>   error, not a crash. If you find one, an issue is very welcome.

### Claude Desktop

Add this to `claude_desktop_config.json` (macOS:
`~/Library/Application Support/Claude/claude_desktop_config.json`). A copy is in
[`claude_desktop_config.example.json`](claude_desktop_config.example.json).

```json
{
  "mcpServers": {
    "woovi": {
      "command": "/absolute/path/to/woovi-mcp-server/.venv/bin/woovi-mcp",
      "env": {
        "WOOVI_APP_ID": "your-sandbox-app-id",
        "WOOVI_BASE_URL": "https://api.woovi-sandbox.com"
      }
    }
  }
}
```

### Claude Code

```bash
claude mcp add woovi --env WOOVI_APP_ID=your-sandbox-app-id -- /absolute/path/to/.venv/bin/woovi-mcp
claude mcp add woovi-demo -- /absolute/path/to/.venv/bin/woovi-mcp --demo   # no account needed
```

### HTTP mode (webhooks and real-time events)

```bash
woovi-mcp --http --port 8000
```

This serves Streamable HTTP MCP at `/mcp`, plus three routes:

- `POST /webhooks/woovi`: receives Woovi webhooks and verifies their signature;
- `GET /events`: a Server-Sent Events stream of payment notifications;
- `GET /health`.

## Configuration

| Variable | Default | Meaning |
|---|---|---|
| `WOOVI_APP_ID` | required | AppID (the `Authorization` header) |
| `WOOVI_BASE_URL` | `https://api.woovi-sandbox.com` | Use `https://api.woovi.com` for production |
| `WOOVI_ACCOUNTS` | none | Multi-account: `store,events`, then `WOOVI_STORE_APP_ID`, `WOOVI_STORE_BASE_URL`, ... |
| `WOOVI_DEFAULT_ACCOUNT` | first account | Account used when a tool gets no `account` |
| `WOOVI_TIMEOUT_SECONDS` | `15` | Per-request timeout (connect timeout ≤ 5 s) |
| `WOOVI_MAX_RETRIES` | `3` | Retries on 429, 5xx, timeouts and network errors |
| `WOOVI_CACHE_TTL_SECONDS` | `30` | Balance and customer cache; `0` disables it |
| `WOOVI_MASK_PII` | `true` | Mask CPF/CNPJ, phone and e-mail in responses |
| `WOOVI_WEBHOOK_HMAC_SECRET` | none | Verify `x-openpix-signature` (HMAC-SHA1) |
| `WOOVI_WEBHOOK_PUBLIC_KEY` | none | Verify `x-webhook-signature` (RSA-SHA256) with Woovi's public key |
| `WOOVI_LOG_LEVEL` | `INFO` | JSON logs go to stderr; stdout belongs to the stdio transport |

A missing or wrong variable stops the server at startup with a message naming the variable to fix.

## Architecture

```mermaid
flowchart LR
    subgraph Client["AI assistant (Claude Desktop / Code)"]
        LLM[Model]
    end
    subgraph Server["woovi-mcp-server"]
        T["MCP layer<br/>tools · resources · prompts<br/>(server.py)"]
        V["Validation<br/>Pydantic models"]
        C["Cache (TTL + stale fallback)"]
        M["PII masking"]
        A["Analytics<br/>(pure functions)"]
        W["WooviClient<br/>timeouts · retries · typed errors<br/>(no MCP dependency)"]
        H["Webhook intake + EventHub"]
    end
    Woovi[(Woovi API<br/>sandbox / prod)]

    LLM -- "stdio or Streamable HTTP" --> T
    T --> V --> W --> Woovi
    T --> C --> W
    T --> A
    T --> M --> LLM
    Woovi -- "POST /webhooks/woovi (signed)" --> H
    H -- "SSE /events" --> Dash[Dashboards / curl]
    H -- "resources/updated + cache invalidation" --> T
```

```
src/woovi_mcp/
├── woovi/            reusable API client: no MCP import, usable from any Python code
│   ├── client.py     HTTP, retries, pagination, one method per endpoint
│   ├── models.py     Pydantic inputs (CPF/CNPJ check digits, centavos, dates)
│   └── errors.py     typed errors with actionable messages
├── server.py         MCP tools, resources, prompts, HTTP routes
├── analytics.py      totals, conversion, reconciliation (pure, tested)
├── cache.py          async TTL cache, single-flight, stale fallback
├── masking.py        PII masking and credential stripping
├── webhooks.py       signature checks, event hub, SSE
├── reference.py      endpoint docs and webhook schemas served as resources
└── config.py         environment and multi-account settings
```

## Design decisions and trade-offs

**Tools are shaped for a model, not mirrored from the REST API.**
- Names are `verb_noun` and consistent.
- Every parameter has a description that says its unit and format: `value_cents`, "R$ 10,50 = 1050", "YYYY-MM-DD".
- List responses return `page.next_skip`, so the model never has to work out pagination.
- Amounts come back both in centavos and formatted (`"R$ 25,90"`), so the model does not divide by 100 and get it wrong.

**The model does not do arithmetic.** `summarize_sales`, `get_customer_charges` and
`reconcile_payments` compute totals, conversion and mismatches in code (`analytics.py`) and
return finished numbers. Models are unreliable at adding hundreds of values from JSON. The
prompts tell them to use these numbers as-is.

**Money safety.**
- `create_refund` is annotated `destructive_hint=True`, so clients ask the user before running it.
- Its description says it moves money.
- It refuses unpaid charges before calling Woovi.
- `create_charge` and `create_refund` always send a `correlationID` (yours, or a generated one). Woovi uses it for idempotency, so a retry after a lost response cannot charge or refund twice. This is also the only reason a POST is allowed to be retried at all.
- Values above R$ 1 million are rejected as a probable unit mistake.

**Errors are for acting on, not for debugging.**
- Every Woovi failure becomes a typed error with a message that says what to do next. For example, a 401 says the AppID may be from the other environment.
- The error also carries a `retryable` flag.
- Input mistakes, such as a bad CPF check digit or a reversed date range, are caught before any HTTP call, with the field name.

**Security.**
- The AppID lives only in the HTTP client's headers. It is hidden from `repr`, never logged, never returned, and a test asserts that.
- CPF/CNPJ, phone and e-mail are masked in tool responses by default. Woovi still receives the full values.
- Request logs mask tax IDs in URL paths, and httpx's own URL logging is silenced.
- IDs are validated and URL-encoded before they go into a path, so `../account` is rejected.
- Webhooks need a valid signature (HMAC or RSA). Unsigned requests get 401, and an unconfigured server returns 503 instead of accepting anything.

**Robustness.**
- Timeouts on every call.
- Exponential backoff with jitter on 429, 5xx and network errors.
- `Retry-After` is honored up to 30 s. A longer wait is returned to the model as "retry after N s" instead of blocking the conversation.
- Balance and customer reads go through a TTL cache that shares concurrent misses. When Woovi is down, the cache serves the last known value marked `stale`, which is the "graceful degradation" requirement.

**Bonus points covered.**
- Caching with TTL.
- Multi-account: `account` on every tool, plus `list_accounts`.
- Analytics and composable tools.
- Webhooks with SSE push: verified intake, an `/events` stream, MCP `resources/updated` notifications, and cache invalidation.
- Progress notifications while long aggregations page through the API.

**Not done, on purpose.**
- **OAuth.** Woovi's API authenticates with an AppID. In HTTP mode, the MCP endpoint and `/events` have no auth of their own, so the server binds to `127.0.0.1` by default; put it behind your gateway before exposing it. The SDK supports an OAuth resource server (`auth=`/`token_verifier=`), and that is the natural next step.
- **Streaming exports.** Large reads report progress instead of streaming partial results.
- **Durable webhook events.** Events are kept in memory (the last 200). A multi-replica deployment would swap `EventHub` and the SDK's `SubscriptionBus` for Redis pub/sub.

## Tests

```bash
.venv/bin/pip install -e ".[dev]"
.venv/bin/pytest            # 45 tests, about 0.5 s, no network
.venv/bin/ruff check . && .venv/bin/ruff format --check .
```

- **Unit tests** cover the API client, validation, masking, cache and analytics.
- **Integration tests** connect a real MCP client to the server in-process. The server talks to an in-memory fake of the Woovi API ([src/woovi_mcp/fake.py](src/woovi_mcp/fake.py)) with the same paths, envelopes and pagination.
- **Fault injection** covers 429 with `Retry-After`, 503, timeouts, connection errors, a wrong AppID and signed and unsigned webhooks.

To regenerate the tool catalog after a change:

```bash
python scripts/gen_tool_catalog.py
```

## License

MIT

TDQS

A3.8/5.0

Scored across 15 tools

Disambiguation4/5

Most tools target a distinct resource+action, and the descriptions actively disambiguate overlapping ones (list_charges explicitly redirects to summarize_sales for totals, get_customer_charges is documented as a composition of get_customer + list_charges). The remaining overlap among list_charges, get_transactions, summarize_sales and reconcile_payments is real but navigable thanks to the guidance in the descriptions.

Naming Consistency5/5

Every tool follows a predictable snake_case verb_noun pattern (create_charge, get_customer, list_charges, get_balance, summarize_sales). The verbs are used consistently for the same kinds of operations across charges, customers and refunds, so an agent can guess names reliably.

Tool Count5/5

15 tools is within a well-scoped range for a payments server covering charges, customers, refunds, transactions, balance, reporting and webhooks. Each tool maps to a concrete operation rather than a redundant wrapper.

Completeness3/5

Core flows (create/get/list charges, customers, refunds, balance, reporting, reconciliation) are covered, but lifecycle gaps exist: there is no way to cancel or expire a charge, no list_refunds, no update/delete for customers, and webhooks can only be read, not registered. These are notable missing operations an agent may need for real payment workflows.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues