agentleFS
useinviouseinvio/nfse-sdk/llms.txt

nfse-sdk

llms.txt4 starsChanged 20 days agoMITView on GitHub

TypeScript SDK for Brazil's NFS-e Nacional (SEFIN/ADN). It issues, queries and cancels national service invoices: builds the DPS from JSON, validates it against the official XSD, signs it (XMLDSIG), sends it over mTLS with an ICP-Brasil A1 certificate, and returns SEFIN's answer as typed results and typed errors. It is not a tax engine: service codes, regime, tax blocks and DPS numbering always come from the user. This file is for AI assistants writing code that uses the package. To…

  • Installs packages
  • In this repositoryOne other file it gives its agents.

The file

We split this llms.txt into the rules it gives an agent

1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Keep fiscal codes and amounts as strings (leading zeros matter).

    line 39

≈ “Common” is an estimate: at least 1 in 5 of the 4,067 llms.txt files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
llms.txt
# @useinvio/nfse-sdk

> TypeScript SDK for Brazil's NFS-e Nacional (SEFIN/ADN). It issues, queries and cancels national service invoices: builds the DPS from JSON, validates it against the official XSD, signs it (XMLDSIG), sends it over mTLS with an ICP-Brasil A1 certificate, and returns SEFIN's answer as typed results and typed errors. It is not a tax engine: service codes, regime, tax blocks and DPS numbering always come from the user.

This file is for AI assistants writing code that uses the package. To change the SDK itself, read `AGENTS.md` in the repository.

## Install and certificate

```bash
npm install @useinvio/nfse-sdk   # Node.js >= 20, ESM, no native binaries
```

```ts
import { NfseCertificate } from '@useinvio/nfse-sdk';
const certificado = NfseCertificate.fromEnv(); // NFSE_CERT_PATH or NFSE_CERT_BASE64, plus NFSE_CERT_PASSWORD or NFSE_CERT_PASSWORD_FILE
```

`NfseCertificate` keeps the private key out of the object; `console.log` and `JSON.stringify` show only CNPJ/CPF, validity and fingerprint. Never log, commit or ask for the `.pfx` or its password. Other loaders: `fromFile(path, pwd)`, `fromBase64(b64, pwd)`, `fromPfx(buffer, pwd)`, `fromPem({ key, cert })`. Errors: `CertificateValidationError` with `code` (`CERTIFICATE_INVALID_PASSWORD`, `CERTIFICATE_EXPIRED`, ...).

## Issue

```ts
import { emitirNfse, EmitirNotaError, explicarErros, type DpsJsonRequest } from '@useinvio/nfse-sdk';

const nota: DpsJsonRequest = {
  ambiente: 'restrita', // official sandbox; 'producao' is legally valid
  prestador: { cnpj, cLocEmi, serie, opSimpNac, regEspTrib },
  servico: { cTribNac, xDescServ, cLocPrestacao },
  emissao: { nDPS, valores: { vServ: '1500.00' }, tributacaoMunicipal, tributacaoFederal, totTrib },
};
try {
  const { chaveAcesso, dpsId, nfseXml } = await emitirNfse(nota, certificado);
} catch (error) {
  if (error instanceof EmitirNotaError) console.table(explicarErros(error.erros)); // official rule per code
  else throw error; // network/timeout: the outcome is unknown, see "Recover"
}
```

- Keep fiscal codes and amounts as strings (leading zeros matter). Do not invent `cTribNac`, IBGE codes, regime or tax blocks; ask the user. Field reference: `JSON_MAPPING.md`.
- Validate without sending: `validateDpsJsonRequest(nota)` returns `{ valid, issues, warnings }`; `buildDpsFromJson(nota)` returns `{ id, xml }`.
- Persist before sending: `const p = prepararNota(nota, cert)` then `transmitirNotaPreparada(p, cert)`.
- Each `nDPS` (with `serie`) produces one invoice; increment it after a successful emission.

