Saltar a contenido

SAP Business One MCP Server Sample

Era el README del repo hasta 2026-11-13. Las tablas de herramientas se actualizan cuando cambian las herramientas (ver CLAUDE.md).


Introduction

As of SAP Business One 10.0 FP2608, a sample for SAP Business One MCP Server is provided to demonstrate how SAP B1 Service Layer OData services can be exposed as dynamic tools for AI agents that support the Model Context Protocol (MCP).

The sample server is designed to be minimal and easy to understand, while still showcasing the core patterns and capabilities of an MCP server. Instead of registering hundreds of individual CRUD tools (one per entity × operation), the server uses a progressive discovery architecture that collapses hundreds of potential tools down to several intelligent, reusable tools.

This design gives AI assistants the ability to: - Discover relevant B1 entities through lightweight semantic search - Understand complete entity schemas including properties, types, and capabilities - Execute authenticated CRUD operations with automatic OData query generation

Natural language requests such as "Show me the top 10 customers by balance" or "Create a purchase order for vendor V00001" are automatically translated into proper Service Layer API calls.

This project is provided as a sample for reference and learning purposes only. It is not necessarily a production-ready product. SAP B1 partners and developers are encouraged to study the architecture, adapt the code, evaluate the built-in capabilities, and build their own MCP server implementations tailored to their specific business requirements and deployment environments.

Version Requirement: This MCP server requires SAP Business One 10.0 FP2608 or higher. It relies on Service Layer APIs introduced in FP2608 and will not function correctly with earlier versions.

Earlier releases (e.g. FP2602): the only FP2608-specific API used is PersonalFieldsSetupsService_GetPersonalFieldsByTable. Set PERSONAL_FIELDS_SOURCE=static with a PERSONAL_FIELDS_FILE map to run without it — see Personal fields source. This mode is not supported by SAP.

> MCP Protocol Version: This sample implements MCP protocol version 2025-11-25, which is the latest version of the Model Context Protocol specification for SAP Business One 10.0 FP2608. MCP clients that connect to this server must also support protocol version 2025-11-25. As the MCP protocol continue to evolve, this sample will be updated to keep pace with new specification releases.

Architecture Overview

The MCP server sits between an AI agent (Cline, GitHub Copilot, Cursor, etc.) and SAP B1 Service Layer. The SAP Business One MCP Server implements a modern, layered architecture that transforms OData service contracts into AI-friendly MCP tools. The architecture is organized around a progressive discovery pattern that balances token efficiency with comprehensive capability exposure.

arch.svg

In this architecture, the MCP client in the AI agent interacts with the MCP server through a secure HTTP transport layer that implements the MCP protocol. For authentication, the MCP server uses OAuth2 with Keycloak. The MCP client or AI Agent registers as an OAuth client via Extension SSO Manager and obtains an access token through the standard OAuth2 flow. Using this token, clients can optionally fetch company list from the SLD to include the correct company context in requests. The server validates each incoming request by verifying the Bearer token against Keycloak to ensure only authenticated clients can access the MCP tools, and checking the audience claim to ensure the token is intended for this server.


Available MCP Tools

Important: Tools are consumed by AI models and do not constitute a stable API. Tool names, parameters, and behavior may change between versions. Do not build hard dependencies on specific tool signatures.

Core Discovery and Execution Tools

The server uses 4 core discovery/execution tools instead of hundreds of individual CRUD tools:

Tool Description Parameters
b1_find_entities Step 1: Searches SAP Business One Service Layer entities by business category and optional name filter. Returns a minimal list (entityName, categories). If no matches are found, all entities are returned. Use b1_get_entity_schema next to retrieve the full schema for a selected entity. Use category='workflow' to discover the available workflow helper tools and their descriptions. - category (optional): Business area filter. Default: 'all'.
- query (optional): Search term for entity names
- limit (optional): Maximum results to return (min: 1, max: 50, default: 20)
b1_get_entity_schema Step 2: Get the schema for a SAP B1 entity. Step 2.1: call with entityName only — returns all properties and structural (complex) types. Step 2.2 (optional): call with entityName + structuralTypeName to drill into a complex type's sub-properties. Step 2.1 must be called first for the same entity. - entityName (required): B1 entity name from b1_find_entities results (case-sensitive, e.g. "BusinessPartners")
- structuralTypeName (optional, Step 2.2 only): Use the complexTypeName from a structuralProperties entry in the Step 2.1 result. Example: 'DocumentLine'
b1_read Step 3a: Executes read operations on SAP B1 Service Layer entities. Use b1_get_entity_schema first to confirm field names and key properties. Supports read for list queries and read-single for a specific entity by key. - entityName (required): The entity name
- operation (required): read or read-single
- parameters (optional): Key fields for read-single (e.g. { DocEntry: 1 }); omit for list reads
- filterString (optional): OData $filter query
- selectString (optional): OData $select for specific fields
- orderbyString (optional): OData $orderby for sorting
- topNumber (optional): Number of records to return
- skipNumber (optional): Number of records to skip (pagination)
b1_write Step 3b: Executes write operations on SAP B1 Service Layer entities: create, update, and delete. Requires user confirmation before execution (see Human Confirmation). Creating IncomingPayments/VendorPayments adds the means of payment, the currency and rate B1 will use, each applied invoice and the estimated exchange difference to the confirmation. Creates that post to the ledger return the journal entry (see Journal entry after posting). - entityName (required): The entity name
- operation (required): create, update, or delete
- parameters (required): Entity data as a flat object. create: body fields only. update: key fields + fields to change (handler separates them automatically). delete: key fields only

Progressive 3-Step Discovery

The server avoids tool explosion by condensing everything into a 3-step flow:

Step 1: b1_find_entities        → Lightweight semantic search; returns entity names and categories
Step 2: b1_get_entity_schema    → Full schema for a selected entity (properties, types, keys)
Step 3: b1_read / b1_write      → Execute the read or write operation with schema-informed parameters
  • Token efficiency: Step 1 returns ~90% less data than full schemas
  • Clear separation: The LLM can scan and select before committing to a full schema fetch
  • Progressive detail: Complex types can be drilled into in a Step 2.2 call without fetching everything upfront

Company Selection Tools

In OAuth mode, select a company before calling entity tools:

Tool Description Parameters
b1_list_companies OAuth Step 0: Returns the list of available SAP B1 companies. Returns: CompanyID, CompanySchemaName, CompanyName, Status. Use b1_select_company with the CompanySchemaName next. None
b1_select_company OAuth Step 1: Selects the active SAP B1 company for all subsequent requests. Optionally retrieves detailed company information (version, localization, etc.). Next: use b1_find_entities to search available entities. - companySchemaName (required): Company schema name from b1_list_companies (e.g. 'SBODEMOUS')
- getDetails (optional): Retrieve detailed company information. Default: false

Workflow Helper Tools

Five workflow helper tools simplify common B1 business workflows:

