Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions docs/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,24 @@ Run the Mercado Pago contract test locally:

Never commit `.env` or any token. Use only **sandbox** credentials from the Test credentials section — never Production.

Run the BrasilAPI contract test locally. No credential is needed (the API is
public), so the gate is only an opt-in to hitting the network:

```bash
BRASIL_API_CONTRACT=1 npx vitest run packages/identity/brasil-api/src/__tests__/contract.test.ts
```

It covers a case a mocked test cannot see: BrasilAPI's edge answers `403` to
the User-Agent Node's `fetch` sends by default, so `get_cnpj` only works while
the server sets its own User-Agent header.

**A package that adds a contract test must exclude tests from its build.**
`test-utils/contract.ts` lives outside every package's `rootDir`, so a
`tsconfig.json` without `"exclude": ["src/__tests__"]` makes `npm run build`
fail *and* emit a CommonJS `test-utils/contract.js` next to it, which then
breaks every contract test file in the repo with "Vitest cannot be imported in
a CommonJS module using require()". Add the `exclude` in the same commit.

### Why this matters (for maintainers)

Every existing test in this repo mocks the network (`vi.mock` + `global.fetch`).
Expand Down
87 changes: 87 additions & 0 deletions packages/identity/brasil-api/src/__tests__/contract.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import { it, expect, beforeAll, vi } from "vitest";
import {
loadContractEnv,
describeContract,
parseToolResult,
} from "../../../../../test-utils/contract.js";

// ---------------------------------------------------------------------------
// Live contract test for BrasilAPI. No credential exists for this provider
// (public API), so the gate is opt-in only: set BRASIL_API_CONTRACT=1 to run
// it. It stays out of CI for the usual reason: it depends on a third party
// being up.
//
// What it is here for: get_cnpj is served behind an edge that rejects the
// User-Agent Node's fetch sends by default. That defect is invisible to a
// stubbed-fetch test, so the third-party half of the mechanism is produced
// here by calling the real API rather than being written by hand.
// ---------------------------------------------------------------------------

let callToolHandler: Function;

vi.mock("@modelcontextprotocol/sdk/server/index.js", () => {
class FakeServer {
constructor() {}
setRequestHandler(schema: any, handler: Function) {
if (JSON.stringify(schema).includes("tools/call")) callToolHandler = handler;
}
connect() {
return Promise.resolve();
}
}
return { Server: FakeServer };
});

vi.mock("@modelcontextprotocol/sdk/server/stdio.js", () => ({
StdioServerTransport: class {},
}));

await loadContractEnv();

// Banco do Brasil S.A., a public and permanent CNPJ record. No secret involved.
const PUBLIC_CNPJ = "00000000000191";
const CNPJ_URL = `https://brasilapi.com.br/api/cnpj/v1/${PUBLIC_CNPJ}`;

describeContract("mcp-brasil-api", "BRASIL_API_CONTRACT", () => {
beforeAll(async () => {
vi.resetModules();
await import("../index.js");
if (!callToolHandler) {
throw new Error("callToolHandler not registered: the import of ../index.js did not run");
}
});

it("get_cnpj resolves a real company against the live API", async () => {
const parsed = parseToolResult(
await callToolHandler({ params: { name: "get_cnpj", arguments: { cnpj: PUBLIC_CNPJ } } }),
);

expect(parsed.isError, `live get_cnpj failed: ${parsed.text}`).toBe(false);
expect((parsed.json as any)?.cnpj).toBe(PUBLIC_CNPJ);
}, 30000);

it("control: the edge is what rejects the default Node User-Agent", async () => {
// Same URL, same method, twice. The only difference is the header.
// `bare` inherits undici's default User-Agent ("node").
const bare = await fetch(CNPJ_URL, {
method: "GET",
headers: { "Content-Type": "application/json" },
});
const identified = await fetch(CNPJ_URL, {
method: "GET",
headers: {
"Content-Type": "application/json",
"User-Agent": "codespar-mcp-dev-latam/mcp-brasil-api/contract-control",
},
});

// Positive control: if this one fails, BrasilAPI is down or rate-limiting
// this host, and the assertion below carries no information.
expect(identified.ok, `identified request failed with ${identified.status}`).toBe(true);

expect(
bare.ok,
`bare request unexpectedly succeeded (${bare.status}): BrasilAPI may have dropped the User-Agent gate`,
).toBe(false);
}, 30000);
});
76 changes: 76 additions & 0 deletions packages/identity/brasil-api/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,3 +241,79 @@ describe("mcp-brasil-api", () => {
});
});
});