## Recover after a timeout (never resend blindly)

```ts
const existing = await recuperarNfsePorDps(p.dpsId, certificado, p.ambiente, { retries: 3 });
// existing !== null: it was issued. null: SEFIN never got it; resend the SAME prepared DPS.
```

POST requests (emission, events) are never retried by the SDK. `{ timeoutMs, retries, signal }` works on every call; `retries` applies to GETs only.

## Query, PDF, cancel

```ts
const { nfseXml, resumo } = await obterNfse(chaveAcesso, certificado); // ConsultaNfseError, .notFound on 404
const { pdf } = await baixarDanfse(chaveAcesso, certificado);
await cancelarNfse({ chaveAcesso, cMotivo: '1', xMotivo: 'Nota emitida com valor incorreto' }, certificado); // RegistrarEventoError
await cancelarNfsePorSubstituicao({ chaveAcesso, chaveSubstituta, cMotivo: '01' }, certificado);
```

`cMotivo` for cancellation: `1` issuing error, `2` service not provided, `9` other; `xMotivo` 15 to 255 characters. `lerNfse(xml)` reads an NFS-e XML you already have. ADN: `distribuirDfePorNsu`, `consultarConvenio`, `consultarAliquota`, `consultarRetencoes`.

## Client

```ts
const client = new NfseClient({ environment: 'sandbox', certificate: certificado, defaults: { prestador, servico }, request: { timeoutMs: 30_000, retries: 2 } });
await client.invoices.create({ emissao });          // also retrieve, recover, cancel, cancelBySubstitution, danfse
```

## Rejection codes

`explicarRejeicao('E0014')` returns the official message, rule and XML field from the gov.br annexes (Anexo I v1.01, Anexo II v1.01), `conhecida: false` for codes not in the catalog. `explicarErros(error.erros)` explains a whole rejection.

## Tests without a certificate or network

```ts
import { createTestCertificate, installMockSefin } from '@useinvio/nfse-sdk/testing';
const mock = installMockSefin();                    // in-process SEFIN + ADN; validates XSD and signatures
const { certificate } = createTestCertificate({ cnpj: '12345678000195' });
// ... emitirNfse / obterNfse / cancelarNfse work as usual ...
mock.rejectNext('E0312'); mock.dropResponseNext(); // script rejections and dropped connections
mock.restore();
```

## Command line

`npx nfse init` (sample nota.json), `nfse doctor`, `nfse validate nota.json`, `nfse emit nota.json [--mock] [--producao] [--yes] [--json]`, `nfse get <chave>`, `nfse danfse <chave>`, `nfse cancel <chave> --motivo 1 --justificativa "..."`, `nfse recover <dpsId>`, `nfse explain E0014`. Exit codes: 0 ok, 1 error, 2 SEFIN rejection.

## AI agents and MCP

- `npx -y @useinvio/nfse-mcp`: MCP stdio server. Env: certificate vars above, `NFSE_AMBIENTE`, `NFSE_MCP_ALLOW_WRITE=1` (emit/cancel), `NFSE_MCP_MOCK=1` (mock SEFIN).
- `@useinvio/nfse-sdk/agent`: `nfseAgentTools` (read-only: `validate_dps`, `build_dps_xml`, `get_nfse`, `recover_nfse_by_dps`, `explain_rejection`) and `createNfseAgentToolkit({ allowWrite })`, which adds `prepare_*`/`confirm_*` emission and cancellation. Certificate and environment are host context, never tool input. Only call `confirm_*` after the user approves the summary from `prepare_*`.
- Claude Code plugin: `/plugin install nfse-nacional --marketplace useinvio/nfse-sdk`.

## Docs

- `docs/README.md` (pt-BR): tutorial, guides, API and error reference.
- `docs/referencia/erros.md`: every error class and code.
- `docs/referencia/ambientes.md`: SEFIN and ADN URLs and endpoints.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.