"""Lexware Office MCP Server — Full Public API coverage.""" import os import json import logging from typing import Optional import httpx from mcp.server.fastmcp import FastMCP logging.basicConfig(level=logging.INFO) logger = logging.getLogger("lexware-mcp") BASE_URL = "https://api.lexware.io/v1" RATE_LIMIT_NOTE = "Lexware API rate limit: 2 requests/second." mcp = FastMCP("Lexware Office") def _get_headers() -> dict: token = os.environ.get("LEXWARE_API_KEY", "") if not token: raise ValueError("LEXWARE_API_KEY environment variable is not set. Please set it in Space secrets.") return { "Authorization": f"Bearer {token}", "Accept": "application/json", "Content-Type": "application/json", } async def _request(method: str, path: str, params: dict | None = None, body: dict | None = None) -> dict | list | str: """Make a request to the Lexware API.""" url = f"{BASE_URL}{path}" headers = _get_headers() async with httpx.AsyncClient(timeout=30.0) as client: if method == "GET": resp = await client.get(url, headers=headers, params=params) elif method == "POST": resp = await client.post(url, headers=headers, params=params, json=body) elif method == "PUT": resp = await client.put(url, headers=headers, json=body) elif method == "DELETE": resp = await client.delete(url, headers=headers) else: raise ValueError(f"Unsupported method: {method}") if resp.status_code == 204: return {"status": "success", "code": 204} if resp.headers.get("content-type", "").startswith("application/json"): return resp.json() else: return {"status_code": resp.status_code, "body": resp.text[:2000]} # ─── Profile ─────────────────────────────────────────────────────────────────── @mcp.tool() async def get_profile() -> dict: """Get the Lexware Office organization profile (company name, address, tax info).""" return await _request("GET", "/profile") # ─── Contacts ───────────────────────────────────────────────────────────────── @mcp.tool() async def list_contacts( email: Optional[str] = None, name: Optional[str] = None, number: Optional[int] = None, customer: Optional[bool] = None, vendor: Optional[bool] = None, page: int = 0, size: int = 25, ) -> dict: """List contacts with optional filters. Returns paginated results. Args: email: Filter by email address name: Filter by contact name number: Filter by contact number customer: Filter for customers only vendor: Filter for vendors only page: Page number (0-based) size: Page size (max 250) """ params = {"page": page, "size": min(size, 250)} if email: params["email"] = email if name: params["name"] = name if number is not None: params["number"] = number if customer is not None: params["customer"] = str(customer).lower() if vendor is not None: params["vendor"] = str(vendor).lower() return await _request("GET", "/contacts", params=params) @mcp.tool() async def get_contact(contact_id: str) -> dict: """Get a specific contact by ID. Args: contact_id: The UUID of the contact """ return await _request("GET", f"/contacts/{contact_id}") @mcp.tool() async def create_contact(contact_data: str) -> dict: """Create a new contact. Pass JSON string with contact fields. Args: contact_data: JSON string with contact data. Required fields vary. Example: {"version": 0, "roles": {"customer": {}}, "company": {"name": "Firma GmbH"}} Or for a person: {"version": 0, "roles": {"customer": {}}, "person": {"firstName": "Max", "lastName": "Mustermann"}} """ data = json.loads(contact_data) return await _request("POST", "/contacts", body=data) @mcp.tool() async def update_contact(contact_id: str, contact_data: str) -> dict: """Update an existing contact. Pass full contact JSON (including current version). Args: contact_id: The UUID of the contact contact_data: JSON string with updated contact data (must include 'version' field from GET response) """ data = json.loads(contact_data) return await _request("PUT", f"/contacts/{contact_id}", body=data) # ─── Invoices ───────────────────────────────────────────────────────────────── @mcp.tool() async def list_invoices( status: Optional[str] = None, page: int = 0, size: int = 25, ) -> dict: """List invoices via the voucherlist endpoint. Args: status: Filter by status: draft, open, paid, paidoff, voided, accepted, rejected page: Page number (0-based) size: Page size (max 250) """ params = {"page": page, "size": min(size, 250), "voucherType": "invoice"} if status: params["voucherStatus"] = status return await _request("GET", "/voucherlist", params=params) @mcp.tool() async def get_invoice(invoice_id: str) -> dict: """Get a specific invoice by ID. Args: invoice_id: The UUID of the invoice """ return await _request("GET", f"/invoices/{invoice_id}") @mcp.tool() async def create_invoice(invoice_data: str, finalize: bool = False) -> dict: """Create a new invoice (draft or finalized). Args: invoice_data: JSON string with invoice data. Example: {"voucherDate": "2026-04-16", "address": {"contactId": "CONTACT_UUID"}, "lineItems": [{"type": "custom", "name": "Beratung", "quantity": 1, "unitName": "Stunde", "unitPrice": {"currency": "EUR", "netAmount": 100.00, "taxRatePercentage": 19}}], "totalPrice": {"currency": "EUR"}} finalize: If True, invoice is finalized and gets a number. If False, saved as draft. """ data = json.loads(invoice_data) params = {"finalize": str(finalize).lower()} if finalize else None return await _request("POST", "/invoices", params=params, body=data) @mcp.tool() async def get_invoice_pdf(invoice_id: str) -> dict: """Download the PDF file of an invoice. Returns file download info. Args: invoice_id: The UUID of the invoice """ return await _request("GET", f"/invoices/{invoice_id}/file") # ─── Quotations ─────────────────────────────────────────────────────────────── @mcp.tool() async def list_quotations( status: Optional[str] = None, page: int = 0, size: int = 25, ) -> dict: """List quotations/offers via the voucherlist endpoint. Args: status: Filter by status: draft, open, accepted, rejected, voided page: Page number (0-based) size: Page size (max 250) """ params = {"page": page, "size": min(size, 250), "voucherType": "quotation"} if status: params["voucherStatus"] = status return await _request("GET", "/voucherlist", params=params) @mcp.tool() async def get_quotation(quotation_id: str) -> dict: """Get a specific quotation by ID. Args: quotation_id: The UUID of the quotation """ return await _request("GET", f"/quotations/{quotation_id}") @mcp.tool() async def create_quotation(quotation_data: str) -> dict: """Create a new quotation/offer. Args: quotation_data: JSON string with quotation data. Same structure as invoices. Example: {"voucherDate": "2026-04-16", "expirationDate": "2026-05-16", "address": {"contactId": "CONTACT_UUID"}, "lineItems": [{"type": "custom", "name": "Beratung", "quantity": 1, "unitName": "Stunde", "unitPrice": {"currency": "EUR", "netAmount": 100.00, "taxRatePercentage": 19}}], "totalPrice": {"currency": "EUR"}} """ data = json.loads(quotation_data) return await _request("POST", "/quotations", body=data) @mcp.tool() async def get_quotation_pdf(quotation_id: str) -> dict: """Download the PDF file of a quotation. Args: quotation_id: The UUID of the quotation """ return await _request("GET", f"/quotations/{quotation_id}/file") # ─── Articles ───────────────────────────────────────────────────────────────── @mcp.tool() async def list_articles( article_number: Optional[str] = None, gtin: Optional[str] = None, article_type: Optional[str] = None, page: int = 0, size: int = 25, ) -> dict: """List articles/products with optional filters. Args: article_number: Filter by article number gtin: Filter by GTIN/EAN article_type: Filter by type: PRODUCT or SERVICE page: Page number (0-based) size: Page size (max 250) """ params = {"page": page, "size": min(size, 250)} if article_number: params["articleNumber"] = article_number if gtin: params["gtin"] = gtin if article_type: params["type"] = article_type return await _request("GET", "/articles", params=params) @mcp.tool() async def get_article(article_id: str) -> dict: """Get a specific article by ID. Args: article_id: The UUID of the article """ return await _request("GET", f"/articles/{article_id}") @mcp.tool() async def create_article(article_data: str) -> dict: """Create a new article/product. Args: article_data: JSON string with article data. Example: {"title": "AI Beratung", "type": "SERVICE", "unitName": "Stunde", "price": {"currency": "EUR", "netPrice": 150.00, "taxRatePercentage": 19}} """ data = json.loads(article_data) return await _request("POST", "/articles", body=data) @mcp.tool() async def update_article(article_id: str, article_data: str) -> dict: """Update an existing article. Args: article_id: The UUID of the article article_data: JSON string with updated article data (must include 'version' field) """ data = json.loads(article_data) return await _request("PUT", f"/articles/{article_id}", body=data) @mcp.tool() async def delete_article(article_id: str) -> dict: """Delete an article. Args: article_id: The UUID of the article """ return await _request("DELETE", f"/articles/{article_id}") # ─── Vouchers (Belege) ─────────────────────────────────────────────────────── @mcp.tool() async def list_vouchers( voucher_type: Optional[str] = None, voucher_status: Optional[str] = None, page: int = 0, size: int = 25, ) -> dict: """List vouchers from the voucherlist with filters. Args: voucher_type: Filter by type: invoice, creditnote, orderconfirmation, quotation, deliverynote, downpaymentinvoice, dunning, purchaseinvoice, purchasecreditnote voucher_status: Filter by status: draft, open, paid, paidoff, voided, accepted, rejected page: Page number (0-based) size: Page size (max 250) """ params = {"page": page, "size": min(size, 250)} if voucher_type: params["voucherType"] = voucher_type if voucher_status: params["voucherStatus"] = voucher_status return await _request("GET", "/voucherlist", params=params) @mcp.tool() async def get_voucher(voucher_id: str) -> dict: """Get a specific voucher by ID (for incoming vouchers/Eingangsbelege). Args: voucher_id: The UUID of the voucher """ return await _request("GET", f"/vouchers/{voucher_id}") @mcp.tool() async def create_voucher(voucher_data: str) -> dict: """Create a new voucher (e.g., incoming invoice/Eingangsrechnung). Args: voucher_data: JSON string with voucher data. Example: {"type": "purchaseinvoice", "voucherNumber": "ER-001", "voucherDate": "2026-04-16", "totalGrossAmount": 119.00, "totalTaxAmount": 19.00, "taxType": "gross", "voucherItems": [{"amount": 119.00, "taxAmount": 19.00, "taxRatePercent": 19, "categoryId": "CATEGORY_UUID"}]} """ data = json.loads(voucher_data) return await _request("POST", "/vouchers", body=data) @mcp.tool() async def update_voucher(voucher_id: str, voucher_data: str) -> dict: """Update an existing voucher. Args: voucher_id: The UUID of the voucher voucher_data: JSON string with updated voucher data (must include 'version' field) """ data = json.loads(voucher_data) return await _request("PUT", f"/vouchers/{voucher_id}", body=data) # ─── Payments ───────────────────────────────────────────────────────────────── @mcp.tool() async def get_payments(invoice_id: str) -> dict: """Get payment information for an invoice. Args: invoice_id: The UUID of the invoice to get payments for """ return await _request("GET", f"/payments/{invoice_id}") # ─── Credit Notes ───────────────────────────────────────────────────────────── @mcp.tool() async def get_credit_note(credit_note_id: str) -> dict: """Get a specific credit note by ID. Args: credit_note_id: The UUID of the credit note """ return await _request("GET", f"/credit-notes/{credit_note_id}") @mcp.tool() async def create_credit_note(credit_note_data: str, finalize: bool = False, preceding_sales_voucher_id: Optional[str] = None) -> dict: """Create a new credit note (Gutschrift). Args: credit_note_data: JSON string with credit note data (same structure as invoices) finalize: If True, credit note is finalized immediately preceding_sales_voucher_id: Optional ID of the preceding sales voucher (invoice) this corrects """ data = json.loads(credit_note_data) params = {} if finalize: params["finalize"] = "true" if preceding_sales_voucher_id: params["precedingSalesVoucherId"] = preceding_sales_voucher_id return await _request("POST", "/credit-notes", params=params or None, body=data) @mcp.tool() async def get_credit_note_pdf(credit_note_id: str) -> dict: """Download the PDF file of a credit note. Args: credit_note_id: The UUID of the credit note """ return await _request("GET", f"/credit-notes/{credit_note_id}/file") # ─── Dunnings (Mahnungen) ──────────────────────────────────────────────────── @mcp.tool() async def get_dunning(dunning_id: str) -> dict: """Get a specific dunning/reminder by ID. Args: dunning_id: The UUID of the dunning """ return await _request("GET", f"/dunnings/{dunning_id}") @mcp.tool() async def create_dunning(dunning_data: str, finalize: bool = False) -> dict: """Create a new dunning/reminder (Mahnung). Args: dunning_data: JSON string with dunning data finalize: If True, dunning is finalized immediately """ data = json.loads(dunning_data) params = {"finalize": "true"} if finalize else None return await _request("POST", "/dunnings", params=params, body=data) @mcp.tool() async def get_dunning_pdf(dunning_id: str) -> dict: """Download the PDF file of a dunning. Args: dunning_id: The UUID of the dunning """ return await _request("GET", f"/dunnings/{dunning_id}/file") # ─── Delivery Notes (Lieferscheine) ────────────────────────────────────────── @mcp.tool() async def get_delivery_note(delivery_note_id: str) -> dict: """Get a specific delivery note by ID. Args: delivery_note_id: The UUID of the delivery note """ return await _request("GET", f"/delivery-notes/{delivery_note_id}") @mcp.tool() async def create_delivery_note(delivery_note_data: str, finalize: bool = False) -> dict: """Create a new delivery note (Lieferschein). Args: delivery_note_data: JSON string with delivery note data finalize: If True, delivery note is finalized immediately """ data = json.loads(delivery_note_data) params = {"finalize": "true"} if finalize else None return await _request("POST", "/delivery-notes", params=params, body=data) @mcp.tool() async def get_delivery_note_pdf(delivery_note_id: str) -> dict: """Download the PDF file of a delivery note. Args: delivery_note_id: The UUID of the delivery note """ return await _request("GET", f"/delivery-notes/{delivery_note_id}/file") # ─── Order Confirmations (Auftragsbestaetigungen) ──────────────────────────── @mcp.tool() async def get_order_confirmation(order_confirmation_id: str) -> dict: """Get a specific order confirmation by ID. Args: order_confirmation_id: The UUID of the order confirmation """ return await _request("GET", f"/order-confirmations/{order_confirmation_id}") @mcp.tool() async def create_order_confirmation(order_confirmation_data: str, finalize: bool = False) -> dict: """Create a new order confirmation (Auftragsbestaetigung). Args: order_confirmation_data: JSON string with order confirmation data finalize: If True, order confirmation is finalized immediately """ data = json.loads(order_confirmation_data) params = {"finalize": "true"} if finalize else None return await _request("POST", "/order-confirmations", params=params, body=data) @mcp.tool() async def get_order_confirmation_pdf(order_confirmation_id: str) -> dict: """Download the PDF file of an order confirmation. Args: order_confirmation_id: The UUID of the order confirmation """ return await _request("GET", f"/order-confirmations/{order_confirmation_id}/file") # ─── Down Payment Invoices (Abschlagsrechnungen) ───────────────────────────── @mcp.tool() async def get_down_payment_invoice(down_payment_invoice_id: str) -> dict: """Get a specific down payment invoice by ID. Args: down_payment_invoice_id: The UUID of the down payment invoice """ return await _request("GET", f"/down-payment-invoices/{down_payment_invoice_id}") @mcp.tool() async def get_down_payment_invoice_pdf(down_payment_invoice_id: str) -> dict: """Download the PDF file of a down payment invoice. Args: down_payment_invoice_id: The UUID of the down payment invoice """ return await _request("GET", f"/down-payment-invoices/{down_payment_invoice_id}/file") # ─── Recurring Templates ───────────────────────────────────────────────────── @mcp.tool() async def list_recurring_templates(page: int = 0, size: int = 25) -> dict: """List all recurring invoice templates. Args: page: Page number (0-based) size: Page size (max 250) """ params = {"page": page, "size": min(size, 250)} return await _request("GET", "/recurring-templates", params=params) @mcp.tool() async def get_recurring_template(template_id: str) -> dict: """Get a specific recurring template by ID. Args: template_id: The UUID of the recurring template """ return await _request("GET", f"/recurring-templates/{template_id}") # ─── Reference Data ────────────────────────────────────────────────────────── @mcp.tool() async def list_countries() -> dict: """Get the list of all countries supported by Lexware Office.""" return await _request("GET", "/countries") @mcp.tool() async def list_posting_categories() -> dict: """Get all posting/booking categories (Buchungskategorien) for voucher categorization.""" return await _request("GET", "/posting-categories") @mcp.tool() async def list_payment_conditions() -> dict: """Get all available payment conditions/terms (Zahlungsbedingungen).""" return await _request("GET", "/payment-conditions") @mcp.tool() async def list_print_layouts() -> dict: """Get all available print layouts for documents.""" return await _request("GET", "/print-layouts") # ─── Event Subscriptions (Webhooks) ────────────────────────────────────────── @mcp.tool() async def list_event_subscriptions() -> dict: """List all webhook/event subscriptions.""" return await _request("GET", "/event-subscriptions") @mcp.tool() async def create_event_subscription(subscription_data: str) -> dict: """Create a new webhook/event subscription. Args: subscription_data: JSON string with subscription data. Example: {"eventType": "invoice.changed", "callbackUrl": "https://your-server.com/webhook"} Event types: contact.changed, invoice.changed, quotation.changed, etc. """ data = json.loads(subscription_data) return await _request("POST", "/event-subscriptions", body=data) @mcp.tool() async def delete_event_subscription(subscription_id: str) -> dict: """Delete a webhook/event subscription. Args: subscription_id: The UUID of the event subscription """ return await _request("DELETE", f"/event-subscriptions/{subscription_id}") # ─── Files ──────────────────────────────────────────────────────────────────── @mcp.tool() async def get_file_info(file_id: str) -> dict: """Get download info for a file. Args: file_id: The UUID of the file """ return await _request("GET", f"/files/{file_id}") # ─── Server startup ────────────────────────────────────────────────────────── if __name__ == "__main__": import uvicorn port = int(os.environ.get("PORT", 7860)) logger.info(f"Starting Lexware MCP Server on port {port}") # Get the default MCP ASGI app (serves /mcp endpoint) inner_app = mcp.streamable_http_app() # ASGI middleware that rewrites / and /mcp/ to /mcp (avoids redirect on HF) async def app(scope, receive, send): if scope["type"] == "http": path = scope.get("path", "") if path in ("/", "/mcp/"): scope = dict(scope) scope["path"] = "/mcp" scope["raw_path"] = b"/mcp" await inner_app(scope, receive, send) uvicorn.run(app, host="0.0.0.0", port=port, log_level="info")