// ---------------------------------------------------------------------------
// Outbound HTTP identity
//
// Node's fetch (undici) fills in "User-Agent: node" when the caller does not
// set one, and BrasilAPI's edge answers 403 to that UA on the CNPJ route, so
// get_cnpj fails in normal use for everyone running this server. Measured
// live against brasilapi.com.br on 2026-08-28 (Node v25.5.0):
//
// GET /cnpj/v1/00000000000191 User-Agent: node -> 403
// GET /cnpj/v1/00000000000191 User-Agent: codespar-mcp-dev-... -> 200
// GET /cep/v1/01001000 User-Agent: node -> 200
//
// (the CEP route answers 200 either way, which is why only CNPJ surfaced).
// These tests pin the header on the request this server actually builds; the
// live half of the evidence is in contract.test.ts, behind BRASIL_API_CONTRACT.
// ---------------------------------------------------------------------------
describe("outbound HTTP identity", () => {
// What undici puts on the wire when no User-Agent is supplied. This is the
// value BrasilAPI rejects, so it is the value the request must not carry.
const NODE_DEFAULT_UA = "node";

function headersOfCall(callIndex: number): Headers {
const [, init] = mockFetch.mock.calls[callIndex];
return new Headers((init?.headers ?? {}) as HeadersInit);
}

it("sends an identifying User-Agent on get_cnpj", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ cnpj: "00000000000191" }),
});

await callToolHandler({
params: { name: "get_cnpj", arguments: { cnpj: "00000000000191" } },
});

const headers = headersOfCall(0);

// Positive control for this assertion's instrument: a header the server
// has always set must be visible here. If this one is null the probe is
// broken and the User-Agent assertions below mean nothing.
expect(headers.get("content-type")).toBe("application/json");

const ua = headers.get("user-agent");
expect(
ua,
"no User-Agent on the outgoing request: undici will send 'node' and BrasilAPI answers 403 on /cnpj",
).not.toBeNull();
expect(ua).not.toBe(NODE_DEFAULT_UA);
expect(ua).toMatch(/mcp-brasil-api\/\d+\.\d+\.\d+/);
});

it("sends it on every route, not only CNPJ", async () => {
const routes: Array<[string, Record<string, unknown>]> = [
["get_cep", { cep: "01001000" }],
["get_banks", {}],
["get_holidays", { year: 2026 }],
];

for (const [name, args] of routes) {
mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) });
await callToolHandler({ params: { name, arguments: args } });
}

expect(mockFetch.mock.calls).toHaveLength(routes.length);

routes.forEach(([name], i) => {
const headers = headersOfCall(i);
expect(headers.get("content-type"), `${name}: probe broken`).toBe("application/json");
const ua = headers.get("user-agent");
expect(ua, `${name} went out without a User-Agent`).not.toBeNull();
expect(ua, `${name} went out with the Node default UA`).not.toBe(NODE_DEFAULT_UA);
});
});
});
11 changes: 10 additions & 1 deletion packages/identity/brasil-api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,19 @@ function validationError(msg: string) {

const BASE_URL = "https://brasilapi.com.br/api";

// Every request must identify itself. Node's fetch (undici) supplies
// "User-Agent: node" when the caller leaves the header out, and BrasilAPI's
// edge answers 403 Forbidden to that UA on /cnpj, so get_cnpj failed for
// every user of this server. Measured live on 2026-08-28:
// /cnpj/v1/00000000000191 with "node" -> 403; with this string -> 200.
// Format follows the other servers in this repo (see payments/malga,
// payments/rinne).
const USER_AGENT = "codespar-mcp-dev-latam/mcp-brasil-api/0.2.2";

async function brasilApiRequest(path: string): Promise<unknown> {
const res = await fetch(`${BASE_URL}${path}`, {
method: "GET",
headers: { "Content-Type": "application/json" },
headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT },
});
if (!res.ok) {
const err = await res.text();
Expand Down
3 changes: 2 additions & 1 deletion packages/identity/brasil-api/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@
"esModuleInterop": true,
"declaration": true
},
"include": ["src"]
"include": ["src"],
"exclude": ["src/__tests__"]
}
Loading