Skip to main content
Glama

generate_fa2_invoice

Generates a KSeF-compliant FA(2) XML invoice from structured invoice data, ready for submission to KSeF. Requires seller tax_id as a 10-digit Polish NIP.

Instructions

Generate a KSeF-compliant FA(2) XML invoice from structured invoice data.

Returns the FA(2) XML string ready for submission to KSeF. The seller's tax_id must be a Polish NIP (10 digits).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
invoiceYesCountry-agnostic invoice document envelope. Country adapters read/write this model via BaseDocumentGenerator.generate() and BaseDocumentParser.to_invoice_document(). document_type: Country-specific code (IT: TD01–TD28, UBL: 380/381/384, DE: RE/GU…). transmission_format: Platform routing hint (IT: FPA12/FPR12, FR: B2B/B2BInt/B2C).

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • FA2Generator.generate() — core handler that builds the FA(2) XML string from an InvoiceDocument, wrapping Naglowek, Podmiot1/Podmiot2, Fa sections with VAT fields, payment, invoice lines, and annotations.
    async def generate(self, invoice: InvoiceDocument) -> str:
        try:
            now_utc = _dt.datetime.now(_dt.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
            vat_fields = _vat_summary_fields(invoice.vat_summary or [])
            payment = _payment_block(invoice)
    
            xml = (
                f'<?xml version="1.0" encoding="UTF-8"?>\n'
                f'<Faktura xmlns="{_NS}"\n'
                f'         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n'
                f"  <Naglowek>\n"
                f'    <KodFormularza kodSystemowy="FA (2)" wersjaSchemy="1-0E">FA</KodFormularza>\n'
                f"    <WariantFormularza>2</WariantFormularza>\n"
                f"    <DataWytworzenieFa>{now_utc}</DataWytworzenieFa>\n"
                f"    <SystemInfo>{xml_escape(_SYSTEM_INFO)}</SystemInfo>\n"
                f"  </Naglowek>\n"
                f"  {_party_block(invoice.seller, 'Podmiot1').strip()}\n"
                f"  {_party_block(invoice.buyer, 'Podmiot2').strip()}\n"
                f"  <Fa>\n"
                f"    <KodWaluty>{xml_escape(invoice.currency)}</KodWaluty>\n"
                f"    <P_1>{xml_escape(str(invoice.date))}</P_1>\n"
                f"    <P_2>{xml_escape(invoice.number)}</P_2>\n"
                f"    {vat_fields}\n"
                f"    {payment}\n"
                f"    <Adnotacje>\n"
                f"      <P_16>2</P_16>\n"
                f"      <P_17>2</P_17>\n"
                f"      <P_18>2</P_18>\n"
                f"      <P_18A>2</P_18A>\n"
                f"      <P_23>2</P_23>\n"
                f"    </Adnotacje>\n"
                f"    {_invoice_lines(invoice).strip()}\n"
                + (f"    <StopkaFaktury>{xml_escape(invoice.note)}</StopkaFaktury>\n" if invoice.note else "")
                + f"  </Fa>\n"
                f"</Faktura>\n"
            )
            return xml
        except Exception as exc:
            raise DocumentGenerationError(f"FA(2) generation failed: {exc}") from exc
  • generate_fa2_invoice — MCP tool handler registered via @mcp.tool, delegates to _fa2_generator.generate(invoice).
    @mcp.tool
    async def generate_fa2_invoice(invoice: InvoiceDocument) -> str:
        """Generate a KSeF-compliant FA(2) XML invoice from structured invoice data.
    
        Returns the FA(2) XML string ready for submission to KSeF.
        The seller's tax_id must be a Polish NIP (10 digits).
        """
        return await _fa2_generator.generate(invoice)
  • @mcp.tool decorator registers generate_fa2_invoice as a named MCP tool with FastMCP server.
    @mcp.tool
    async def generate_fa2_invoice(invoice: InvoiceDocument) -> str:
        """Generate a KSeF-compliant FA(2) XML invoice from structured invoice data.
    
        Returns the FA(2) XML string ready for submission to KSeF.
        The seller's tax_id must be a Polish NIP (10 digits).
        """
        return await _fa2_generator.generate(invoice)
  • _party_block() — helper that renders Podmiot1/Podmiot2 XML blocks with tax IDs and address.
    def _party_block(party: InvoiceParty, tag: str) -> str:
        """Render a Podmiot1 (seller) or Podmiot2 (buyer) XML block."""
        name = party.name or f"{party.first_name or ''} {party.last_name or ''}".strip()
        nip = party.tax_id.identifier if party.tax_id.country_code.upper() == "PL" else ""
    
        id_block = f"<NIP>{xml_escape(nip)}</NIP>\n" if nip else ""
        if party.alt_tax_id:
            id_block += f"<KodUE>{xml_escape(party.tax_id.country_code.upper())}</KodUE>\n"
            id_block += f"<NrVatUE>{xml_escape(party.alt_tax_id.identifier)}</NrVatUE>\n"
        id_block += f"<Nazwa>{xml_escape(name)}</Nazwa>\n"
    
        addr_block = ""
        if party.address:
            a = party.address
            addr_block = (
                f"<Adres>\n"
                f"  <KodKraju>{xml_escape(a.country_code.upper())}</KodKraju>\n"
                f"  <AdresL1>{xml_escape(a.street or '')}</AdresL1>\n"
                + (f"  <KodPocztowy>{xml_escape(a.postal_code)}</KodPocztowy>\n" if a.postal_code else "")
                + f"  <Miejscowosc>{xml_escape(a.city or '')}</Miejscowosc>\n"
                + (f"  <Wojewodztwo>{xml_escape(a.province)}</Wojewodztwo>\n" if a.province else "")
                + f"</Adres>\n"
            )
    
        return (
            f"<{tag}>\n"
            f"  <DaneIdentyfikacyjne>\n"
            f"    {id_block.strip()}\n"
            f"  </DaneIdentyfikacyjne>\n"
            f"  {addr_block.strip()}\n"
            f"</{tag}>\n"
        )
  • _invoice_lines(), _payment_block(), _vat_summary_fields() — helpers that build FA(2) invoice line items, payment info, and VAT summary field blocks.
    def _invoice_lines(invoice: InvoiceDocument) -> str:
        rows = []
        for line in invoice.lines:
            rate_str = str(int(line.vat_rate)) if line.vat_rate == int(line.vat_rate) else str(line.vat_rate)
            rows.append(
                f"  <FaWiersz>\n"
                f"    <NrWierszaFa>{line.line_number}</NrWierszaFa>\n"
                f"    <P_7>{xml_escape(line.description)}</P_7>\n"
                f"    <P_8A>{xml_escape(line.unit_of_measure or 'szt')}</P_8A>\n"
                f"    <P_8B>{format_amount(line.quantity)}</P_8B>\n"
                f"    <P_9A>{_d(line.unit_price)}</P_9A>\n"
                f"    <P_11>{_d(line.total_price)}</P_11>\n"
                f"    <P_12>{xml_escape(rate_str)}</P_12>\n"
                + (f"    <P_12_XII>{xml_escape(line.vat_exemption_code)}</P_12_XII>\n" if line.vat_exemption_code else "")
                + f"  </FaWiersz>\n"
            )
        return "<FaWiersze>\n" + "".join(rows) + "</FaWiersze>\n"
    
    
    def _payment_block(invoice: InvoiceDocument) -> str:
        if not invoice.payment:
            return ""
        p = invoice.payment
        parts = []
        if p.due_date:
            parts.append(f"<P_6>{xml_escape(str(p.due_date))}</P_6>")
        if p.iban:
            parts.append(f"<RachunekBankowy><NrRB>{xml_escape(p.iban)}</NrRB></RachunekBankowy>")
        return "\n".join(parts)
Behavior3/5

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

No annotations are provided, so the description must carry the full burden. It states the tool returns an XML string and imposes a constraint on the seller tax_id, but it does not disclose other behaviors such as input validation or error handling. The description is adequate but minimal.

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

Conciseness5/5

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

The description is concise at three sentences, with the purpose stated first, followed by the output type, and ending with a key constraint. Every sentence adds value with no redundancy.

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

Completeness4/5

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

Given the rich input schema and the presence of an output schema, the description is largely complete. It provides the essential constraint (NIP) and output format. However, it could mention any validation that occurs during generation.

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

Parameters4/5

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

Schema description coverage is 100%, so baseline is 3. The description adds a crucial constraint: the seller's tax_id must be a Polish NIP (10 digits), which is not enforced by the schema alone. This adds meaningful guidance beyond the structured field.

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

Purpose5/5

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

The description clearly states that the tool generates a KSeF-compliant FA(2) XML invoice from structured data, and specifies the output format. It distinguishes itself from sibling tools like generate_fa3_invoice and generate_peppol_invoice by explicitly naming FA(2) and KSeF.

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

Usage Guidelines4/5

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

The description implies when to use this tool (for generating FA(2) invoices for KSeF) and mentions a critical prerequisite (seller NIP). However, it does not explicitly state when not to use it or name alternative tools for other formats.

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/cmendezs/mcp-ksef-pl'

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