Tool Description Parameters
b1_copy_document Creates a new sales document by copying an existing source document, automatically resolving BaseType, BaseEntry, and BaseLine references. Supports standard B1 flows: Order→Delivery, Delivery→Invoice, Order→Invoice. - sourceEntityName (required): Source entity (e.g., "Orders", "DeliveryNotes")
- sourceDocEntry (required): DocEntry of source document
- targetEntityName (required): Target entity to create (e.g., "DeliveryNotes", "Invoices")
- lineSelections (optional): Zero-based line indexes to copy; omit for all lines
- additionalFields (optional): Header fields to add/override
b1_create_payment Validates and creates an incoming payment for A/R invoices or a vendor payment for A/P invoices. Fetches open balances and allocates payment automatically (oldest-first by DocDate) or manually before posting. Pays in local currency by default, or in the invoices' foreign currency (paymentCurrency, at rate or the system rate of the date); rate: 'invoice' pays at the invoices' own rate, for operations where invoice and payment are one transaction (currency purchases from a bank). When the payment's rate differs from an invoice's, the validation and the confirmation show the exchange difference B1 will post (an estimate: B1 rounds its own way); it is a warning, never a refusal. A foreign-currency bank account must match the payment currency. - paymentType (optional): incoming (default, Invoices → IncomingPayments) or outgoing (PurchaseInvoices → VendorPayments)
- cardCode (required): Business Partner code
- invoiceDocEntries (required): Array of invoice DocEntry values
- paymentAmount (required): Total payment amount to allocate, in the payment currency
- allocationType (optional): auto or manual (default: auto)
- manualAllocations (optional): Required with allocationType=manual; per-invoice amount allocation
- transferAccount (optional): G/L transfer account; required for outgoing
- paymentCurrency (optional): Currency of the payment; omit for local currency
- rate (optional): Rate for a foreign-currency payment, or 'invoice'
- transferDate (optional): Payment date (YYYY-MM-DD)
- transferReference (optional): Payment reference/check number
- remarks (optional): Payment notes
- validateOnly (optional): If true, validates without posting. Default: false (validate and post)
b1_document_action Cancels or closes an existing document through the Service Layer Cancel/Close actions. Restricted to an allowlist: cancel on Quotations, Orders, DeliveryNotes, Returns, Invoices, CreditNotes, DownPayments, their Purchase* counterparts, IncomingPayments and VendorPayments; close on Quotations, Orders, DeliveryNotes, Returns and their Purchase* counterparts. Reads the document first and stops early if it is already cancelled/closed, is an invoice with payments applied (cancel the payment first), or has a folio on a cancel (B1 refuses with 1470000534): for Purchase* documents the message says to note the folio, clear FolioPrefixString/FolioNumber with b1_write and cancel again; for sales documents, whose folio is the company's own fiscal number, it says not to clear it. post (entity Drafts) adds a reviewed A/P invoice draft as a posted A/P invoice through DraftsService_SaveDraftToDocument: the confirmation shows the supplier, total, VAT and the goods receipts or orders it closes, and the tool refuses drafts whose remarks start with REVISAR: or that still have text lines (the notes b1_import_einvoice leaves; the single line Artículos confirmados that b1_receive_einvoice_draft leaves is allowed), closed drafts, drafts of other document types, and A/P invoice drafts whose supplier invoice is already posted (same supplier, FolioNumber, establishment and point, not cancelled), which posting would book twice. B1 permissions apply as for the user in the SAP client. - entityName (required): Document entity (e.g., "Invoices", "IncomingPayments", "Drafts")
- docEntry (required): DocEntry of the document or draft
- action (required): cancel, close or post
b1_pick_list Sets the picked quantity on lines of an existing released pick list (PickLists). For serial-managed items it sends the picked quantity together with the serial numbers (and optional bin locations) through the Service Layer PickListsService_UpdateReleasedAllocation action, because a plain update of PickedQuantity is rejected without them and the action rejects serials whose count does not match PickedQuantity; lines without serials or bins are saved with a plain update. Checks that the pick list and lines are open, that the quantity does not exceed the released quantity, and that there is one serial per picked unit. Create the pick list itself with b1_write on PickLists; its PickDate must fall between the order date and the order's cancellation date. - absoluteEntry (required): Pick list Absoluteentry
- lines (required): Array of { lineNumber, pickedQuantity, serialNumbers?, binAllocations? }; lineNumber is the pick list line, serialNumbers are internal serial numbers, binAllocations are { binAbsEntry, quantity, serialAndBatchNumbersBaseLine? }
b1_bank_match_proposals Read-only bank reconciliation assistant. Loads the unreconciled bank statement lines (BankPages) of a house bank G/L account for a period, and proposes matches with incoming/vendor payments posted to that account — by amount, date (booking date or, when the import filled U_TransferDate, the date the transfer was sent), transfer reference and payer — each with a confidence level and reasons. The payer's business partner comes from, in order: the CardCode the line was linked to in B1; the payer tax ID (bank RUC/CI formats are normalised to B1's FederalTaxID; when the statement import left U_PayerTaxId/U_PayerName empty, the payer is read from the RUC:/CI: segment of the memo); the payer bank account (U_PayerAcct or the memo) against the business partners' default bank account (DefaultAccount; other accounts in BPBankAccounts cannot be filtered through the Service Layer); and, for lines that carry only an account, the tax ID on earlier statement lines from that account. When a line is linked to a business partner whose tax ID is not the payer's, a match with that partner's payment is not rated high (the reason says to check the link), and a payment of the payer's own business partner wins. A match without that evidence is also rated high when the payer paid for the payment's business partner before (an earlier external reconciliation on the account, found through a third SQL query, SQLQueries('mcpPartnerReconciliations'), on JDT1; the company's own transfers do not count), when every word of the name on the payment is in the payer's name (payments posted to a G/L account carry only a name), or when payer and payment share a surname; below smallAmountThreshold a shared surname is not enough and an amount-and-date match is rated low. A statement line from the company itself (its own tax ID) is matched high with a payment to a G/L account or with an entry booked on this bank account by a payment drawn on another account (a transfer between the company's accounts); and when several identical statement lines (same counterparty, amount, date) fit the same number of identical payments of one partner, the pairing does not matter and they are rated as single candidates. A line without payer data (e.g. ESSAPONLINE-<number> \| <number>, IPSCorp-Extracto:…) is identified from history instead: earlier reconciled statement lines of the account with the same memo signature (numbers of 3+ digits masked, ESSAPONLINE-# \| #) and what their journal entries were posted against, a business partner or a G/L account (a fourth SQL query, SQLQueries('mcpReconciledCounterparts'), on JDT1 by reconciliation number). When at least 3 of the last 8 such reconciliations, and at least 80%, agree, a payment to that partner or account (for an account payment, its PaymentAccounts) is rated high; 2 agreeing reconciliations (at least 75%) raise it to medium, and a payment to someone else is rated low. A memo number that equals the payment's transfer reference or its journal line's Ref1/Ref2 (or ends with it, for card numbers cut to their last digits) also rates the match high. The summary counts payers by source. Remaining lines get a suggested action: internal transfer/FX (company's own tax ID or a currency exchange), card settlement, direct debit (POS purchase, loan instalment, service or card payment, card processor debit, from the import's operation name in InvoiceNumber or the memo), possible bank fee, create vendor/incoming payment (to the counterpart learned from earlier lines with the same memo, or with the payer's open documents of that amount: invoices and down payments of the line's direction, or a credit note for a refund, e.g. an A/R credit note paid out to a customer), match an open A/R invoice, or unidentified. Then, on what is left, proposes group matches of several statement lines for one or a few open journal entry lines of the account (groupProposals, each with a reconcile field ready for the reconciliations batch of b1_external_reconciliation): (1) all of one payer's lines over a run of whole days that add up to the open journal lines of the payer's business partner (high); for journal lines without a business partner, such as the monthly Contimarket credit booked as a payment to a G/L account, the only payer whose lines over a run of days add up to one journal line, or to two together (high with at least 10 lines, otherwise medium; two journal lines only with at least 10); (2) the only combination of up to 8 statement lines within the date tolerance that adds up to one journal line, searched among the business partner's own lines first (high when every line's payer is that partner, otherwise medium, low below smallAmountThreshold). When several combinations fit, none is proposed (ambiguousGroups) and their lines are held back from later searches; a search with more than 24 candidate lines, or one that exceeds its step budget, is skipped and listed in skippedGroupSearches. Card settlements and currency exchanges are left out, and so are payments and their cancellations. Also lists B1 payments with no statement line. Each proposed payment carries its open journal entry line on the bank account (TransId/Line_ID), ready for b1_external_reconciliation; payments whose line is already externally reconciled are left out (counted in the summary). Posts and reconciles nothing. Payments by check drawn on the account (PaymentChecks.CheckAccount) or in cash are candidates too, and a check number equal to the statement reference makes the match high. On a foreign-currency account (e.g. USD, ChartOfAccounts.AcctCurrency) every amount is compared in the account currency: payments by the FC amount of their journal line on the account (JDT1.FCDebit/FCCredit), open documents by DocTotalFc - PaidToDateFC (documents in that currency only); journal lines with a local amount only, such as exchange rate revaluations, are left out and counted (localOnlyJournalLines). The result contains payer names and tax IDs from the statement; it is not subject to b1_read redaction. - accountCode (required): Bank G/L account (e.g., "111401")
- dateFrom, dateTo (required): YYYY-MM-DD, at most 31 days
- dateToleranceDays (optional): Default 3
- amountTolerance (optional): Default 0
- includeReconciled (optional): Default false
- maxLines (optional): Abort above this many lines. Default 500
- feeThreshold (optional): Small debits without counterparty flagged as fees. Default 50000 in local currency, converted at the B1 rate of dateTo on a foreign-currency account
- smallAmountThreshold (optional): Below it, amount-and-date matches are low and a shared surname does not make them high. Default as feeThreshold
b1_reconciliation_items Read-only external (bank) reconciliation view of a house bank G/L account. open_items: open bank statement lines (BankPages, by Sequence) and open journal entry lines on the account (TransId/Line_ID, with source document) for a period, with the net of each side; on a foreign-currency account in the account currency (currency, journal FC amounts), with lines that have a local amount only counted in localOnlyJournalLines. list: the account's external reconciliation numbers. get: the statement and journal entry lines of one reconciliation (ExternalReconciliationsService_GetReconciliation). No Service Layer entity exposes whether a journal entry line is reconciled (JDT1.ExtrMatch), so open lines are read through a saved SQL query, SQLQueries('mcpOpenBankJeLines'), which the server creates on first use per company (the B1 user needs permission to create SQL queries, and the Service Layer must allow JDT1/OJDT in b1s_sqltable.conf). - operation (required): open_items, list or get
- accountCode (required): Bank G/L account
- dateFrom, dateTo: YYYY-MM-DD; required for open_items (at most 31 days), optional reconciliation-date filter for list
- reconciliationNo: Required for get
- maxLines (optional): Default 500
b1_external_reconciliation Reconciles bank statement lines with journal entry lines of a house bank G/L account (ExternalReconciliationsService_Reconcile), or cancels an external reconciliation (ExternalReconciliationsService_CancelReconciliation). Before asking for confirmation it checks that every line is open on the account and that the sides balance: money in minus money out on the statement equals debit minus credit on the journal lines. A journal line that is not open gets its reason (no such entry or line, a line on another account, or already reconciled) and the entry's open line(s) on the bank account; without lineId, the entry's only open line on the account is used, and an entry with several is refused with its lines listed. Several lines on either side are allowed. At least one statement line is required: the Service Layer rejects journal-only reconciliations (-5002), so journal entry lines that net to zero (e.g. a payment and its cancellation) are added to a reconciliation that has a statement line. Post missing payments or journal entries (fees, transfers) first with b1_create_payment or b1_write. Batch: reconciliations reconciles several independent groups (e.g. a day's high-confidence proposals) with a single confirmation: each group is checked on its own, invalid groups (already reconciled, unbalanced, a line also used by an earlier group) are skipped and reported, and the others are posted one by one; a group B1 rejects does not stop the rest. Open journal lines of a document and its cancellation (a cancelled payment and its reversal, a journal entry and its StornoToTr reversal, a deposit and the document whose memo cancels it, or a marketing document such as an A/P invoice and its cancellation document, found through the cancellation's BaseEntry) net to zero and cannot be reconciled on their own. With attachCancellations the pairs whose cancellation is dated from 31 days before the batch's first statement line up to its last one are added: first to groups made only of statement lines that net to zero (a returned transfer, which the Service Layer would otherwise refuse), one pair each, of their amount when possible; then each pair to the group nearest in date among those with a statement or journal line of its amount (related, the default). any also adds the remaining pairs to the group nearest in date; none adds none. The assignment does not depend on the order of the groups. The confirmation lists each pair under its group with the reason, and the result counts the pairs left open. G/L accounts only (not business partner reconciliation). - operation (required): reconcile or cancel
- accountCode (required): Bank G/L account
- bankLines: reconcile, array of BankPages Sequence (at least one)
- journalLines: reconcile, array of { transId, lineId? }
- reconciliations: reconcile, instead of bankLines/journalLines: array of { bankLines, journalLines }, at most 100
- attachCancellations (optional): With reconciliations: related (default), any or none; true/false mean related/none
- reconciliationNo: Required for cancel
b1_investigate_bank_item Read-only investigation of why an item does not reconcile on a house bank G/L account. Starts from a statement line with no journal entry, or from a payment or bank journal line with no statement line, and searches around its date and amount: the payer (statement fields or memo) and its business partners; incoming/vendor payments on any account, including cancelled ones and matching transfer references; unposted payment drafts (Cancelled eq 'tNO': on drafts tYES means already posted); journal entry lines with the amount on any G/L account, reconciled or not (a line of the bank account that nets to zero with its cancellation, such as a cancelled deposit, is shown as such and not suggested); other statement lines (refunds, duplicates, the payer's other transfers, other bank accounts); open documents of the payer's business partners with that open balance: invoices and down payments (requests included) of the line's direction, and credit notes for a refund (A/R credit note for money out, A/P credit note for money in). When no single document fits, finds the only set of up to 6 open invoices and down payments of one business partner that adds up to the line, optionally less one credit note the partner deducted (documentCombinations); several fitting sets are reported as ambiguous, to check with the payer. Also looks for combinations: several payments of the payer that make up one statement line, several statement lines of the payer that make up one payment, or one statement line that equals the payment plus other payments of the same business partner, each with the journal lines for b1_external_reconciliation; a difference of up to 0.1% (rounding, a bank charge) is reported as an amount to post first. Stops right away when the item is already reconciled. Returns findings with reasons, an outcome, and rule-based suggested actions, most likely explanation first, e.g. "the payer's lines net to zero: money returned, no payment needed", a cancelled payment to repost, a payment posted to cash or another bank, a match outside the 3-day tolerance, an amount that differs slightly (< 1%), a card settlement, a bank direct debit, a possible duplicate, or, for a line without payer data and without a payment, the business partner or G/L account earlier lines with the same memo signature were reconciled against. The payer is identified as in b1_bank_match_proposals. Journal lines across accounts come from a second SQL query, SQLQueries('mcpJeLinesByAmount'), created on first use like mcpOpenBankJeLines. The result contains payer names and tax IDs; it is not subject to b1_read redaction. - accountCode (required): Bank G/L account
- Exactly one of: bankLine (BankPages Sequence), payment ({ entityName: 'IncomingPayments' \| 'VendorPayments', docEntry }), journalLine ({ transId, lineId })
- dateWindowDays (optional): Days before and after, default 7, max 31
- amountTolerance (optional): Default 0
b1_investigate_bank_period Read-only. Explains everything that does not reconcile on a house bank G/L account in a period: runs b1_bank_match_proposals for the period, then investigates every statement line and B1 payment it could not match (as b1_investigate_bank_item, 4 at a time, in date order) and groups them by outcome: reconcile, reconcile as a combination, reconcile after checking, amount differs slightly, returned money, needs a payment, cancelled payment, posted to another account, unposted draft, journal entry on another account, possible duplicate, payer not in B1, card settlement, bank debit, no trace. Items explained by another item (the other half of a refund, the payments of a combination, the payment or line an item is proposed to be reconciled with, a payment that differs slightly from an unexplained line) are listed as covered. A payment proposed for several statement lines stays with the only confirmed match; when no line or several confirm it, none of them gets it and each says so. Medium and low matcher proposals are counted but not checked. Each item takes about 0.7 s, so a month on a busy account needs several runs: when maxItems is reached the result gives continueFrom. The result contains payer names and tax IDs; it is not subject to b1_read redaction. - accountCode (required): Bank G/L account
- dateFrom, dateTo (required): YYYY-MM-DD, at most 31 days
- dateWindowDays (optional): Default 7, max 31
- amountTolerance (optional): Default 0
- maxItems (optional): Default 60, max 200
b1_import_bank_statement Imports a bank statement file the user uploaded in the chat, for banks without automatic import. The AI reads the file and passes its lines; the server finds the G/L account from the bank account number through the house bank accounts (register the bank there first; when no number matches exactly, the only one that ends with the printed number, or whose end it is, is used and noted), checks that the running balance adds up line by line and matches the printed opening and closing balances, ties the file to the bank balance stored on the last imported line (U_BankBalance), skips lines already in B1 (same date, direction, amount and reference, counting repeats within a day), leaves lines dated today for the next import, and warns about lines added late on days already imported, B1 lines the file no longer shows, a first import that cannot be tied, and files without a running balance. preview writes nothing; import repeats every check, needs acceptWarnings when there were warnings, asks for one confirmation and posts the new lines in date order, stopping at the first one B1 rejects (importing the same file again posts the rest). For a month in progress, import the month-to-date file every day. Requires the UDF U_BankBalance (amount) on bank statement lines. - mode (required): preview or import
- accountNumber (required): as printed on the statement
- lines (required, max 1000): date, valueDate, description, reference, debit, credit, balance, payerTaxId, payerName, payerAccount
- currency, dateFrom, dateTo, openingBalance, closingBalance (optional): as printed
- includeToday (optional): Default false
- acceptWarnings (optional): Default false
b1_import_einvoice Creates an A/P invoice draft (Drafts, oPurchaseInvoices) from a supplier's Paraguayan electronic invoice (SIFEN XML) for the clerk to review and post. Refuses documents that are not facturas electrónicas (iTiDE 1), invoices addressed to another RUC than the company's, and invoices already in B1 as draft or A/P invoice (same CDC in U_SIFEN_CDC, or same supplier RUC, timbrado, establishment, expedition point and number). Finds the supplier by RUC or creates it from the issuer data (all currencies, group and series of the supplier created last). Service invoices (iTipTra 2) get one line per VAT rate with the G/L account of the supplier's latest service A/P invoice; goods invoices get item lines for items identified by the supplier's catalog number (AlternateCatNum), barcode or the item's supplier catalog number, copied from the supplier's open goods receipt POs first, then purchase orders (open quantity less what open drafts already take). Lines that cannot be loaded safely (unknown item, quantity that does not fit the open base documents, a base document in another currency, price difference above the tolerance, no G/L account) become text lines with a note; the remarks then start with REVISAR: and the draft totals less than the invoice. The 0% tax code is the one the supplier's last A/P invoices of the same kind used. Due date from the installments or credit term; payment terms from PaymentTermsTypes. The company's RUC, currencies and tax codes are read from B1, so it works in any company without setup (see Configuration Reference). preview writes nothing; import repeats every check and asks for one confirmation covering the supplier and the draft. - mode (required): preview or import
- xml (required): the whole XML file content
b1_import_paper_invoice Creates the same A/P invoice draft as b1_import_einvoice from a paper invoice (or a printed e-invoice whose XML never arrived) that the AI read from a photo (spec, flow C). Before writing, the server checks that quantity × price gives each line total (allowing a printed unit price rounded to the currency's unit), that the lines add up to the printed subtotals per VAT rate and those to the total, that the printed VAT 5% and 10% match the subtotals, the RUC formats, that the invoice is addressed to the company's RUC, the timbrado (8 digits) and that the invoice date falls within its validity, and that a foreign-currency invoice has its exchange rate; when anything doesn't add up nothing is written and the result names the values to read again. The supplier must exist (found by RUC); a supplier is never created from a photo. Duplicates are searched by supplier RUC or card code, timbrado, establishment, expedition point and number. Items are identified and planned as for e-invoices; the draft gets U_CENT_COMPROBANTE 109, the printed timbrado expiry in U_CENT_FVTIM and no CDC, and lines it can't load become the text lines b1_receive_einvoice_draft completes. preview writes nothing; import asks for one confirmation that shows the timbrado and VAT read. - mode (required): preview or import
- invoice (required): supplier and receiver RUC, timbrado and its expiry, establishment, expedition point, number, date, currency (and rate), credit or cash, kind (items/services), lines (description, supplier code, quantity, unit price, total, VAT rate), printed subtotals per rate, total, vat5, vat10
b1_receive_einvoice_draft For the warehouse: completes an A/P invoice draft created by b1_import_einvoice when its goods arrive, and posts it (spec). Finds the draft by docEntry, by the e-invoice CDC (U_SIFEN_CDC, spaces ignored) or by the supplier (supplierRuc, matched to every supplier with that RUC, or cardCode) with the number as printed (invoiceNumber 001-001-0038415: U_CENT_EST, U_CENT_PE, FolioNumber); when several open drafts match it lists them, and when the invoice is already posted it says so. Reads the draft whole (with $select the Service Layer hides text lines and serials) and reads back the import's "Sin artículo en B1" text lines as invoice lines (its other line notes, such as a quantity that doesn't fit the open goods receipt, stop the receipt: those lines are copied in SAP): quantity, price and VAT rate come from the e-invoice, the tax code from the company (a 0% line takes the code the draft's other 0% lines use). The user names the items for those lines; label codes (scanned, or read from a photo and marked so) are sorted into product codes and serials: a GTIN equal to the item's BarCode or a part number equal to U_COD_PART confirms the item and ties the following serials to it, and once a line has all its serials the next ones go to the only line still waiting. It stops on serials already in B1 for the item, product codes not on the draft, missing serials on items managed on every transaction, a completed total different from the invoice (kept in the remarks, so a re-run after a failed posting still checks it), and, unless onDifference is reserve, on lines where less arrived than was invoiced; lines copied from a goods receipt PO are already received: they need no serials and rule out the reserve route; a GTIN close to the item's bar code is reported as a likely bar code error. receive sends one PATCH with B1S-ReplaceCollectionsOnPatch (all lines, new item lines with their serials, the draft's notes replaced by the text line Artículos confirmados, which a PATCH can't remove) and posts it with DraftsService_SaveDraftToDocument after one confirmation; with reserve it posts an A/P reserve invoice for the whole invoice and a goods receipt PO copied from it for what arrived, with the serials, the rest staying open on the reserve invoice. New lines go to the warehouse of the draft's lines, else of the supplier's latest A/P invoice. A draft whose supplier invoice is already posted is refused, as in b1_document_action. The import's notes keep the e-invoice GTIN ([cód. 129398, GTIN 7730737129394]): receiving shows it, ranks with it as the bar code, and uses it as the line's bar code for scanned labels when the chosen item has none. For each line without an item the preview lists up to five existing items from b1_suggest_items's ranking (with the supplier's history), and names the item of a scanned bar code that is not on the draft; the server never chooses one. reject leaves the draft unposted with the text line Rechazado en la recepción (date): reason after one confirmation, which keeps b1_document_action from posting it; a later receipt replaces it. Returns the journal entry. - mode (required): preview, receive or reject
- docEntry, cdc, or supplierRuc/cardCode with invoiceNumber/folioNumber: the draft
- reason: for reject
- items: { line, itemCode } for the lines without an item
- codes: { value, source: 'scan' \| 'photo', line? } in the order read
- received: { line, quantity } where less arrived
- onDifference: stop (default) or reserve
b1_create_items Creates items for received products that are not in B1 (spec, Item fields), for b1_receive_einvoice_draft to use. Each item copies from a similar existing item the user confirmed (likeItem, an active purchase and inventory item): item group, manufacturer, purchase and sales tax codes (with IndirectTax, without which B1 drops them), UoM group, tariff code (SWW), tourism regime (U_REG_TUR), warranty template, Properties1 and its warehouse rows (items created through the Service Layer get none otherwise); the code comes from the numbering series of the group's newest item. The name is upper-cased and ForeignName copies it. Serial management is always given by the caller. Bar codes must be valid GTIN-8/12/13/14. Refused when an existing item has the same bar code (BarCode, the barcode UDFs or BarCodes; not overridable when that item has the same name or model code, overridable as a probably wrong bar code when it looks like another product), part number (U_COD_PART, placeholders such as N/D ignored), supplier catalog number, supplier's code (AlternateCatNum for the supplier, or a SupplierCatalogNo equal to it or ending in - and it, as Fastrax items' FX- codes), the same name on letters and digits (case, accents, spaces and hyphens ignored; + and decimal points kept), or a model code of the name (searched with contains by model code and by all the name's words at once, since B1 compares case-sensitively, then compared in code); all but the same-model bar code can be overridden per item with notDuplicateOf. The item index of b1_suggest_items is asked too: a same name in any letter case or spacing, or a rare model code, stops like the live matches; weaker candidates are listed without stopping. When the new name contains another manufacturer's name than the one copied (FTX in the name, Kolke copied from the similar item), the preview and the confirmation say so, naming that manufacturer's code, without stopping. With cardCode and supplierCode it adds an AlternateCatNum row, which the e-invoice import matches first. No prices. preview writes nothing; create repeats every check, asks for one confirmation for all items and creates them in order, reporting those already created if one fails. - mode (required): preview or create
- cardCode (optional): supplier, for supplierCode
- items (required, max 10): itemName, likeItem, serialManagement (none, onEveryTransaction, onReleaseOnly) required; barCode, partNumber, supplierCode, supplierCatalogNo, shortDescription, itemsGroupCode, manufacturer, tourismRegime, tariffCode, notDuplicateOf
b1_suggest_items Read-only. Ranks existing items for product descriptions that matched none: invoice or delivery note lines, a photographed box, "do we have this?". The company's active purchase and inventory items (with BarCodes and AlternateCatNum) are loaded in pages of 1000 and kept 15 minutes per company (about 11 s for COMPU's 10,325 items; invalidated when b1_create_items creates one), and compared in code, since B1 compares text case-sensitively. Strong: bar code, the supplier's catalog number, a SupplierCatalogNo equal to the supplier's code or ending in -<code> (Fastrax FX-), the same name on letters and digits, a model code few items share. Possible, with what differs: a model that only adds a letter suffix (12400/12400F), other capacities or colors, a shared code beside each name's own model code, another kind of product (first word), words: how much of the item's name the description covers (words with digits left to model codes and specs; P/2MON reads as MONITOR). With the supplier (cardCode or supplierRuc), its invoice and goods receipt lines of the last year (saved SQL query mcpSupplierItemPurchases, created on first use; skipped when the user may not create it) raise the rank and report a price far from the last one. Strong candidates rank first. - lines (required, max 20): description, supplierCode, barCode, unitPrice, currency
- cardCode or supplierRuc (optional)
- limit (optional): candidates per line, default 5, max 15
b1_confirm_operation Carries out a write, or a read of personal fields, that another tool stopped with CONFIRMATION REQUIRED, for clients that cannot show elicitation prompts (see Human Confirmation). The token is single-use, bound to the user and company, and expires after MCP_CONFIRMATION_TTL_MINUTES; the tool re-runs the original call and does nothing, returning a new summary and token, if the request or the data in SAP changed since the summary. Registered only when MCP_HUMAN_CONFIRMATION_ENABLED=true. - token (required): from the CONFIRMATION REQUIRED result

Discovering workflow tools at runtime:

Show me what workflow tools are available in the B1 MCP server

The AI agent calls b1_find_entities with category: 'workflow' and receives the full descriptions of b1_copy_document, b1_create_payment, b1_document_action, b1_pick_list, b1_bank_match_proposals, b1_reconciliation_items, b1_external_reconciliation, b1_investigate_bank_item, b1_investigate_bank_period, b1_import_bank_statement, b1_import_einvoice, b1_import_paper_invoice, b1_receive_einvoice_draft, b1_create_items and b1_suggest_items.

Journal entry after posting

Every write that posts to the ledger returns the journal entry it produced, in the text ([JOURNAL ENTRY <JdtNum>], one line per account with its name, business partner, debit or credit and the foreign-currency amount) and as journalEntry in structuredContent: b1_write creates of documents, payments and journal entries, b1_copy_document, b1_create_payment, b1_document_action post, and the reversal of a cancelled payment. Documents are found by their TransNum; payments by OriginalJournal/Original on JournalEntries. On a payment, lines that are neither on the payment's own accounts nor the business partner (exchange differences, bank charges, withholding) are listed as [CHECK] lines for the user to confirm. A failed read never fails the tool, since the posting already happened; the result then says to look the entry up with b1_read.

MCP Resources

Two resource types provide contextual knowledge without tool calls:

Resource URI Pattern Description
b1://service-layer/metadata Service and entity metadata for the Service Layer.
b1://constants/{type} Reference data including objectTypes, documentFlows, fieldPatterns, statuses, paymentTypes, and all. Example: b1://constants/objectTypes

Benefits: AI assistants can access these resources instantly without tool calls - more efficient for workflows!

Integration Endpoint: e-invoices from automations

POST /integrations/einvoice runs the same import as b1_import_einvoice for an automation such as an n8n workflow watching the invoices mailbox, without the chat confirmation:

  • Authentication: a Keycloak bearer token with the scope b1_einvoice:import (EINVOICE_ENDPOINT_SCOPES), required even when OAUTH_VERIFY_SCOPES=false. The token is forwarded to the Service Layer, so the caller's own B1 user creates the drafts. Use a dedicated client-credentials client without b1_mcp:access (see Keycloak setup). In direct mode the endpoint exists only outside production.
  • Request: header x-b1-companyID (required) and JSON { "xml": "<the XML file>", "mode": "import" | "preview", "pdf": { "contentBase64": "<the invoice PDF>" } }; pdf is optional. The PDF is uploaded to Attachments2 as FE_<CDC>.pdf (the attachments folder set in B1 General Settings) and the draft is created with it; if it cannot be attached the draft is still created and attachmentError says why.
  • Response: { status, message?, cdc, folio, draftDocEntry?, attachmentEntry?, attachmentError?, duplicate?, supplier?, notes, warnings, preview? } with HTTP 201 created, 200 duplicate or preview, 422 for invoices that will never import as sent (rejected: not an invoice, another company's RUC, unreadable XML; supplier_missing: the supplier is not in B1, since suppliers are only created with EINVOICE_UNATTENDED_SUPPLIER_CREATION=true), 502 for B1 errors worth retrying. Retries are safe: a repeated invoice is a duplicate.
  • Every import outcome except previews and duplicates is audited as EInvoiceImport.

Prerequisites

Requirement Minimum version
Node.js 22.22.3
npm 10.9.8
SAP B1 Service Layer FP2608
SAP B1 Identity and Authentication Management (IAM-Keycloak) FP2608
SAP B1 System Landscape Directory (SLD) FP2608

Installation

  1. Download this package b1-mcp-server.zip from the online help, unpack it and then navigate to the unpacked project folder.
  2. Install dependencies and compile:

npm install
npm run build

Configuration

All settings are controlled through a .env file in the project root. Copy .env.example as a starting point:

cp .env.example .env

For a complete reference of every available variable, see the Configuration Reference chapter.

Direct Mode (Development Only)

Use this mode when SAP B1 Service Layer is accessible with a username and password. Suitable for quick prototyping in local development environment and testing only.

Note: Despite using a username and password in the .env file, this is not HTTP Basic Authentication. The credentials are used by the MCP server to obtain a session token from SAP B1 Service Layer via its login API (/b1s/v2/Login), and all subsequent requests are authenticated with that session token.

NODE_ENV=development
AUTHENTICATION_MODE=direct

# B1 Service Layer host (server appends /b1s/v2/ internally)
SERVICE_LAYER_ROOT_URL=https://servicelayer.b1.example.com:50000

B1_COMPANY_DB=yourCompanyDB
B1_USERNAME=yourUsernameHere
B1_PASSWORD=yourPasswordHere

# Accept self-signed certs for local development/testing only
AUTH_ALLOW_SELF_SIGNED=true

OAuth Mode (Production, Default mode)

Use this default mode since the Service Layer is always fronted by Keycloak. Incoming bearer tokens are validated against the OAuth provider before any B1 request is forwarded.

# Default mode, validate incoming requests via OAuth 2.0 / OIDC (requires OAUTH_BASE_URL and OAUTH_CLIENT_ID)
AUTHENTICATION_MODE=oauth

SERVICE_LAYER_ROOT_URL=https://servicelayer.b1.example.com:50000
SLD_ROOT_URL=https://sld.b1.example.com:40000

OAUTH_BASE_URL=https://keycloak.b1.example.com/auth/realms/sapb1/
OAUTH_CLIENT_ID=your-client-id
OAUTH_CLIENT_SECRET=your-client-secret

HTTPS / Transport

The server uses HTTPS by default, and use a self-signed certificate for local development. You can also switch to HTTP if you prefer.

HTTPS (default):

HTTPS_ENABLED=true
HTTPS_KEY_PATH=./certs/server.key
HTTPS_CERT_PATH=./certs/server.crt
PORT=3000

# Optional:
# HTTPS_CA_PATH=./certs/ca.crt
# HTTPS_PASSPHRASE=your-cert-passphrase

HTTP:

If you want HTTP instead of HTTPS due to local testing or avoiding browser security warning issues or other reasons (e.g. You already have a upfront HTTPS gateway or reverse proxy), set:

HTTPS_ENABLED=false
PORT=3000

Advertised public URL (MCP_BASE_URL):

By default the server derives its advertised URL from the active listener settings. If the server is behind a reverse proxy or you need clients to use a specific base URL for OAuth metadata and MCP endpoints, set this explicitly:

MCP_BASE_URL=https://mcp.example.com

Leave it unset for local development — the server will infer the correct URL automatically.


Running the Server

For production on Google Cloud Run behind Cloudflare Access (Claude remote connectors), see the runbook.

Start the server:

npm start

Verify it is running:

curl http://localhost:3000/health

The server exposes three built-in REST endpoints:

Endpoint Description
GET /health Liveness check — returns status, version, and component health
GET /mcp Server metadata — protocol version, capabilities, active sessions
GET /docs Brief API reference — endpoints, MCP capabilities, usage hints

OAuth note: In OAuth mode, GET /mcp requires a valid bearer token in the Authorization header.

GET /health — example response:

{
  "status": "healthy",
  "timestamp": "2026-06-17T03:50:58.338Z",
  "version": "1.0.0",
  "checks": {
    "auditLogger": { "healthy": true },
    "personalFieldCache": { "healthy": true }
  }
}

GET /mcp — example response:

{
  "name": "b1-mcp-server",
  "version": "1.0.0",
  "protocol": { "version": "2025-11-25", "transport": "streamable-http" },
  "capabilities": { "tools": {}, "resources": {}, "logging": {} },
  "features": [
    "Dynamic SAP Business One Service Layer OData service discovery",
    "CRUD operations for all discovered entities",
    "Natural language query support",
    "Session-based HTTP transport",
    "Real-time service metadata"
  ],
  "endpoints": { "health": "/health", "mcp": "/mcp", "docs": "/docs" },
  "activeSessions": 1
}

Connecting an AI Client

The server exposes a Streamable HTTP MCP endpoint at:

http(s)://<host>:<port>/mcp

Any MCP-compatible AI client can connect to this endpoint. The table below summarizes key capabilities across the supported clients:

Client Transport type MCP Elicitation OAuth / PKCE
Cline (VS Code) streamableHttp Not supported (v4.0.8) Built-in PKCE flow
GitHub Copilot (VS Code) http Supported Built-in PKCE flow
Goose (Desktop) streamable_http Supported Built-in PKCE flow

Write operations and sensitive reads need human confirmation: an MCP elicitation prompt in clients that show one, otherwise a summary the user approves through b1_confirm_operation. See Human Confirmation (MCP Elicitation) for details.


Cline (VS Code)

For setup instructions, LLM provider configuration, OAuth / Keycloak setup, and test examples covering all CRUD operations and workflow tools, see Cline guide.


GitHub Copilot (VS Code)

For setup instructions, OAuth / Keycloak setup, static client ID configuration, OAuth company selection flow, and elicitation test examples, see GitHub Copilot guide.


Goose (Desktop)

For setup instructions, configuration options, OAuth / Keycloak setup, and usage examples, see Goose guide.


MCP Inspector (Browser)

Use the MCP Inspector to interactively browse tools and inspect raw MCP messages. For full usage instructions — including how to obtain a bearer token and set required headers in OAuth mode — see MCP Inspector guide.


MCP Client Integration

If you are building a custom MCP client application that connects to the server in OAuth mode, the integration follows a standard PKCE OAuth 2.0 flow:

  1. Discover OAuth metadata from GET /mcp (the server advertises its authorization and token endpoints).
  2. Initiate a PKCE authorization request and redirect the user to Keycloak.
  3. Exchange the authorization code for tokens (access token + refresh token).
  4. Fetch available companies using b1_list_companies.
  5. Let the user select a company and call b1_select_company.
  6. Include the access token and company ID in every MCP request:
  7. Authorization: Bearer <access_token>
  8. x-b1-companyID: <companySchemaName>
  9. Refresh the token before expiry; re-initiate the PKCE flow on refresh failure.

For a complete working example with annotated code — including client registration, OAuth flow, company selection, and expected output — see Simple MCP client.

Server instructions

The initialize response carries instructions that every MCP client passes to its model: the order of the discovery tools, company selection (OAuth mode only), paging of b1_read, the confirmation flow (only when MCP_HUMAN_CONFIRMATION_ENABLED=true), the bank reconciliation sequence and B1 semantics that are easy to get wrong. They cover how the tools work together; each tool's own behaviour stays in its description. The text is built in src/tools/b1-server-instructions.ts, and a unit test fails if it names a tool the server does not register.

Claude plugin

plugins/sap-b1 is a Claude plugin that bundles the connector (https://sapmcp.compulandia.com.py/mcp) with the team's procedures as skills: bank-reconciliation, bank-statement-import (with per-bank notes in references/banks.md), continental-111401-cleanup and b1-queries. The repository root is its marketplace (.claude-plugin/marketplace.json, name compulandia-b1).

  • Distribution: an Owner syncs this repository from claude.ai Organization settings > Plugins & skills > Sync from GitHub with Sync automatically on, and sets the plugin to Available to install. Members add it from Customize > Plugins > Discover. Each push to main republishes it.
  • Changes: raise version in plugins/sap-b1/.claude-plugin/plugin.json with every change, and update the skills when a tool's behaviour changes. b1-server-instructions.test.ts fails when a skill names a tool the server does not register, or when the marketplace entry, the manifest and the skill folders disagree on names.
  • Testing: run claude plugin validate ./plugins/sap-b1 and claude plugin validate ., then claude --plugin-dir ./plugins/sap-b1 for a session with the working copy. On claude.ai, upload a zip of plugins/sap-b1 from Customize > Plugins > Add > Upload plugin.
  • Personal data: keep payer names, tax IDs and customer accounts out of the skills. Every member who installs the plugin receives its files.

Human Confirmation (MCP Elicitation)

MCP Elicitation is a protocol-level mechanism that allows an MCP server to pause a tool call mid-execution and ask the connected client for additional input or confirmation before proceeding. Unlike a simple prompt, elicitation is built into the MCP protocol: the server sends a structured request to the client, the client presents it to the user (typically as an inline dialog or form), and the server waits for the response before deciding whether to continue or abort. This keeps the human in the loop for sensitive operations without requiring the AI agent to improvise its own confirmation flow.

When MCP_HUMAN_CONFIRMATION_ENABLED=true (the default), the server pauses before: - Write operations (create, update, delete) — prompts for explicit user approval - Sensitive reads — prompts when the query selects fields classified as personal data (email, phone, identity numbers)

Clients that support elicitation (such as GitHub Copilot) display an inline confirmation dialog. The user must approve before the server proceeds; declining cancels the operation without modifying any data.

Example write confirmation prompt (MCP_ELICITATION_LANGUAGE=es, the default, with MCP_CONFIRMATION_MODE=accept):

Confirme: Crear Pago recibido

Socio de negocios: C00001
Facturas: 84124, 84125 (2)
Total a aplicar: 1.500.000
Campos:
  - paymentAmount: 1500000
  - transferAccount: 111401

Esta acción modificará datos en SAP Business One.
Presione Aceptar solo si desea continuar.

Prompt language (MCP_ELICITATION_LANGUAGE): es (default) writes prompts in Spanish with SAP B1 Spanish document names (Invoices → Factura de clientes) and Paraguayan number format; en writes them in English with Service Layer entity names:

Confirm: Update BusinessPartners

Record: 'C00001'
Fields:
  - Phone1: [personal data]

This action will modify SAP Business One data.
Tick "Approve write operation" only if you intend to continue.
Values of personal fields are always masked in the prompt. Errors and tool output returned to the AI stay in English.

Confirmation mode (MCP_CONFIRMATION_MODE):

  • checkbox (default) — the prompt carries a confirmed boolean that starts as false; the operation proceeds only if the user sets it to true.
  • accept — the prompt carries no fields; pressing Accept approves, Decline/Cancel block. Use this for clients that render elicitations as Accept/Decline buttons without showing form fields, such as Claude Code: they submit unrendered fields at their default (confirmed: false), so in checkbox mode every operation is rejected.

Clients that do not show elicitation prompts (Claude web and Cowork, the Claude mobile apps, Cline v4.0.8, …):

Elicitation is used only for clients known to display it; some clients declare the capability and never show the question. For every other client the confirmation goes through the client's own tool approval instead:

  1. The write tool (or b1_read with personal fields) does nothing and returns CONFIRMATION REQUIRED, the same summary the prompt would show, and a single-use token.
  2. The AI shows the summary to the user and, if they approve, calls b1_confirm_operation with the token. The client asks the user to allow that tool, and the server re-runs the original call. If the request or the data in SAP changed in between, nothing is done and a new summary and token are returned.

Keep b1_confirm_operation on Needs approval in the client's connector settings (claude.ai: Settings → Connectors → this server → Tool permissions). Set to "Always allow", the client no longer asks, and the user's approval rests on the AI showing the summary.

Variable Default
MCP_CONFIRMATION_CHANNEL auto auto: elicitation for clients listed in MCP_ELICITATION_CLIENTS that declare it, b1_confirm_operation for the rest. elicitation or tool forces one for all clients
MCP_ELICITATION_CLIENTS claude-code Comma-separated client names (clientInfo.name, logged at the start of every MCP session) known to show elicitation prompts
MCP_CONFIRMATION_TTL_MINUTES 10 How long a confirmation token stays valid

To bypass confirmation entirely in automated or development pipelines, set:

MCP_HUMAN_CONFIRMATION_ENABLED=false

Personal Data Classification

The server uses SAP Business One PersonalFieldsSetups metadata (resolved per table via PersonalFieldsSetupsService_GetPersonalFieldsByTable) to classify sensitive fields and apply safeguards during reads and writes.

Personal fields source

PERSONAL_FIELDS_SOURCE selects where personal-field classification comes from:

Value Behaviour
service (default) Per-table lookup via PersonalFieldsSetupsService_GetPersonalFieldsByTable (FP2608+). In production a failed lookup fails closed.
static Reads a JSON map from PERSONAL_FIELDS_FILE (default ./personal-fields.json). Use on releases before FP2608. The file is validated at startup and the server refuses to start if it is missing or malformed.
none No fields are flagged, so redaction and personal-field confirmation prompts are disabled. Logged as a warning at startup.

The static file maps physical table names (case-insensitive, UDTs with their @ prefix) to DB column names, which are matched against each property's SAPB1.ColumnName annotation (or the property name if absent):

{
  "OCRD": ["Phone1", "E_Mail", "LicTradNum"],
  "CRD1": ["Street", "City", "ZipCode"]
}

Start from personal-fields.example.json and review it against your company's data-protection requirements — it is a starting point, not a complete classification.

How fields are classified

  • Classification source: Service Layer table-scoped personal-field entries returned by PersonalFieldsSetupsService_GetPersonalFieldsByTable, or the static map when PERSONAL_FIELDS_SOURCE=static.
  • Matching rule: A property is marked personal when table name + field name matches a PersonalFieldsSetups row.
  • Scope: Classification is applied to both top-level entity properties and nested complex-type properties.
  • Nested resolution: For complex properties, table context switches using child table mapping and continues recursively for deeper nesting.

Where classification appears

  • In Step 2 schema output via b1_get_entity_schema, personal properties are flagged with isPersonalField.
  • This includes scalar fields and nested structural type properties when the table mapping marks them as personal.

Runtime protections

When MCP_HUMAN_CONFIRMATION_ENABLED=true:

  • Write operations (create, update, delete) require explicit user confirmation, through MCP elicitation or b1_confirm_operation.
  • Sensitive reads require confirmation when selectString explicitly includes personal top-level fields.

Redaction behavior for read results

Read redaction depends on whether selectString is meaningful:

  • No selectString (or blank/whitespace): full-response redaction is applied recursively to personal fields in both top-level and nested complex data.
  • Meaningful selectString with only scalar selections: selected scalar fields are returned as requested.
  • Meaningful selectString including complex properties: selected scalar fields remain visible, and personal fields inside selected complex properties are redacted recursively.

This means a selected top-level scalar personal field can be visible after user confirmation, while nested personal fields inside selected complex properties are still redacted.

For more details about personal data configuration, see this link: SAP Business One Help Portal - Protecting Personal Data.


UDO/UDT/UDF Support

The server automatically discovers and exposes User-Defined Objects (UDO), User-Defined Tables (UDT), and User-Defined Fields (UDF) alongside standard SAP B1 entities — no additional configuration required.

  • UDOs registered in SAP B1 appear as queryable and writable entities in b1_find_entities, discoverable under their assigned business category.
  • UDTs (custom tables prefixed with @) are surfaced as first-class entities and support the same CRUD operations as standard entities.
  • UDFs added to standard or custom tables are included automatically in the schema returned by b1_get_entity_schema, with correct types and metadata.

This means any customization made in SAP B1 — partner extensions, localization add-ons, or customer-specific fields — is immediately available to AI agents through the same 3-step discovery flow, without any server-side changes.

UDO Naming

UDO codes must comply with OData identifier rules to be recognized by Service Layer. Use only letters, digits, and underscores — no spaces or other special characters (e.g. use MY_CUSTOM_OBJECT, not My Custom Object). UDOs with non-compliant codes will not be discoverable.

Discovery Delay

UDOs and UDTs added or modified through the SAP B1 client, Web Client, or add-ons are not reflected in the MCP server immediately. The server caches OData metadata fetched from Service Layer for a configurable period (default: 30 minutes, controlled by METADATA_CACHE_TTL_MINUTES). New or changed UDOs/UDTs will only become discoverable after the cache expires naturally, or when the MCP server is restarted. During active development of custom objects, lower METADATA_CACHE_TTL_MINUTES to a smaller value (e.g. 5) to pick up changes faster.


Multi-Tenant Support

A single MCP server instance can serve multiple SAP Business One companies without any configuration changes. In OAuth mode, the active tenant or company is selected dynamically at runtime using the System Landscape Directory (SLD).

How it works:

  1. The MCP client calls b1_list_companies to retrieve all available companies registered in the SLD, along with their status.
  2. The user (or AI agent, guided by the user) selects the target company by calling b1_select_company with the chosen CompanySchemaName.
  3. All subsequent tool calls (b1_find_entities, b1_read, b1_write, etc.) are routed to the selected company's Service Layer database for the duration of the session.
  4. To switch companies, call b1_select_company again with a different schema name — no server restart required.

Key characteristics:

  • Session-scoped: Company selection is bound to the MCP session. Different AI client sessions can operate against different companies simultaneously on the same server instance.
  • SLD-driven: The company list is sourced directly from the SLD and reflects the live state of registered companies. No static company list needs to be maintained in configuration.
  • OAuth-only: Multi-tenant company switching requires OAuth mode. Direct mode is single-company only (B1_COMPANY_DB is fixed in .env).

Note: If a valid x-b1-companyID header is already present in the request, the MCP server uses it directly — calling b1_list_companies and b1_select_company is not required. The purpose of those tools is simply to help the AI agent or user determine the correct company schema name and establish the company context when it is not already known. Once the desired company is known, its company ID (resolved from the CompanySchemaName) can be passed directly in the x-b1-companyID header of every subsequent MCP request.


Usage Examples

Natural Language Queries

Natural Language Tool Called Generated Parameters
"Show me 10 sales orders" b1_read { entityName: "Orders", operation: "read", topNumber: 10 }
"Get sales order DocEntry 12345" b1_read { entityName: "Orders", operation: "read-single", parameters: { DocEntry: 12345 } }
"Find sales orders over $1000" b1_read { entityName: "Orders", operation: "read", filterString: "DocTotal gt 1000" }
"Create a purchase order for vendor V00001" b1_write { entityName: "PurchaseOrders", operation: "create", parameters: { CardCode: "V00001" } }
"Update business partner C00001 phone number" b1_write { entityName: "BusinessPartners", operation: "update", parameters: { CardCode: "C00001", Phone1: "123-456-7890" } }

Workflow Examples

To implement additional business workflows or add new MCP tools, see Developer guide.

Basic CRUD Workflow

1. b1_find_entities → "BusinessPartners"
  ↓ Returns: List of matching entities

2. b1_get_entity_schema → "BusinessPartners"
  ↓ Returns: scalar properties plus structuralProperties[]

3. b1_get_entity_schema → "BusinessPartners", structuralPropertyName="ContactEmployees"
  ↓ Returns: sub-properties for that structural property when needed

4. b1_read or b1_write → execute the selected operation
   ✓ Executes operation with proper parameters

Order to Cash Workflow (Step-by-Step)

1. b1_write → Create Sales Order
   ↓ Returns: DocEntry 123

2. b1_copy_document → Order → Delivery
   ↓ Returns: DocEntry 456 (automatic BaseType handling)

3. b1_copy_document → Delivery → Invoice
   ↓ Returns: DocEntry 789 (automatic BaseType handling)

4. b1_create_payment → Create Payment
   ✓ Validates and creates payment (automatic balance checking)

Production Order Workflow (Step-by-Step)

Production runs entirely through b1_write: releasing and closing are plain updates of ProductionOrderStatus, and issues and receipts are ordinary inventory documents that point to the order with BaseType: 202.

1. b1_write → create ProductTrees (bill of materials)
   { "TreeCode": "10442", "TreeType": "iProductionTree", "Quantity": 1, "Warehouse": "CEN",
     "ProductTreeLines": [{ "ItemCode": "10287", "Quantity": 1, "Warehouse": "CEN" }, ...] }
   ↓ Parent and components must exist as items linked to the warehouse

2. b1_write → create ProductionOrders
   { "ItemNo": "10442", "ProductionOrderType": "bopotStandard", "PlannedQuantity": 1,
     "Warehouse": "CEN", "DueDate": "2026-10-30" }
   ↓ Returns: AbsoluteEntry 1468 (lines are filled in from the bill of materials)

3. b1_write → update ProductionOrders
   { "AbsoluteEntry": 1468, "ProductionOrderStatus": "boposReleased" }

4. b1_write → create InventoryGenExits (issue for production)
   { "DocumentLines": [{ "BaseType": 202, "BaseEntry": 1468, "BaseLine": 0, "Quantity": 1,
       "WarehouseCode": "CEN", "SerialNumbers": [{ "InternalSerialNumber": "SN-1", "Quantity": 1 }] }, ...] }
   ↓ BaseLine is the production order's LineNumber; serial-managed components need their serials

5. b1_write → create InventoryGenEntries (receipt from production)
   { "DocumentLines": [{ "BaseType": 202, "BaseEntry": 1468, "Quantity": 1, "WarehouseCode": "CEN",
       "SerialNumbers": [{ "InternalSerialNumber": "SN-FG-1", "Quantity": 1 }] }] }

6. b1_write → update ProductionOrders
   { "AbsoluteEntry": 1468, "ProductionOrderStatus": "boposClosed" }
   ✓ Order closed with CompletedQuantity and IssuedQuantity filled in

Documents posted on a date without a USD exchange rate fail with Update the exchange rate 'USD'. The MCP cannot set rates (SBOBobService_SetCurrencyRate is not supported), so enter the rate in the B1 client first.

Business Intelligence Queries

User: "Show me top 10 customers by balance"
→ Tool: b1_read
→ Parameters:
  {
    "entityName": "BusinessPartners",
    "operation": "read",
    "filterString": "CardType eq 'cCustomer'",
    "orderbyString": "CurrentAccountBalance desc",
    "topNumber": 10
  }
User: "How many open sales orders are there?"
→ Tool: b1_read
→ Parameters:
  {
    "entityName": "Orders",
    "operation": "read",
    "filterString": "DocumentStatus eq 'bost_Open'",
    "selectString": "DocEntry"
  }

Data Manipulation

User: "Update supplier V10000 to have phone number 123-456-7890"
→ Tool: b1_write
→ Parameters:
  {
    "entityName": "BusinessPartners",
    "operation": "update",
    "parameters": {
      "CardCode": "V10000",
      "Phone1": "123-456-7890"
    }
  }

Testing the Server

Unit Tests

npm test

This is an alias for npm run test:unit. Unit tests live under src/tests/unit/.

Integration Tests

Integration tests require a running MCP server with a reachable Service Layer and OAuth provider. They also require the b1_mcp:access scope to be configured in Keycloak — see KEYCLOAK_SETUP.md for setup instructions. Configure the test client credentials in your .env, then run:

npm run test:integration

Key variables for integration tests:

Variable Description
TEST_MCP_CLIENT_ID OAuth client ID used by the test runner
TEST_OAUTH_SCOPES Scopes to request (e.g. email b1_mcp:access profile)
TEST_OAUTH_INTERACTIVE Set to true to trigger a browser-based login during tests

Integration tests live under src/tests/integration/.

Note: If a test fails after updating dependencies, run npm run build first — compile-time errors often surface there before the test runner does.

Full Quality Check

Run lint, build, and unit tests in sequence:

npm run lint
npm run build
npm test
npm run test:integration

Logging

The server produces two separate log streams, each independently configurable.

Application Logs

Application logs cover request handling, tool dispatch, session lifecycle, and Service Layer calls. The default level is info. Enable verbose logging during development to trace what the server is doing:

APP_LOG_LEVEL=debug
APP_LOG_CONSOLE_ENABLED=true

Logs are written to a rotating file by default (APP_LOG_FILE_ENABLED=true). File size and retention are controlled by APP_LOG_MAX_SIZE_BYTES (default 10 MB) and APP_LOG_RETENTION_DAYS (default 90 days).

Audit Logs

Audit logs record security-relevant events: write confirmations, session starts and expiry, and authentication failures. They are written to a rotating file by default and should remain enabled in production.

To also stream audit events to the console during development:

AUDIT_LOG_CONSOLE_ENABLED=true

File size and retention are controlled by AUDIT_LOG_MAX_SIZE_BYTES (default 10 MB) and AUDIT_LOG_RETENTION_DAYS (default 365 days).

For the full list of logging variables, see Configuration reference.

For step-by-step Keycloak configuration required for OAuth mode — including MCP server client registration, client scope, audience mapper, and trusted hosts — see Keycloak setup.


Security Considerations

Note: This project is a sample. Before deploying to a production environment, review and harden all security settings in accordance with your organization's security standards and compliance requirements.

Authentication

This MCP server acts as a Resource Server (RS) in the OAuth 2.0 framework and uses the standard MCP authentication mechanism. Every request from an AI agent must carry a valid bearer access token; the server validates the token before processing any request.

Access tokens are obtained from the SAP Business One Identity and Authentication Management service by providing valid user credentials. This service is built on top of Keycloak and can be configured to connect to SAP IAS (Identity Authentication Service) or other identity providers for user authentication.

Authorization

Authorization is enforced at two layers:

Layer 1 — MCP server: checks the scope and aud (audience) claims of the access token to determine whether the AI agent is permitted to invoke the requested MCP tools. Only tokens that carry the required b1_mcp:access scope and are addressed to this server are accepted.

Layer 2 — SAP B1 Service Layer: delegates the data-access decision to Service Layer, which evaluates the user roles and permissions associated with the token against the standard SAP Business One access control model. Administrators can define fine-grained access policies per user and group. If Service Layer returns HTTP 403 (Forbidden), the MCP server surfaces an error to the AI agent indicating insufficient privileges and does not return any data.

Production Configuration

Review these settings before any production deployment.

Transport - HTTPS_ENABLED — defaults to true. Always use HTTPS in production. Only disable behind a TLS-terminating reverse proxy. - AUTH_ALLOW_SELF_SIGNED — defaults to false. Never enable in production; use a valid CA or NODE_EXTRA_CA_CERTS.

Token validation - TOKEN_VALIDATION_MODE — use introspection or introspection-with-jwt-fallback (default) in production. Avoid jwt-only mode unless tokens are short-lived (< 5 min), as revoked tokens remain valid until expiry. - VALIDATE_AUDIENCE — defaults to true. Disabling it allows tokens issued for other services to authenticate; only disable if your OAuth provider cannot restrict the aud claim. - OAUTH_VERIFY_SCOPES / OAUTH_REQUIRED_SCOPES — keep scope verification enabled and restrict to the minimum required scope (b1_mcp:access).

Network and access control - MCP_ALLOWED_HOSTS — list all hostnames through which the server is reachable. Requests with a non-matching Host header are rejected (DNS rebinding protection). - REQUEST_BODY_LIMIT — keep small (default 1mb) to limit memory and reduce DoS risk. - CORS_ALLOWED_ORIGINS — leave unset (CORS disabled) unless browser-based clients require it. Avoid * in production. - MCP_RATE_LIMIT_WINDOW_MINUTES / MCP_RATE_LIMIT_MAX — tune to match expected client throughput.

Session and write safety - SESSION_TIMEOUT_MINUTES — idle sessions are expired and audited. Keep short in production (default: 30 min). - MCP_HUMAN_CONFIRMATION_ENABLED — defaults to true. Require user confirmation before any write. Only disable in fully automated, non-interactive pipelines.

Audit logging - AUDIT_LOG_FILE_ENABLED — defaults to true. Audit logs record all write confirmations and session events. Keep enabled in production and set AUDIT_LOG_RETENTION_DAYS to meet your compliance requirements.


Troubleshooting

Server or connection issues

  • Verify Node.js >= 22.22.3 (node --version) and that npm run build completes without errors.
  • Check that SERVICE_LAYER_ROOT_URL is the host only — no /b1s/v2/ path (e.g. https://servicelayer.b1.example.com:50000).
  • Confirm the server is running: curl http://localhost:3000/health.
  • Verify the MCP endpoint URL in the client config matches the server address and restart VS Code if tools do not appear.

Authentication and company context

  • Direct mode: verify B1_COMPANY_DB, B1_USERNAME, and B1_PASSWORD.
  • OAuth mode: verify OAUTH_BASE_URL, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, and SLD_ROOT_URL. If Service Layer uses a self-signed certificate, set AUTH_ALLOW_SELF_SIGNED=true (development only).
  • Check Keycloak trusted hosts if VS Code clients fail with Failed to verify remote host — see Keycloak setup.
  • In OAuth mode, always call b1_list_companies then b1_select_company before any entity tool call. Without a selected company, tools will not return SAP B1 data.

Entity, field, or write issues

  • Use b1_find_entities to confirm the correct entity name (case-sensitive) and b1_get_entity_schema to verify property names before building filter or select strings.
  • If write operations wait for a prompt that never appears, the client declares elicitation but does not show it: remove its name from MCP_ELICITATION_CLIENTS (or set MCP_CONFIRMATION_CHANNEL=tool) so it confirms through b1_confirm_operation. Set MCP_HUMAN_CONFIRMATION_ENABLED=false only for automated pipelines.

Enable debug options

Enable verbose logging to trace request handling and Service Layer calls:

APP_LOG_LEVEL=debug
APP_LOG_CONSOLE_ENABLED=true
AUDIT_LOG_CONSOLE_ENABLED=true

Configuration Reference

For the full list of environment variables grouped by category (authentication, HTTPS, OAuth, session, caching, logging), see Configuration reference.


Limitation

  • The stdio transport is not supported. Only streamable HTTP is supported.
  • OData actions/functions are not supported in general. Only standard CRUD operations on entities are available, plus the Cancel/Close document actions and DraftsService_SaveDraftToDocument exposed through b1_document_action and PickListsService_UpdateReleasedAllocation used by b1_pick_list.
  • Attachment/Picture upload/download is not supported in the current MCP server sample.
  • OData batch operations are not supported in the current MCP server sample. Each entity operation must be performed individually.
  • Advanced OData queries are not fully supported. Only basic $filter, $select, $top, and $orderby are implemented in the MCP tools.