mcp-zenskar 2.3.0 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/mcp-config.json +40 -0
- package/dist/server.mjs +9 -9
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Zenskar MCP Server
|
|
2
2
|
|
|
3
|
-
MCP server for the Zenskar API.
|
|
3
|
+
MCP server for the Zenskar API. 115 tools covering customers, contracts, invoices, payments, credit notes, accounting, products, plans, entitlements, billable metrics, and more.
|
|
4
4
|
|
|
5
5
|
## What it does
|
|
6
6
|
|
|
@@ -290,6 +290,7 @@ Once configured, you can ask Claude to interact with your Zenskar data:
|
|
|
290
290
|
| `getRawMetricLogs` | Get recent event rows for a Usage Event using the same preview-query path as the frontend |
|
|
291
291
|
| `getRawMetricBySlug` | Get a Usage Event by API slug; backend/API may also call it a raw metric |
|
|
292
292
|
| `ingestRawMetricEvent` | Ingest a usage event |
|
|
293
|
+
| `ingestRawMetricEventsBulk` | Ingest multiple usage events (up to 500) for a resource slug in a single call |
|
|
293
294
|
|
|
294
295
|
### Entitlements
|
|
295
296
|
|
package/dist/mcp-config.json
CHANGED
|
@@ -2903,6 +2903,46 @@
|
|
|
2903
2903
|
"prependBody": "## Usage Event Ingested\n\nThe usage event was ingested successfully:\n\n"
|
|
2904
2904
|
}
|
|
2905
2905
|
},
|
|
2906
|
+
{
|
|
2907
|
+
"name": "ingestRawMetricEventsBulk",
|
|
2908
|
+
"description": "Ingest MULTIPLE Usage Events for the specified resource slug in a single API call (bulk ingestion). Use this instead of calling ingestRawMetricEvent once per event — it sends one HTTP request carrying every event, which is far more efficient for CSV/batch imports. Each element of 'events' has the same shape as ingestRawMetricEvent's 'event' arg: customer_id, timestamp, and a data map with schema-compliant types. If importing from a CSV (or any source) whose column names don't clearly correspond to the expected fields (customer_id, timestamp, data.*), confirm the mapping with the user before constructing events — do not guess a mapping silently. Limit: 500 events per call — split larger batches into multiple calls. Host enforces user confirmation via the approval gate; do NOT ask the user to re-confirm before calling.",
|
|
2909
|
+
"needsApproval": true,
|
|
2910
|
+
"approvalConfig": {
|
|
2911
|
+
"title": "Ingest Usage Events (Bulk)",
|
|
2912
|
+
"description": "This will ingest ALL of the listed Usage Events for the selected Usage Event schema in one request. Review the full payload carefully — approving this ingests every event shown, not just one.",
|
|
2913
|
+
"warningText": "Ensure every event's data payload matches the Usage Event schema (raw metric schema) before proceeding. Up to 500 events are ingested in a single call; review the count and a sample of entries before confirming.",
|
|
2914
|
+
"confirmText": "Ingest Usage Events",
|
|
2915
|
+
"cancelText": "Cancel",
|
|
2916
|
+
"sensitiveFields": ["rawMetricSlug", "events"]
|
|
2917
|
+
},
|
|
2918
|
+
"args": [
|
|
2919
|
+
{
|
|
2920
|
+
"name": "rawMetricSlug",
|
|
2921
|
+
"description": "Slug of the Usage Event resource (raw metric), e.g. api_usage_events.",
|
|
2922
|
+
"type": "string",
|
|
2923
|
+
"required": true,
|
|
2924
|
+
"position": "path"
|
|
2925
|
+
},
|
|
2926
|
+
{
|
|
2927
|
+
"name": "events",
|
|
2928
|
+
"description": "Array of Usage Event payloads, each containing customer_id, timestamp, and a data map with schema-compliant types — same shape as ingestRawMetricEvent's 'event' arg, but plural. customer_id and timestamp are mandatory on EVERY event; MCP does not auto-add them. Events are validated server-side against the raw metric's real schema before anything is sent — an unknown data field or wrong type is rejected with the exact list of valid fields, so you do NOT need to pre-fetch the schema via getRawMetricBySlug first; only do so if you're unsure what fields/types this raw metric expects. Maximum 500 events per call — if you have more, split into multiple calls to this tool. Prefer 100–200 events per call: batches approaching 500 consume significant context, more so under stateless approval (the batch is base64-packed into the approval token and echoed back verbatim). Example event shape: {\"customer_id\": \"example_customer\", \"timestamp\": \"2025-01-01 00:00:00\", \"data\": {\"String\": \"sample value\", \"Int64\": 10, \"Float64\": 42.5}}.",
|
|
2929
|
+
"type": "array",
|
|
2930
|
+
"required": true,
|
|
2931
|
+
"position": "body"
|
|
2932
|
+
}
|
|
2933
|
+
],
|
|
2934
|
+
"requestTemplate": {
|
|
2935
|
+
"url": "/usage/{rawMetricSlug}",
|
|
2936
|
+
"method": "POST",
|
|
2937
|
+
"headers": {
|
|
2938
|
+
"Content-Type": "application/json",
|
|
2939
|
+
"apiversion": "20240301"
|
|
2940
|
+
}
|
|
2941
|
+
},
|
|
2942
|
+
"responseTemplate": {
|
|
2943
|
+
"prependBody": "## Usage Events Ingested (Bulk)\n\nThe usage events were ingested successfully:\n\n"
|
|
2944
|
+
}
|
|
2945
|
+
},
|
|
2906
2946
|
{
|
|
2907
2947
|
"name": "extractContractFromRaw",
|
|
2908
2948
|
"description": "Extract structured contract data from raw text content using AI. This tool analyzes natural language contract descriptions and extracts key fields like dates, products, pricing, and billing terms. The extracted data can then be used to create a customer and contract via createCustomer and createContract tools.",
|
package/dist/server.mjs
CHANGED
|
@@ -75,25 +75,25 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
75
75
|
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),wm(t)}clear(){this._buffer=void 0}};function wm(e){return ml.parse(JSON.parse(e))}function Tm(e){return JSON.stringify(e)+`
|
|
76
76
|
`}var Em=class{constructor(e=c.stdin,t=c.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Cm,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{this.onerror?.(e)}}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=Tm(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};const Dm=[];for(let e=0;e<256;++e)Dm.push((e+256).toString(16).slice(1));function Om(e,t=0){return(Dm[e[t+0]]+Dm[e[t+1]]+Dm[e[t+2]]+Dm[e[t+3]]+`-`+Dm[e[t+4]]+Dm[e[t+5]]+`-`+Dm[e[t+6]]+Dm[e[t+7]]+`-`+Dm[e[t+8]]+Dm[e[t+9]]+`-`+Dm[e[t+10]]+Dm[e[t+11]]+Dm[e[t+12]]+Dm[e[t+13]]+Dm[e[t+14]]+Dm[e[t+15]]).toLowerCase()}const km=new Uint8Array(16);function Am(){return crypto.getRandomValues(km)}function jm(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():Mm(e,t,n)}function Mm(e,t,n){e||={};let r=e.random??e.rng?.()??Am();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return Om(r)}var Nm=class{constructor(){this.maxResponseLength=2e6}processResponse(e,t){try{let t=typeof e==`string`?e:JSON.stringify(e,null,2);return t.length>this.maxResponseLength&&(t=t.substring(0,this.maxResponseLength)+`
|
|
77
77
|
|
|
78
|
-
[Response truncated due to length]`),t}catch(e){return console.error(`Response processing error:`,e),`Error processing response`}}};function Pm(e){if(!e||typeof e!=`object`||Array.isArray(e))return nc();let t=e.oneOf||e.anyOf;if(Array.isArray(t)&&t.length>0){let e=t.map(Pm);return e.length===1?e[0]:U(e)}if(Array.isArray(e.enum)&&e.enum.length>0){let t=e.enum.filter(e=>typeof e==`string`);if(t.length===e.enum.length&&t.length>0)return gc(t)}let n,r=Array.isArray(e.type)?e.type[0]:e.type;if(r===`integer`||r===`number`)n=r===`integer`?z().int():z(),typeof e.minimum==`number`&&(n=n.min(e.minimum)),typeof e.maximum==`number`&&(n=n.max(e.maximum));else if(r===`boolean`)n=Qs();else if(r===`array`)n=V(Pm(e.items)),typeof e.minItems==`number`&&(n=n.min(e.minItems)),typeof e.maxItems==`number`&&(n=n.max(e.maxItems));else if(r===`object`){let t=new Set(Array.isArray(e.required)?e.required:[]),r=e.properties||{},i={};Object.entries(r).forEach(([e,n])=>{let r=Pm(n);t.has(e)||(r=r.optional()),i[e]=r}),n=e.additionalProperties===!1?H(i):H(i).passthrough()}else n=L();return e.description&&(n=n.describe(e.description)),n}function Fm(e){let t={};return e.forEach(e=>{let n;n=e.schema?Pm(e.schema):e.type===`integer`||e.type===`number`?z():e.type===`boolean`?Qs():e.type===`object`?W(nc()):e.type===`array`?V(nc()):e.type===`datetime`?U([L(),z()]):L(),e.default!==void 0&&(n=n.default(e.default)),e.required||(n=n.optional()),e.description&&(n=n.describe(e.description)),t[e.name]=n}),t.__userContext=H({userId:L().optional(),authorization:L().optional(),organization:L().optional(),apiKey:L().optional(),headers:H({}).optional(),approval:H({approved:Qs(),token:L().optional(),modifiedArguments:W(nc()).optional(),originalArguments:W(nc()).optional(),toolName:L().optional()}).optional()}).optional().describe(`Internal user context for multi-tenant authentication and approval workflow`),t}const Im={generateInvoice(e){let t=[],n=e=>{if(typeof e==`number`)return Number.isInteger(e)?e:null;if(typeof e==`string`){let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):null}return null},r=n(e.from_date),i=n(e.to_date);return r===null&&t.push(`'from_date' must be either an integer UNIX timestamp (seconds) or an ISO-8601 datetime string. Copy from getContractBillingCycles.start_date.`),i===null&&t.push(`'to_date' must be either an integer UNIX timestamp (seconds) or an ISO-8601 datetime string. Copy from getContractBillingCycles.end_date.`),r!==null&&i!==null&&i<=r&&t.push(`'to_date' must be strictly greater than 'from_date'.`),n(e.bill_for_date)===null&&t.push(`'bill_for_date' is REQUIRED (UNIX seconds or ISO-8601 string). Without it the API returns a $0 invoice. Copy from getContractBillingCycles.bill_for_date — do NOT compute.`),(!Number.isInteger(e.billing_cycle_start_day)||e.billing_cycle_start_day<1||e.billing_cycle_start_day>31)&&t.push(`'billing_cycle_start_day' is REQUIRED and must be an integer 1-31. Copy from getContractBillingCycles.billing_cycle_start_day.`),t},pauseContract(e){let t=[];return e.start_date||t.push(`'start_date' is required (ISO 8601).`),e.unpause_extension_policy||t.push(`'unpause_extension_policy' is required: 'extend' or 'overlap'.`),t},updateContract(e){let t=[],n=Array.isArray(e.phases)?e.phases:null,r=e=>{if(e==null||e===``)return null;let t=Date.parse(e);return Number.isFinite(t)?t:NaN},i=r(e.end_date),a=Number.isFinite(i),o=e=>{let t=r(e&&e.end_date);return Number.isFinite(t)?t:null},s=[];if(Number.isNaN(i)&&s.push(`contract end_date '${e.end_date}'`),n&&n.forEach((e,t)=>{Number.isNaN(r(e&&e.end_date))&&s.push(`phase ${t+1} end_date '${e.end_date}'`)}),s.length>0&&t.push(`Unparseable date(s): ${s.join(`, `)}. Use ISO 8601, e.g. 2026-08-24T00:00:00. Day-first formats such as 24/08/2026 are not accepted, and a date that cannot be parsed is not treated as an absent one.`),a&&i<Date.now()&&t.push(`'end_date' is in the past, which expires the contract. Call expireContract instead — it sets the same end_date and also prunes future phases, trims overlapping phases and caps product dates.`),a&&n){let e=n.filter(e=>{let t=o(e);return t!==null&&t>i});e.length>0&&t.push(`${e.length} phase(s) end after the contract-level 'end_date'. The API rejects this. To shorten contracts call expireContract, which trims phases automatically and accepts several contract ids in one call; otherwise set each phase end_date to at most the contract 'end_date'.`)}return!a&&n&&n.length>0&&n.every(e=>o(e)!==null)&&t.push(`Every phase has an 'end_date' but no contract-level 'end_date' was supplied. Contract status is derived from the contract-level end_date, not from phase dates, so this would leave the contract ACTIVE with no current phase. To expire the contract, call expireContract — it also trims phases and product dates, and accepts several contract ids in one call. To update without expiring, keep a phase open or set 'end_date' explicitly.`),t},expireContract(e){return e.expiry_date===void 0||e.expiry_date===null||Number.isFinite(Date.parse(e.expiry_date))?[]:[`Unparseable 'expiry_date' '${e.expiry_date}'. Use ISO 8601, e.g. 2026-08-24. Day-first formats such as 24/08/2026 are not accepted.`]}};function Lm(e,t){let{listArg:n,maxBatch:r}=e.bulkOver,i=t[n];if(!Array.isArray(i))return[];let a=[];i.length===0&&a.push(`'${n}' is empty — nothing to do.`),r!==void 0&&i.length>r&&a.push(`'${n}' has ${i.length} entries. The limit is ${r}. ${e.name} runs one item at a time. A batch must be small enough to review in one approval. It must also complete before the client timeout. Send fewer ids.`);let o=i.filter(e=>typeof e!=`string`||e.trim()===``);o.length>0&&a.push(`'${n}' has ${o.length} empty or non-string entries.`);let s=[...new Set(i.filter((e,t)=>i.indexOf(e)!==t))];return s.length>0&&a.push(`'${n}' repeats ${s.join(`, `)}.`),a}function Rm(e,t){let n=Im[e.name]?Im[e.name](t):[];return e.bulkOver&&n.push(...Lm(e,t)),{valid:n.length===0,errors:n}}function zm(e){return!e||typeof e!=`string`?``:e.replace(/[_-]+/g,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/\b\w/g,e=>e.toUpperCase()).trim()}const Bm=new Set([`getInvoiceSummary`,`getCustomerBalance`,`getPaymentStatus`]),Vm={listCustomers:{shape:`customer-table`,noun:`customer`,toPayload:Wm,threshold:0},listInvoices:{shape:`invoice-table`,noun:`invoice`,toPayload:Km,threshold:0},getInvoiceLineItems:{shape:`invoice-line-items`,noun:`line item`,toPayload:Jm,threshold:0},listAllPayments:{shape:`payment-table`,noun:`payment`,toPayload:$m,threshold:0},listCreditNotes:{shape:`credit-note-table`,noun:`credit note`,toPayload:th,threshold:0},listContracts:{shape:`contract-table`,noun:`contract`,toPayload:rh,threshold:0},getCustomerById:{shape:`customer-detail`,noun:`customer`,toPayload:ah,threshold:0},getInvoiceById:{shape:`invoice-detail`,noun:`invoice`,toPayload:oh,threshold:0},getContractById:{shape:`contract-detail`,noun:`contract`,toPayload:sh,threshold:0},getCreditNoteById:{shape:`credit-note-detail`,noun:`credit note`,toPayload:fh,threshold:0},listProducts:{shape:`product-table`,noun:`product`,toPayload:ph,threshold:0},listPlans:{shape:`plan-table`,noun:`plan`,toPayload:hh,threshold:0},listJournalEntries:{shape:`journal-table`,noun:`journal entry`,toPayload:_h,threshold:0},listJobs:{shape:`job-table`,noun:`job`,toPayload:yh,threshold:0},listContacts:{shape:`contact-table`,noun:`contact`,toPayload:xh,threshold:0},listRawMetrics:{shape:`raw-metric-table`,noun:`raw metric`,toPayload:Ch,threshold:0},listAggregates:{shape:`aggregate-table`,noun:`aggregate`,toPayload:Th,threshold:0},listCustomerAddresses:{shape:`address-list`,noun:`address`,toPayload:Dh,threshold:0},listPaymentMethods:{shape:`payment-method-list`,noun:`payment method`,toPayload:kh,threshold:0},listBusinessEntities:{shape:`entity-table`,noun:`business entity`,toPayload:jh,threshold:0},listEntitlements:{shape:`entitlement-table`,noun:`entitlement`,toPayload:Nh,threshold:0},getInvoicePreviewHtml:{shape:`invoice-preview`,noun:`invoice preview`,toPayload:zh,threshold:0}},Hm=Object.freeze([`app`]);function Um(e){return`ui://zenskar/app.html`}function Wm(e,t){let n=Gm(e),r=Fh(n,[`customers`,`data`,`results`]),i=Lh(n,[`total`,`count`,`total_count`])??r.length,a=Ih(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search_name_external_id||t.search)||void 0;return{customers:r.map(Qm),total:i,cursor:{next:o,prev:s},scope:c}}function Gm(e){return e&&typeof e==`object`&&e.api_response&&typeof e.api_response==`object`?e.api_response:e||{}}function Km(e,t){let n=Gm(e),r=Fh(n,[`invoices`,`data`,`results`]),i=Lh(n,[`total`,`count`,`total_count`])??r.length,a=Ih(n,[`cursor`,`pagination`])||{},o=a.next??n.next??null,s=a.prev??n.previous??null;return{invoices:r.map(qm),total:i,cursor:{next:o,prev:s},scope:t&&(t.customer__customer_name__ilike||t.invoice_number__like||t.status)||void 0,default_currency:`USD`}}function qm(e){if(!e||typeof e!=`object`)return{id:``,invoice_number:null,customer_id:null,customer_name:null,status:null,invoice_total:null,amount_due:null,due_date:null,invoice_period_begin:null,invoice_period_end:null,external_id:null,created_at:null,payment_url:null};let t=e.invoice_period||{},n=e.customer&&typeof e.customer==`object`?e.customer:null;return{id:String(e.id||e.invoice_id||``),invoice_number:e.invoice_number??null,customer_id:n?.id??e.customer_id??null,customer_name:n?.customer_name??n?.name??null,status:e.status??null,invoice_total:Rh(e.net_invoice_total??e.invoice_total),amount_due:Rh(e.amount_due),due_date:e.due_date??e.promise_due_date??null,invoice_period_begin:t.begin_date??e.period_begin_date??null,invoice_period_end:t.end_date_exclusive??e.period_end_date??null,external_id:e.external_id??null,created_at:e.created_at??null,payment_url:e.payment_url??null}}function Jm(e,t){let n=Gm(e),r=Array.isArray(n.lines)?n.lines:Array.isArray(n)?n:[],i=Rh(n.total),a=Ym(r)||`USD`;return{invoice_id:t&&t.invoiceId?String(t.invoiceId):void 0,total:i,currency:a,lines:r.map(Xm)}}function Ym(e){for(let t of e){if(t&&t.subtotal&&t.subtotal.unit)return t.subtotal.unit;if(t&&t.features&&t.features[0]&&t.features[0].currency)return t.features[0].currency}return null}function Xm(e){return!e||typeof e!=`object`?{name:``,description:null,pricing_model:null,subtotal:{value:null,unit:null},quantity:{value:null,unit:null},price:null,service_start_date:null,service_end_date:null,is_billed:null}:{name:e.name??e.description??``,description:e.description??null,pricing_model:e.pricing_model??null,subtotal:Zm(e.subtotal),quantity:Zm(e.quantity),price:e.price?Zm(e.price):null,service_start_date:e.service_start_date??e.billing_period_start??null,service_end_date:e.service_end_date??e.billing_period_end??null,is_billed:typeof e.is_billed==`boolean`?e.is_billed:null,line_item_type:e.line_item_type??null,is_adjustment:typeof e.is_adjustment==`boolean`?e.is_adjustment:null,adjustment_type:e.adjustment_type??null}}function Zm(e){return e?{value:Rh(e.value),unit:e.unit??null,display:e.display??null}:{value:null,unit:null,display:null}}function Qm(e){return!e||typeof e!=`object`?{id:``,name:null,external_id:null,email:null}:{id:String(e.id||e.customer_id||``),name:e.customer_name??e.name??null,external_id:e.external_id??null,email:e.email??e.primary_email??null,created_at:e.created_at??e.created??null}}function $m(e,t){let n=Gm(e),r=Fh(n,[`payments`,`data`,`results`]),i=Lh(n,[`total`,`count`,`total_count`])??r.length,a=Ih(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search||t.customer_id||t.type||t.payment_method)||void 0;return{payments:r.map(eh),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0,default_currency:`USD`}}function eh(e){if(!e||typeof e!=`object`)return{id:``,external_id:null,customer_id:null,customer_name:null,invoice_id:null,invoice_name:null,amount:null,currency:null,payment_method:null,type:null,status:null,description:null,payment_date:null,created_at:null};let t=((Array.isArray(e.payment_parts)?e.payment_parts:[]).find(e=>e&&e.invoice_id)||{}).invoice_id||e.invoice_id||null,n=e.customer&&typeof e.customer==`object`?e.customer:null,r=e.invoice&&typeof e.invoice==`object`?e.invoice:null;return{id:String(e.id||e.payment_id||``),external_id:e.external_id??null,customer_id:n?.id??e.customer_id??null,customer_name:n?.customer_name??n?.name??null,invoice_id:r?.id??t,invoice_name:r?.name??r?.invoice_number??null,amount:Rh(e.amount??e.value),currency:e.currency_code??e.currency??null,payment_method:e.payment_method??null,type:e.type??null,status:e.status??null,description:e.description??e.notes??null,payment_date:e.payment_date??e.received_at??e.processed_at??null,created_at:e.created_at??null}}function th(e,t){let n=Gm(e),r=Fh(n,[`credit_notes`,`creditNotes`,`data`,`results`]),i=Lh(n,[`total`,`count`,`total_count`])??r.length,a=Ih(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.customer_id||t.invoice_id||t.status)||void 0;return{credit_notes:r.map(nh),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0,default_currency:`USD`}}function nh(e){if(!e||typeof e!=`object`)return{id:``,credit_note_number:null,customer_id:null,customer_name:null,invoice_id:null,invoice_name:null,status:null,amount:null,currency:null,repayment_method:null,created_at:null};let t=e.customer&&typeof e.customer==`object`?e.customer:null,n=e.invoice&&typeof e.invoice==`object`?e.invoice:null;return{id:String(e.id||e.credit_note_id||``),credit_note_number:e.credit_note_number??null,customer_id:t?.id??e.customer_id??null,customer_name:t?.customer_name??t?.name??null,invoice_id:n?.id??e.invoice_id??null,invoice_name:n?.name??n?.invoice_number??null,status:e.status??null,amount:Rh(e.amount??e.total??e.value),currency:e.currency_code??e.currency??null,repayment_method:e.repayment_method??null,created_at:e.created_at??null}}function rh(e,t){let n=Gm(e),r=Fh(n,[`contracts`,`data`,`results`]),i=Lh(n,[`total`,`count`,`total_count`])??r.length,a=Ih(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.customer_id||t.name__ilike||t.status)||void 0;return{contracts:r.map(ih),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0}}function ih(e){if(!e||typeof e!=`object`)return{id:``,customer_id:null,customer_name:null,name:null,status:null,currency:null,start_date:null,end_date:null,created_at:null};let t=e.customer&&typeof e.customer==`object`?e.customer:null;return{id:String(e.id||e.contract_id||``),customer_id:t?.id??e.customer_id??null,customer_name:t?.customer_name??t?.name??null,name:e.name??e.contract_name??null,status:e.status??e.state??null,currency:e.currency??e.currency_code??null,start_date:e.start_date??null,end_date:e.end_date??null,created_at:e.created_at??null}}function ah(e){let t=Gm(e),n=t.customer??t,r=Qm(n),i=n.business_entity,a=n.default_payment_method,o=Array.isArray(n.contacts)?n.contacts:[],s=Array.isArray(n.tax_info)?n.tax_info:[];return{customer:{...r,phone:n.phone_number??n.phone??n.primary_phone??null,business_entity_id:n.business_entity_id??null,business_entity_name:(i&&typeof i==`object`?i.name:null)??null,address:n.address??null,ship_to_address:n.ship_to_address??null,communications_enabled:typeof n.communications_enabled==`boolean`?n.communications_enabled:null,auto_charge_enabled:typeof n.auto_charge_enabled==`boolean`?n.auto_charge_enabled:null,custom_data:n.custom_data??null,tax_info:s.length?s.map(e=>({country_code:e.country_code??null,tax_code:e.tax_code??null,tax_id:e.tax_id??null})):null,contacts:o.length?o.map(e=>({name:[e.first_name??``,e.last_name??``].filter(Boolean).join(` `)||null,email:e.email??null,send_invoice:typeof e.send_invoice==`boolean`?e.send_invoice:null,send_contract:typeof e.send_contract==`boolean`?e.send_contract:null})):null,default_payment_method:a&&typeof a==`object`?{type:a.type??null,brand:(a.details&&a.details.brand)??a.brand??null,last4:(a.details&&a.details.last4)??a.last4??null,connector_name:a.connector_name??null}:null,updated_at:n.updated_at??null}}}function oh(e){let t=Gm(e),n=t.invoice??t,r=qm(n),i=n.customer,a=n.contract;return{invoice:{...r,paid_amount:Rh(n.paid_amount??(r.invoice_total!=null&&r.amount_due!=null?r.invoice_total-r.amount_due:null)),currency:n.currency_code??n.currency??null,business_entity_id:n.business_entity_id??null,notes:n.notes??null,custom_data:n.custom_data??n.custom_attributes??null,customer_name:(i&&typeof i==`object`?i.name:null)??null,contract_id:n.contract_id??(a&&typeof a==`object`?a.id:null)??null,contract_name:(a&&typeof a==`object`?a.name:null)??null,invoice_pdf:n.invoice_pdf??null,approved_at:n.approved_at??null,paid_at:n.paid_at??null,sent_at:n.sent_at??null}}}function sh(e){let t=Gm(e),n=t.contract??t,r=ih(n),i=Array.isArray(n.phases)?n.phases:[],a=n.customer,o=Array.isArray(n.tags)?n.tags:[];return{contract:{...r,description:n.description??null,custom_attributes:n.custom_attributes??null,renewal_policy:n.renewal_policy??null,anchor_date:n.anchor_date??null,plan_id:n.plan_id??null,customer_name:(a&&typeof a==`object`?a.customer_name??a.name:null)??null,contract_type:n.contract_type??null,tags:o.length?o:null,contract_link:n.contract_link??null},phases:i.map(ch)}}function ch(e){if(!e||typeof e!=`object`)return{id:null,name:null,start_date:null,end_date:null,pricing_summary:null,product_count:null,pricings:[]};let t=Array.isArray(e.products)?e.products:[],n=Array.isArray(e.pricings)?e.pricings:t;return{id:e.id??null,name:e.name??e.phase_name??null,start_date:e.start_date??null,end_date:e.end_date??null,pricing_summary:e.pricing_summary??null,product_count:n.length||Rh(e.product_count),pricings:n.map(uh)}}function lh(e){return!e||!Array.isArray(e.prices)||!Array.isArray(e.dimensions)||e.prices.length===0?null:e.prices.map((t,n)=>({dimension:e.dimensions[n]?.name??null,display_alias:Array.isArray(e.display_alias)?e.display_alias[n]??null:null,price:typeof t==`number`?t:null}))}function uh(e){if(!e||typeof e!=`object`)return{product_name:null,pricing_model:null};let t=e.pricing??{},n=e.pricing_data??t.pricing_data??e,r=t.quantity??e.quantity??{},i=t.billing_period??e.billing_period??{},a=e.product??{};return{id:e.id??null,product_name:a.name??e.name??e.product_name??null,product_type:a.type??null,description:e.description??t.description??a.description??null,pricing_model:n.pricing_type??e.pricing_model??null,currency:n.currency??null,unit_amount:n.unit_amount??null,tiers:Array.isArray(n.tiers)?n.tiers:null,package_size:n.package_size??null,matrix:lh(n),quantity_type:r.type??null,quantity_value:r.quantity??null,quantity_unit:r.unit??null,meter_name:r.aggregate?.name??r.aggregate_name??null,billing_cadence:i.cadence??null,billing_timing:e.billing_timing??t.billing_timing??null,is_recurring:typeof t.is_recurring==`boolean`?t.is_recurring:typeof e.is_recurring==`boolean`?e.is_recurring:null,start_date:e.start_date??null,end_date:e.end_date??null,features:dh(t)}}function dh(e){let t=[],n=t=>Array.isArray(e[t])?e[t]:[];for(let e of n(`discounts`)){let n=e.type===`percentage`;t.push({type:`Discount`,label:e.label??null,summary:`${e.unit_amount??`?`}${n?`%`:` (Fixed)`}`})}for(let e of n(`taxes`)){let n=e.type===`avalara`;t.push({type:`Tax`,label:e.label??null,summary:n?`Avalara - ${e.code??`?`}`:`${e.unit_amount??`?`}%`})}for(let e of n(`free_units`))t.push({type:`Free Units`,label:e.label??null,summary:`${e.unit_amount??`?`} units`});for(let e of n(`commitments`)){let n=e.type?zm(e.type):`Commitment`;t.push({type:`Commitment`,label:e.label??null,summary:`${n}: ${e.unit_amount??`?`}`})}for(let e of n(`grants`)){let n=e.trigger_event?zm(e.trigger_event):``,r=e.expires_at?`, expires ${zm(e.expires_at)}`:``,i=e.entitlement?.name?` → ${e.entitlement.name}`:``;t.push({type:`Grant`,label:e.label??null,summary:`${e.unit_amount??`?`} units on ${n}${r}${i}`})}for(let e of n(`consumptions`)){let n=e.entitlement?.name??`Entitlement`,r=e.trigger_event?zm(e.trigger_event):``;t.push({type:`Consumption`,label:e.label??null,summary:`${n} (${zm(e.type??``)}) on ${r}`})}for(let e of n(`service_fees`)){let n=e.type===`percentage`;t.push({type:`Service Fee`,label:e.label??null,summary:`${e.unit_amount??`?`}${n?`%`:` (Fixed)`}`})}for(let e of n(`payment_terms`)){let n=e.due_days==null?``:`Due in ${e.due_days} days`;t.push({type:`Payment Terms`,label:e.label??null,summary:n||`Custom`})}return t.length>0?t:null}function fh(e){let t=Gm(e),n=t.credit_note??t.creditNote??t,r=nh(n),i=n.customer,a=n.invoice;return{credit_note:{...r,line_items_url:n.line_items_url??null,credits_returned:Rh(n.credits_returned),custom_data:n.custom_data??null,customer_name:(i&&typeof i==`object`?i.name:null)??null,invoice_number:(a&&typeof a==`object`?a.invoice_number??a.name:null)??null}}}function ph(e,t){let n=Gm(e),r=Fh(n,[`products`,`data`,`results`]),i=Lh(n,[`total`,`count`,`total_count`])??r.length,a=Ih(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.name__ilike||void 0;return{products:r.map(mh),total:i,cursor:{next:o,prev:s},scope:c}}function mh(e){return!e||typeof e!=`object`?{id:``,name:null,sku:null,description:null,product_type:null,is_active:null,created_at:null}:{id:String(e.id||e.product_id||``),name:e.name??e.product_name??null,sku:e.sku??null,description:e.description??null,product_type:e.product_type??e.type??null,is_active:typeof e.is_active==`boolean`?e.is_active:null,created_at:e.created_at??null}}function hh(e,t){let n=Gm(e),r=Fh(n,[`plans`,`data`,`results`]),i=Lh(n,[`total`,`count`,`total_count`])??r.length,a=Ih(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.name__ilike||t.status)||void 0;return{plans:r.map(gh),total:i,cursor:{next:o,prev:s},scope:c}}function gh(e){return!e||typeof e!=`object`?{id:``,name:null,description:null,status:null,plan_version:null,created_at:null}:{id:String(e.id||e.plan_id||``),name:e.name??e.plan_name??null,description:e.description??null,status:e.status??e.state??null,plan_version:Rh(e.plan_version),created_at:e.created_at??null}}function _h(e,t){let n=Gm(e),r=Fh(n,[`entries`,`journal_entries`,`data`,`results`]),i=Lh(n,[`total`,`count`,`total_count`])??r.length,a=Ih(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.search_query||void 0;return{entries:r.map(vh),total:i,cursor:{next:o,prev:s},scope:c,default_currency:`USD`}}function vh(e){if(!e||typeof e!=`object`)return{id:``,posted_at:null,event:null,description:null,status_type:null,currency:null,total_debit:null,total_credit:null,line_count:null,created_at:null};let t=Array.isArray(e.journal_lines)?e.journal_lines:[],n=0,r=0;for(let e of t)Number.isFinite(e?.debits)&&(n+=e.debits),Number.isFinite(e?.credits)&&(r+=e.credits);return{id:String(e.id||e.journal_entry_id||``),posted_at:e.posted_at??null,event:e.event??null,description:e.description??null,status_type:e.status_type??null,currency:e.currency??e.currency_code??null,total_debit:t.length?n:null,total_credit:t.length?r:null,line_count:t.length||null,created_at:e.created_at??null}}function yh(e,t){let n=Gm(e),r=Fh(n,[`jobs`,`data`,`results`]),i=Lh(n,[`total`,`count`,`total_count`])??r.length,a=Ih(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.search||void 0,l={};for(let e of r){let t=e&&e.status||`unknown`;l[t]=(l[t]||0)+1}return{jobs:r.map(bh),total:i,cursor:{next:o,prev:s},scope:c,status_counts:l}}function bh(e){return!e||typeof e!=`object`?{id:``,name:null,description:null,job_type:null,resource:null,status:null,created_at:null}:{id:String(e.id||e.job_id||``),name:e.name??null,description:e.description??null,job_type:e.job_type??e.type??null,resource:e.resource??null,status:e.status??null,created_at:e.created_at??null}}function xh(e,t){let n=Gm(e),r=Fh(n,[`contacts`,`data`,`results`]),i=Lh(n,[`total`,`count`,`total_count`])??r.length,a=Ih(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.customer_id||void 0;return{contacts:r.map(Sh),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0}}function Sh(e){if(!e||typeof e!=`object`)return{id:``,name:null,email:null,customer_id:null,send_invoice:null,send_contract:null};let t=[e.first_name??``,e.last_name??``].filter(Boolean).join(` `).trim(),n=e.customer,r=typeof n==`string`?n:(n&&typeof n==`object`?n.id:null)??e.customer_id??null;return{id:String(e.id||e.contact_id||``),name:e.name??(t||null),email:e.email??e.primary_email??null,customer_id:r??null,send_invoice:typeof e.send_invoice==`boolean`?e.send_invoice:null,send_contract:typeof e.send_contract==`boolean`?e.send_contract:null}}function Ch(e,t){let n=Gm(e),r=Fh(n,[`raw_metrics`,`rawmetrics`,`rawMetrics`,`data`,`results`]),i=Lh(n,[`total`,`count`,`total_count`])??r.length,a=Ih(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search||t.name__ilike)||void 0;return{raw_metrics:r.map(wh),total:i,cursor:{next:o,prev:s},scope:c}}function wh(e){return!e||typeof e!=`object`?{id:``,name:null,api_slug:null,usage_upload_enabled:null,created_at:null}:{id:String(e.id||e.raw_metric_id||``),name:e.name??null,api_slug:e.api_slug??null,usage_upload_enabled:typeof e.usage_upload_enabled==`boolean`?e.usage_upload_enabled:null,created_at:e.created_at??null}}function Th(e,t){let n=Gm(e),r=Fh(n,[`aggregates`,`data`,`results`]),i=Lh(n,[`total`,`count`,`total_count`])??r.length,a=Ih(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.name__ilike||t.datasource)||void 0;return{aggregates:r.map(Eh),total:i,cursor:{next:o,prev:s},scope:c}}function Eh(e){return!e||typeof e!=`object`?{id:``,name:null,datasource:null,created_at:null}:{id:String(e.id||e.aggregate_id||``),name:e.name??null,datasource:e.datasource??e.data_source??e.raw_metric_name??null,created_at:e.created_at??null}}function Dh(e,t){let n=Fh(Gm(e),[`addresses`,`data`,`results`]);return{customer_id:t&&t.customerId?String(t.customerId):void 0,addresses:n.map(Oh),total:n.length}}function Oh(e){return!e||typeof e!=`object`?{id:``,label:null,line1:null,line2:null,city:null,state:null,zip_code:null,country:null,is_primary:null}:{id:String(e.id||``),label:e.label??e.name??e.address_type??null,line1:e.line1??e.address_line_1??null,line2:e.line2??e.address_line_2??null,line3:e.line3??null,city:e.city??null,state:e.state??null,zip_code:e.zipCode??e.zip_code??e.postal_code??null,country:e.country??e.country_code??null,validation_status:e.validation_status??null,is_primary:typeof e.is_primary==`boolean`?e.is_primary:typeof e.primary==`boolean`?e.primary:null}}function kh(e,t){let n=Fh(Gm(e),[`payment_methods`,`paymentMethods`,`data`,`results`]);return{customer_id:t&&t.customerId?String(t.customerId):void 0,payment_methods:n.map(Ah),total:n.length}}function Ah(e){if(!e||typeof e!=`object`)return{id:``,type:null,brand:null,last4:null,exp_month:null,exp_year:null,is_default:null,created_at:null};let t=e.card||e.details||{};return{id:String(e.id||``),type:e.type??e.payment_method_type??null,brand:t.brand??e.brand??null,last4:t.last4??e.last4??null,exp_month:Rh(t.exp_month??e.exp_month),exp_year:Rh(t.exp_year??e.exp_year),is_default:typeof e.is_default==`boolean`?e.is_default:typeof e.default==`boolean`?e.default:null,created_at:e.created_at??null,connector_name:e.connector_name??null,status:e.status??null}}function jh(e,t){let n=Gm(e),r=Fh(n,[`business_entities`,`businessEntities`,`entities`,`data`,`results`]),i=Lh(n,[`total`,`count`,`total_count`])??r.length,a=Ih(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null;return{entities:r.map(Mh),total:i,cursor:{next:o,prev:s}}}function Mh(e){return!e||typeof e!=`object`?{id:``,name:null,email:null,phone_number:null,country:null,is_default:null}:{id:String(e.id||e.business_entity_id||``),name:e.name??e.business_entity_name??null,email:e.email??null,phone_number:e.phone_number??null,country:(e.address&&e.address.country)??e.country??null,is_default:typeof e.is_default==`boolean`?e.is_default:null}}function Nh(e,t){let n=Gm(e),r=Fh(n,[`entitlements`,`data`,`results`]),i=Lh(n,[`total`,`count`,`total_count`])??r.length,a=Ih(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search||t.name__ilike)||void 0;return{entitlements:r.map(Ph),total:i,cursor:{next:o,prev:s},scope:c}}function Ph(e){return!e||typeof e!=`object`?{id:``,name:null,entitlement_type:null,units:null,is_active:null,product_name:null,created_at:null}:{id:String(e.id||e.entitlement_id||``),name:e.name??null,entitlement_type:e.entitlement_type??null,units:e.units??null,is_active:typeof e.is_active==`boolean`?e.is_active:null,product_name:(e.product&&(e.product.name??e.product.product_name))??null,created_at:e.created_at??null}}function Fh(e,t){if(Array.isArray(e))return e;for(let n of t)if(e&&Array.isArray(e[n]))return e[n];return[]}function Ih(e,t){for(let n of t)if(e&&e[n]&&typeof e[n]==`object`)return e[n];return null}function Lh(e,t){for(let n of t)if(e&&Number.isFinite(e[n]))return e[n];return null}function Rh(e){return Number.isFinite(e)?e:null}function zh(e,t){let n=Gm(e);return{html:n.html??(typeof n==`string`?n:``),invoice_id:t&&t.invoiceId?String(t.invoiceId):void 0}}function Bh(e){if(Bm.has(e))return{mode:`text-only`};let t=Vm[e];return t?{mode:`ui`,...t}:{mode:`unmapped`}}const Vh=a(s(import.meta.url)),Hh=[o(Vh,`..`,`..`,`..`,`dist`,`ui`),o(Vh,`ui`)];function Uh(e){for(let t of Hh){let i=o(t,`${e}.html`);if(n(i))return r(i,`utf8`)}return`<!doctype html><html><body style="font-family:sans-serif;padding:16px;">UI bundle missing: ${e}.html. Run <code>pnpm run build:ui</code>.</body></html>`}function Wh(){let e=new Set,t=t=>{if(t)try{e.add(new URL(t).origin)}catch{}};return t(process.env.ZENSKAR_MCP_PUBLIC_BASE_URL||process.env.MCP_PUBLIC_BASE_URL),t(process.env.ZENSKAR_API_BASE_URL),t(process.env.ZENSKAR_APP_BASE_URL),Array.from(e)}function Gh(){let e={prefersBorder:!0},t=Wh();return t.length>0&&(e.csp={connectDomains:t,resourceDomains:t}),e}function Kh(e){for(let t of Hm){let n=Um(t);e.registerResource(`zenskar-app`,n,{},async()=>({contents:[{uri:n,mimeType:`text/html;profile=mcp-app`,text:Uh(t),_meta:{"openai/widgetPrefersBorder":!0,ui:Gh()}}]}))}}const qh=[`claude-code`,`cline`,`roo-code`,`continue`,`codex`,`windsurf`,`zed`,`aider`,`copilot`,`gemini-cli`],Jh=[`claude-desktop`,`claude-ai`,`chatgpt`,`mcp-inspector`,`toon`,`cursor`];let Yh=null,Xh=null;function Zh(e){Yh=e?String(e).toLowerCase().trim():null}function Qh(e){Xh=e}function $h(){if(Yh==null&&Xh){let e=Xh();e&&Zh(e)}return Yh}function eg(e){let t=(e??Yh??``).toLowerCase().trim();return t?qh.some(e=>t.includes(e))?`coding-agent`:Jh.some(e=>t.includes(e))?`widget-host`:`default`:`default`}const tg={comma:`,`,tab:` `,pipe:`|`}.comma;function ng(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}function rg(e){return e===`true`||e===`false`||e===`null`}function ig(e){if(e===null)return null;if(typeof e==`object`&&e&&`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();if(t!==e)return ig(t)}if(typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e==`bigint`)return e>=-(2**53-1)&&e<=2**53-1?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(ig);if(e instanceof Set)return Array.from(e).map(ig);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),ig(t)]));if(lg(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&(t[n]=ig(e[n]));return t}return null}function ag(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function og(e){return Array.isArray(e)}function sg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cg(e){return Object.keys(e).length===0}function lg(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ug(e){return e.length===0||e.every(e=>ag(e))}function dg(e){return e.length===0||e.every(e=>og(e))}function fg(e){return e.length===0||e.every(e=>sg(e))}const pg=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,mg=/^0\d+$/;function hg(e){return/^[A-Z_][\w.]*$/i.test(e)}function gg(e){return/^[A-Z_]\w*$/i.test(e)}function _g(e,t=tg){return!(!e||e!==e.trim()||rg(e)||vg(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\n\r\t]/.test(e)||e.includes(t)||e.startsWith(`-`))}function vg(e){return pg.test(e)||mg.test(e)}function yg(e,t,n,r,i,a,o){if(r.keyFolding!==`safe`||!sg(t))return;let{segments:s,tail:c,leafValue:l}=bg(e,t,o??r.flattenDepth);if(s.length<2||!s.every(e=>gg(e)))return;let u=xg(s),d=a?`${a}.${u}`:u;if(!n.includes(u)&&!(i&&i.has(d)))return{foldedKey:u,remainder:c,leafValue:l,segmentCount:s.length}}function bg(e,t,n){let r=[e],i=t;for(;r.length<n&&sg(i);){let e=Object.keys(i);if(e.length!==1)break;let t=e[0],n=i[t];r.push(t),i=n}return!sg(i)||cg(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function xg(e){return e.join(`.`)}function Sg(e,t){return e===null?`null`:typeof e==`boolean`||typeof e==`number`?String(e):Cg(e,t)}function Cg(e,t=tg){return _g(e,t)?e:`"${ng(e)}"`}function wg(e){return hg(e)?e:`"${ng(e)}"`}function Tg(e,t=tg){return e.map(e=>Sg(e,t)).join(t)}function Eg(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;if(n!=null&&(a+=wg(n)),a+=`[${e}${i===tg?``:i}]`,r){let e=r.map(e=>wg(e));a+=`{${e.join(i)}}`}return a+=`:`,a}function*Dg(e,t,n){if(ag(e)){let n=Sg(e,t.delimiter);n!==``&&(yield n);return}og(e)?yield*Ag(void 0,e,n,t):sg(e)&&(yield*Og(e,n,t))}function*Og(e,t,n,r,i,a){let o=Object.keys(e);t===0&&!r&&(r=new Set(o.filter(e=>e.includes(`.`))));let s=a??n.flattenDepth;for(let[a,c]of Object.entries(e))yield*kg(a,c,t,n,o,r,i,s)}function*kg(e,t,n,r,i,a,o,s){let c=o?`${o}.${e}`:e,l=s??r.flattenDepth;if(r.keyFolding===`safe`&&i){let s=yg(e,t,i,r,a,o,l);if(s){let{foldedKey:e,remainder:t,leafValue:i,segmentCount:c}=s,u=wg(e);if(t===void 0){if(ag(i)){yield Bg(n,`${u}: ${Sg(i,r.delimiter)}`,r.indent);return}else if(og(i)){yield*Ag(e,i,n,r);return}else if(sg(i)&&cg(i)){yield Bg(n,`${u}:`,r.indent);return}}if(sg(t)){yield Bg(n,`${u}:`,r.indent);let i=l-c,s=o?`${o}.${e}`:e;yield*Og(t,n+1,r,a,s,i);return}}}let u=wg(e);ag(t)?yield Bg(n,`${u}: ${Sg(t,r.delimiter)}`,r.indent):og(t)?yield*Ag(e,t,n,r):sg(t)&&(yield Bg(n,`${u}:`,r.indent),cg(t)||(yield*Og(t,n+1,r,a,c,l)))}function*Ag(e,t,n,r){if(t.length===0){yield Bg(n,Eg(0,{key:e,delimiter:r.delimiter}),r.indent);return}if(ug(t)){yield Bg(n,Mg(t,r.delimiter,e),r.indent);return}if(dg(t)&&t.every(e=>ug(e))){yield*jg(e,t,n,r);return}if(fg(t)){let i=Pg(t);i?yield*Ng(e,t,i,n,r):yield*Lg(e,t,n,r);return}yield*Lg(e,t,n,r)}function*jg(e,t,n,r){yield Bg(n,Eg(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)if(ug(e)){let t=Mg(e,r.delimiter);yield Vg(n+1,t,r.indent)}}function Mg(e,t,n){let r=Eg(e.length,{key:n,delimiter:t}),i=Tg(e,t);return e.length===0?r:`${r} ${i}`}function*Ng(e,t,n,r,i){yield Bg(r,Eg(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*Ig(t,n,r+1,i)}function Pg(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&Fg(e,n))return n}function Fg(e,t){for(let n of e){if(Object.keys(n).length!==t.length)return!1;for(let e of t)if(!(e in n)||!ag(n[e]))return!1}return!0}function*Ig(e,t,n,r){for(let i of e)yield Bg(n,Tg(t.map(e=>i[e]),r.delimiter),r.indent)}function*Lg(e,t,n,r){yield Bg(n,Eg(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)yield*zg(e,n+1,r)}function*Rg(e,t,n){if(cg(e)){yield Bg(t,`-`,n.indent);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(og(a)&&fg(a)){let e=Pg(a);if(e){yield Vg(t,Eg(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indent),yield*Ig(a,e,t+2,n),o.length>0&&(yield*Og(Object.fromEntries(o),t+1,n));return}}let s=wg(i);if(ag(a))yield Vg(t,`${s}: ${Sg(a,n.delimiter)}`,n.indent);else if(og(a))if(a.length===0)yield Vg(t,`${s}${Eg(0,{delimiter:n.delimiter})}`,n.indent);else if(ug(a))yield Vg(t,`${s}${Mg(a,n.delimiter)}`,n.indent);else{yield Vg(t,`${s}${Eg(a.length,{delimiter:n.delimiter})}`,n.indent);for(let e of a)yield*zg(e,t+2,n)}else sg(a)&&(yield Vg(t,`${s}:`,n.indent),cg(a)||(yield*Og(a,t+2,n)));o.length>0&&(yield*Og(Object.fromEntries(o),t+1,n))}function*zg(e,t,n){if(ag(e))yield Vg(t,Sg(e,n.delimiter),n.indent);else if(og(e))if(ug(e))yield Vg(t,Mg(e,n.delimiter),n.indent);else{yield Vg(t,Eg(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*zg(r,t+1,n)}else sg(e)&&(yield*Rg(e,t,n))}function Bg(e,t,n){return` `.repeat(n*e)+t}function Vg(e,t,n){return Bg(e,`- `+t,n)}function Hg(e,t){let n=t(``,e,[]);return Ug(n===void 0?e:ig(n),t,[])}function Ug(e,t,n){return sg(e)?Wg(e,t,n):og(e)?Gg(e,t,n):e}function Wg(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=[...n,i],o=t(i,a,e);o!==void 0&&(r[i]=Ug(ig(o),t,e))}return r}function Gg(e,t,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i],o=[...n,i],s=t(String(i),a,o);if(s===void 0)continue;let c=ig(s);r.push(Ug(c,t,o))}return r}function Kg(e,t){return Array.from(qg(e,t)).join(`
|
|
79
|
-
`)}function
|
|
80
|
-
`+Yg(a)}],structuredContent:a}:n_(n)}function t_(e){if(!e||typeof e!=`object`)return 0;for(let t of[`customers`,`invoices`,`lines`,`payments`,`credit_notes`,`contracts`,`transactions`,`rows`,`items`,`data`,`addresses`,`payment_methods`,`products`,`plans`,`entries`,`jobs`,`contacts`,`raw_metrics`,`aggregates`,`entities`])if(Array.isArray(e[t]))return e[t].length;if(Number.isFinite(e.total))return e.total;for(let t of[`customer`,`invoice`,`contract`,`credit_note`])if(e[t]&&typeof e[t]==`object`)return 1;return+!!e.html}function n_(e){return{content:[{type:`text`,text:e}]}}const r_=s(import.meta.url),i_=i.dirname(r_),a_={logUsage:async()=>{}},o_=(e,t)=>({valid:!0,adjustedArgs:t,warnings:[],errors:[]}),s_=()=>({message:`Limits validation unavailable`,severity:`info`,suggestions:[]}),$={debug:(e,t)=>{if(process.env.MCP_DEBUG===`true`){let n=new Date().toISOString();console.error(`[${n}] [MCP-DEBUG] ${e}`,t?JSON.stringify(t,null,2):``)}},info:(e,t)=>{let n=new Date().toISOString();console.error(`[${n}] [MCP-INFO] ${e}`,t?JSON.stringify(t,null,2):``)},error:(e,t)=>{let n=new Date().toISOString();console.error(`[${n}] [MCP-ERROR] ${e}`,t?JSON.stringify(t,null,2):``)},warn:(e,t)=>{let n=new Date().toISOString();console.error(`[${n}] [MCP-WARN] ${e}`,t?JSON.stringify(t,null,2):``)}},c_=i.join(i_,`mcp-config.json`);let l_;try{l_=JSON.parse(t.readFileSync(c_,`utf8`))}catch(e){console.error(`Failed to load MCP config:`,e.message),console.error(`Please ensure mcp-config.json exists in the project root`),process.exit(1)}const u_=new pm({name:l_.server?.name||`zenskar-api-server`,version:`1.0.0`});Qh(()=>{let e=u_.server.getClientVersion();return e&&e.name?e.name:null});const d_=new Nm;function f_(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t={...e};return typeof t.timestamp==`string`&&(t.timestamp=p_(t.timestamp)),t.data&&typeof t.data==`object`&&!Array.isArray(t.data)&&(t.data={...t.data},[`DateTime64`,`DateTime`,`DateTime32`].forEach(e=>{typeof t.data[e]==`string`&&(t.data[e]=p_(t.data[e]))})),t}function p_(e){return typeof e==`string`?e.replace(`T`,` `).replace(`t`,` `).replace(/Z$/i,``).trim():e}function m_(e){if(typeof e!=`string`)return e;let t=e.trim();if(!t)return e;switch(t.toLowerCase()){case`boolean`:return`Bool`;case`string`:return`String`;case`int`:case`int64`:return`Int64`;case`float`:case`float64`:case`double`:return`Float64`;case`date`:case`date32`:return`Date32`;case`datetime`:case`datetime64`:return`DateTime64`;case`uuid`:return`UUID`;default:return t}}function h_(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t={...e};if(t.customer_id&&=m_(t.customer_id),t.timestamp&&=m_(t.timestamp),t.data&&typeof t.data==`object`&&!Array.isArray(t.data)){let e={};Object.entries(t.data).forEach(([t,n])=>{e[t]=m_(n)}),t.data=e}return t}function g_(e){return e?Array.isArray(e)?e:Array.isArray(e.results)?e.results:e.api_response===void 0?[]:g_(e.api_response):[]}function __(e){return!e||typeof e!=`string`?`Uncategorized`:e.trim()||`Uncategorized`}function v_(e){let t=Number(e);return Number.isFinite(t)?t/100:null}function y_(e,t){let n=__(t);return e===`getBalanceSheet`&&n===`Liabilities`?`Liabilities & Equity`:n}function b_(e,t){return(e===`getBalanceSheet`?{Assets:1,Liabilities:2,Equity:3}:{Income:1,Revenue:1,"Cost of Goods Sold":2,Expense:3,Expenses:3,"Other Income":4,"Other Expense":5,"Other Expenses":5})[t]||999}function x_(e){return`${e?.interval_start||`unknown_start`}__${e?.interval_end||`unknown_end`}`}function S_(e){return Object.values(e).sort((e,t)=>String(e.interval_start).localeCompare(String(t.interval_start)))}function C_(e,t,n){let r=new Map,i=new Map;t.forEach(t=>{let a=y_(e,t.account_category),o=x_(t),s=r.get(o)||{key:o,interval_start:t.interval_start||null,interval_end:t.interval_end||null};r.set(o,s),i.has(a)||i.set(a,{category:a,accounts:new Map,totals_by_period:{},total_balance:0,total_debits:0,total_credits:0});let c=i.get(a),l=t.account_id||`unknown_account`,u=n.get(l)||{};c.accounts.has(l)||c.accounts.set(l,{account_id:l,account_name:t.account_name||u.name||l,account_description:t.account_description||u.description||null,account_category:a,parent_path:t.account_parent_path||u.parent_path||null,balance_normality:t.balance_normality||u.balance_normality||null,periods:{},total_balance:0,total_debits:0,total_credits:0});let d=c.accounts.get(l);d.periods[o]={interval_start:t.interval_start||null,interval_end:t.interval_end||null,balance:t.balance??0,display_balance:v_(t.balance??0),debits:t.debits??0,display_debits:v_(t.debits??0),credits:t.credits??0,display_credits:v_(t.credits??0)},d.total_balance+=Number(t.balance||0),d.total_debits+=Number(t.debits||0),d.total_credits+=Number(t.credits||0);let f=c.totals_by_period[o]||{interval_start:t.interval_start||null,interval_end:t.interval_end||null,balance:0,debits:0,credits:0,display_balance:0,display_debits:0,display_credits:0};f.balance+=Number(t.balance||0),f.debits+=Number(t.debits||0),f.credits+=Number(t.credits||0),f.display_balance=v_(f.balance),f.display_debits=v_(f.debits),f.display_credits=v_(f.credits),c.totals_by_period[o]=f,c.total_balance+=Number(t.balance||0),c.total_debits+=Number(t.debits||0),c.total_credits+=Number(t.credits||0)});let a=Array.from(i.values()).sort((t,n)=>{let r=b_(e,t.category)-b_(e,n.category);return r===0?t.category.localeCompare(n.category):r}).map(e=>({category:e.category,accounts:Array.from(e.accounts.values()).sort((e,t)=>e.account_name.localeCompare(t.account_name)).map(e=>({...e,periods:S_(e.periods)})),totals_by_period:S_(e.totals_by_period),total_balance:e.total_balance,display_total_balance:v_(e.total_balance),total_debits:e.total_debits,display_total_debits:v_(e.total_debits),total_credits:e.total_credits,display_total_credits:v_(e.total_credits)}));return{report_type:e===`getBalanceSheet`?`balance_sheet`:`income_statement`,periods:Array.from(r.values()).sort((e,t)=>String(e.interval_start).localeCompare(String(t.interval_start))),sections:a}}function w_(e){if(!e)return``;let t=e.account_category||``;return t===`Liabilities`?`Liabilities & Equity`:t}function T_(e){let t=[...e].map(e=>({...e,account_category:w_(e)})).sort((e,t)=>{let n=w_(e).localeCompare(w_(t));return n===0?String(e.name||``).localeCompare(String(t.name||``)):n}),n=new Map;t.forEach(e=>{let t=w_(e)||`Uncategorized`;n.has(t)||n.set(t,[]),n.get(t).push(e)}),[`Assets`,`Liabilities & Equity`,`Equity`,`Income`,`Expenses`].forEach(e=>{n.has(e)||n.set(e,[])});let r=Array.from(n.entries()).sort((e,t)=>e[0].localeCompare(t[0])).map(([e,t])=>({id:e,name:e,description:e,account_category:e,is_parent:!0,parent_path:null,children:t.map(t=>({...t,parent_path:t.parent_path||e}))})),i=r.find(e=>e.name===`Liabilities & Equity`);return i&&(i.children.some(e=>e.name===`Equity`)||(i.children.push({id:`Equity`,name:`Equity`,description:`Equity`,account_category:`Liabilities & Equity`,balance_normality:`credit`,is_parent:!0,parent_path:`Liabilities & Equity`,custom_data:{default_account:!1},children:[]}),i.children.push({id:`Equity:Retained Earnings`,name:`Retained Earnings`,description:`Retained Earnings`,account_category:`Liabilities & Equity`,balance_normality:`credit`,is_parent:!1,parent_path:`Equity`,custom_data:{default_account:!1}}))),r}function E_(e){if(!e||!Array.isArray(e.results))return e;let t=e.results.reduce((e,t)=>{let n=t.status||`unknown`;return e[n]=(e[n]||0)+1,e},{});return{...e,summary:{total_count:e.total_count??e.results.length,returned_count:e.results.length,page_status_counts:t,has_more:!!e.next,note:e.next?`Showing ${e.results.length} jobs from the current page. Use the cursor to continue through the remaining jobs.`:`Showing ${e.results.length} jobs from the current page.`}}}function D_(e){if(!e||!Array.isArray(e.results))return e;let t=[...e.results].sort((e,t)=>{let n=__(e.account_category),r=__(t.account_category),i=n.localeCompare(r);return i===0?String(e.name||``).localeCompare(String(t.name||``)):i}),n=t.reduce((e,t)=>{let n=__(t.account_category);return e[n]=e[n]||[],e[n].push(t),e},{});return{...e,results:t,grouped_view:n}}async function O_(e,t){let n=await fetch(e,{method:`GET`,headers:t}),r=await n.text();if(!n.ok)throw Error(`Supplemental fetch failed: ${n.status} ${n.statusText}\nResponse: ${r}`);try{return JSON.parse(r)}catch{throw Error(`Supplemental fetch returned non-JSON response: ${r}`)}}async function k_(e,t,n){let r=e.rawMetricId,i=await O_(`${n}/rawmetric/${encodeURIComponent(r)}`,t);if(!i?.api_slug)throw Error(`Unable to resolve api_slug for raw metric ${r}`);let a={...t,apiversion:`20240301`},o={limit:e.limit??20,offset:e.offset??0,order_by:e.order_by??[{column:`timestamp`,type:`DESC`}],aggregate_operation:e.aggregate_operation??null,customer_mapping:null,end_date_mapping:null,start_date_mapping:null,table_name:`raw_metric_${i.api_slug}`,visual_query:{groups:[{filters:Array.isArray(e.filters)?e.filters:[],logic:`AND`}],logic:`AND`}},s=await fetch(`${n}/aggregate/visualquery/preview`,{method:`POST`,headers:a,body:JSON.stringify(o)}),c=await s.text();if(!s.ok)throw Error(`API request failed: ${s.status} ${s.statusText}\nResponse: ${c}`);try{return JSON.parse(c)}catch{return c}}async function A_(e,t,n,r){if(!t||!Array.isArray(t.results))return t;try{let i=g_(await O_(`${r}/accounting_new/chart_of_accounts`,n)),a=new Map(i.filter(e=>e&&e.id).map(e=>[e.id,e])),o=t.results.map(t=>{let n=a.get(t.account_id)||{};return{...t,account_name:n.name||t.account_id||null,account_description:n.description||null,account_category:y_(e,n.account_category),account_parent_path:n.parent_path||null,balance_normality:n.balance_normality||null,display_balance:v_(t.balance??0),display_debits:v_(t.debits??0),display_credits:v_(t.credits??0)}}),s=C_(e,o,a);if(e===`getBalanceSheet`){let e=new URLSearchParams;n.apiversion&&e.set(`apiversion`,n.apiversion);let t=await O_(`${r}/accounting_new/income_statement/v2`,n),i=Array.isArray(t?.results)?t.results:[],a={};i.forEach(e=>{let t=x_(e),n=a[t]||{interval_start:e.interval_start||null,interval_end:e.interval_end||null,balance:0,debits:0,credits:0};n.balance+=Number(e.balance||0),n.debits+=Number(e.debits||0),n.credits+=Number(e.credits||0),a[t]=n});let o=S_(Object.fromEntries(Object.entries(a).map(([e,t])=>[e,{...t,display_balance:v_(t.balance),display_debits:v_(t.debits),display_credits:v_(t.credits)}]))),c={account_id:`Equity:Retained Earnings`,account_name:`Retained Earnings (Derived)`,account_description:`Derived from the companion income statement for MCP presentation.`,account_category:`Liabilities & Equity`,parent_path:`Equity`,balance_normality:`credit`,periods:o,total_balance:o.reduce((e,t)=>e+Number(t.balance||0),0),display_total_balance:v_(o.reduce((e,t)=>e+Number(t.balance||0),0)),total_debits:o.reduce((e,t)=>e+Number(t.debits||0),0),display_total_debits:v_(o.reduce((e,t)=>e+Number(t.debits||0),0)),total_credits:o.reduce((e,t)=>e+Number(t.credits||0),0),display_total_credits:v_(o.reduce((e,t)=>e+Number(t.credits||0),0))},l=s.sections.find(e=>e.category===`Liabilities & Equity`);l||(l={category:`Liabilities & Equity`,accounts:[],totals_by_period:[],total_balance:0,display_total_balance:0,total_debits:0,display_total_debits:0,total_credits:0,display_total_credits:0},s.sections.push(l)),l.accounts.push(c)}return{...t,results:o,statement_view:s}}catch(n){return $.warn(`[${e}] Failed to enrich accounting report output; returning raw report`,{error:n.message}),t}}async function j_(e,t){let n=Date.now();if(e.name===`getCurrentDateTime`){let e=new Date;return{currentDate:e.toISOString().split(`T`)[0],currentDateTime:e.toISOString(),timestamp:e.getTime(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,humanReadable:e.toLocaleString()}}$.debug(`[${e.name}] Raw args received:`,{argKeys:Object.keys(t),argValues:JSON.stringify(t,null,2)});let r=t.__userContext,i={...t};delete i.__userContext,$.debug(`[${e.name}] User context received:`,r?{hasUserId:!!r.userId,hasAuthorization:!!r.authorization,hasOrganization:!!r.organization,authPrefix:r.authorization?r.authorization.substring(0,20)+`...`:`none`}:`NO USER CONTEXT`);let a=e.requestTemplate?.url||`/`,o=e.requestTemplate?.method||`GET`,s=a.startsWith(`http://`)||a.startsWith(`https://`);$.debug(`[${e.name}] Executing ${o} request with args:`,JSON.stringify(i,null,2)),r&&$.debug(`[${e.name}] Using user context:`,{hasApiKey:!!r.apiKey,hasOrganization:!!r.organization,userId:r.userId}),e.args&&e.args.forEach(e=>{e.position===`path`&&i[e.name]!==void 0&&(a=a.replace(`{${e.name}}`,encodeURIComponent(i[e.name])))});let c=new URLSearchParams;e.args&&e.args.forEach(e=>{e.position===`query`&&i[e.name]!==void 0&&i[e.name]!==null&&i[e.name]!==``&&(typeof i[e.name]==`boolean`?c.append(e.name,i[e.name].toString()):Array.isArray(i[e.name])?i[e.name].forEach(t=>{c.append(e.name,t)}):c.append(e.name,i[e.name]))}),Object.keys(i).forEach(t=>{if(!c.has(t)&&i[t]!==void 0&&i[t]!==null&&i[t]!==``){let n=e.args?.some(e=>e.position===`path`&&e.name===t),r=e.args?.some(e=>e.position===`body`&&e.name===t);!n&&!r&&(typeof i[t]==`boolean`?c.append(t,i[t].toString()):Array.isArray(i[t])?i[t].forEach(e=>{c.append(t,e)}):c.append(t,i[t]))}}),c.toString()&&(a+=`?`+c.toString());let l=null;if(o!==`GET`&&o!==`DELETE`&&e.args){let t=e=>{if(typeof e==`number`)return Number.isFinite(e)?Math.floor(e):e;if(typeof e==`string`){let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):e}return e},n={};if(e.args.forEach(r=>{if(r.position===`body`&&i[r.name]!==void 0){if(r.type===`datetime`){n[r.name]=t(i[r.name]);return}if(e.name===`ingestRawMetricEvent`&&r.name===`event`){let e=f_(i[r.name]);e&&typeof e==`object`&&!Array.isArray(e)?Object.entries(e).forEach(([e,t])=>{t!==void 0&&(n[e]=t)}):n[r.name]=e}else n[r.name]=i[r.name]}}),e.name===`createCustomer`||e.name===`updateCustomer`){let t=(t,r)=>{let i={[`${t}line1`]:`line1`,[`${t}line2`]:`line2`,[`${t}line3`]:`line3`,[`${t}city`]:`city`,[`${t}state`]:`state`,[`${t}zipCode`]:`zipCode`,[`${t}country`]:`country`,[`${t}country_code`]:`country_code`},a={},o=!1;Object.entries(i).forEach(([e,t])=>{n[e]!==void 0&&(a[t]=n[e],delete n[e],o=!0)}),o&&(n[r]=a,$.debug(`[${e.name}] Transformed flat ${t}* fields into ${r} object`))};t(`address_`,`address`),t(`ship_to_`,`ship_to_address`)}if(e.name===`createBusinessEntity`&&((t,r)=>{let i={[`${t}line1`]:`line1`,[`${t}line2`]:`line2`,[`${t}line3`]:`line3`,[`${t}city`]:`city`,[`${t}state`]:`state`,[`${t}zipCode`]:`zipCode`,[`${t}country`]:`country`},a={},o=!1;Object.entries(i).forEach(([e,t])=>{n[e]!==void 0&&(a[t]=n[e],delete n[e],o=!0)}),o&&(n[r]=a,$.debug(`[${e.name}] Transformed flat ${t}* fields into ${r} object`))})(`address_`,`address`),e.name===`getInvoicePreviewHtml`&&!i.orgId){let e=r?.organization||process.env.ZENSKAR_ORGANIZATION;e&&(i.orgId=e)}if(e.name===`extractContractFromRaw`&&!n.organization_id){let t=r?.organization||process.env.ZENSKAR_ORGANIZATION;t&&(n.organization_id=t,$.debug(`[${e.name}] Auto-populated organization_id: ${t}`))}e.name===`createRawMetric`&&(n.connector||=i.connector||`push_to_zenskar`,n.api_type||=i.api_type||`PUSH`,n.dataschema||={customer_id:`string`,timestamp:`timestamp`,data:{usage_amount:`decimal`,feature_id:`string`}},n.dataschema&&=h_(n.dataschema),n.column_order=[`timestamp`]),Object.keys(n).length>0?l=JSON.stringify(n):(o===`PATCH`||o===`POST`||o===`PUT`)&&(l=`{}`)}let u={"Content-Type":`application/json`,"User-Agent":`Zenskar-MCP-Server/1.0.0`,apiversion:`20230501`},d=r?.organization||process.env.ZENSKAR_ORGANIZATION,f=r?.authorization||r?.headers?.authorization||r?.headers?.Authorization||process.env.ZENSKAR_AUTH_TOKEN,p=r?.apiKey||r?.headers?.[`x-api-key`]||process.env.ZENSKAR_API_KEY||process.env.ZENSKAR_AUTH_TOKEN;if(d)u.organisation=d;else throw $.error(`[${e.name}] SECURITY ERROR: No organization ID provided`),Error(`Organization ID is required for API access. Set ZENSKAR_ORGANIZATION env var or provide in user context.`);if(f&&f.startsWith(`eyJ`))u.Authorization=f.startsWith(`Bearer `)?f:`Bearer ${f}`;else if(p)u[`x-api-key`]=p;else throw $.error(`[${e.name}] SECURITY ERROR: No authorization provided`),Error(`Authorization is required. Set ZENSKAR_AUTH_TOKEN (JWT) or ZENSKAR_API_KEY env var.`);if(r?.headers){let e=new Set(Object.keys(u).map(e=>e.toLowerCase())),t=new Set([`__proto__`,`prototype`,`constructor`]);Object.keys(r.headers).forEach(n=>{t.has(n)||Object.prototype.hasOwnProperty.call(r.headers,n)&&r.headers[n]&&!e.has(n.toLowerCase())&&(u[n]=r.headers[n])})}$.debug(`[${e.name}] Using headers:`,{hasOrganization:!!u.organisation,hasAuthorization:!!u.Authorization,hasApiKey:!!u[`x-api-key`],source:r?.organization?`userContext`:`env`}),e.requestTemplate?.headers&&(Array.isArray(e.requestTemplate.headers)?e.requestTemplate.headers.forEach(e=>{u[e.key]=e.value}):Object.keys(e.requestTemplate.headers).forEach(t=>{u[t]=e.requestTemplate.headers[t]}));let m;if(s)m=a,$.debug(`[${e.name}] Using absolute URL: ${m}`);else{let t=process.env.ZENSKAR_API_BASE_URL||`https://api.zenskar.com`;m=t+a,$.debug(`[${e.name}] Using relative URL with base: ${t} + ${a} = ${m}`)}$.debug(`[${e.name}] Making ${o} request to: ${m}`),$.info(`[${e.name}] MULTI-TENANT SECURITY CHECK - Headers being sent:`,{organization:u.organisation||`MISSING`,hasAuth:!!u.Authorization,authPrefix:u.Authorization?u.Authorization.substring(0,30)+`...`:`NONE`,allHeaders:JSON.stringify(u,null,2)});try{if(e.name===`getRawMetricLogs`){let t=await k_(i,u,process.env.ZENSKAR_API_BASE_URL||`https://api.zenskar.com`);return $.debug(`[${e.name}] Successfully processed frontend-style usage-event logs`),t}let t=await fetch(m,{method:o,headers:u,body:l}),r=await t.text(),a=Date.now()-n;if($.info(`[${e.name}] Response received in ${a}ms - Status: ${t.status}, Size: ${r.length} chars`),$.info(`[${e.name}] Raw response body:`,r),!t.ok){$.error(`[${e.name}] API Error Response:`,r);let n=`API request failed: ${t.status} ${t.statusText}\nResponse: ${r}`;throw Error(n)}let s;try{s=JSON.parse(r)}catch{$.debug(`[${e.name}] Failed to parse JSON response, returning as text`),s=r}if(e.name===`getInvoicePreviewHtml`)if(typeof s==`string`)try{let e=Buffer.from(s,`base64`).toString(`utf8`);s=e.includes(`<`)?{html:e}:{html:s}}catch{s={html:s}}else s={html:``};if(e.name===`getBalanceSheet`||e.name===`getIncomeStatement`){let t=process.env.ZENSKAR_API_BASE_URL||`https://api.zenskar.com`;s=await A_(e.name,s,u,t)}return e.name===`listJobs`&&(s=E_(s)),e.name===`listAccounts`&&(s=D_(s)),e.name===`getChartOfAccounts`&&Array.isArray(s)&&(s={raw_accounts:s,chart_view:T_(s)}),e.responseTemplate?.prependBody&&(s={template_info:e.responseTemplate.prependBody,api_response:s}),$.debug(`[${e.name}] Successfully processed response`),s}catch(t){throw $.error(`[${e.name}] Network error:`,t),Error(`Network error: ${t.message}`)}}async function M_(e,t){let{listArg:n}=e.bulkOver,r=[];for(let i of t[n])try{r.push({id:i,status:`succeeded`,response:await j_(e,{...t,[n]:i})})}catch(t){$.error(`[${e.name}] ${i} failed:`,t),r.push({id:i,status:`failed`,error:t.message})}let i=r.filter(e=>e.status===`failed`);return $.info(`[${e.name}] bulk complete: ${r.length-i.length}/${r.length} succeeded`),{summary:{requested:r.length,succeeded:r.length-i.length,failed:i.length},results:r}}const N_=300*1e3,P_=process.env.APPROVAL_HMAC_SECRET,F_=!!P_,I_=new Map,L_=new Map;function R_(e){if(e==null)return e;if(typeof structuredClone==`function`)try{return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}function z_(e){let t=e?R_(e):{};return delete t.__userContext,t}function B_(t){return e.createHmac(`sha256`,P_).update(t).digest(`base64url`)}function V_(t,n){let r=Date.now(),i=r+N_,a=z_(n);if(F_){let n={toolName:t,args:a,issuedAt:r,expiresAt:i,nonce:e.randomBytes(12).toString(`base64url`)},o=Buffer.from(JSON.stringify(n),`utf8`).toString(`base64url`);return`v1.${o}.${B_(o)}`}let o=jm();return I_.set(o,{toolName:t,issuedAt:r,expiresAt:i,args:a}),o}function H_(t,n){if(!t||typeof t!=`string`)return null;if(F_){let r=t.split(`.`);if(r.length!==3)return null;let[i,a,o]=r;if(i!==`v1`)return null;let s=B_(a),c=Buffer.from(o,`base64url`),l=Buffer.from(s,`base64url`);if(c.length!==l.length||!e.timingSafeEqual(c,l))return null;let u;try{u=JSON.parse(Buffer.from(a,`base64url`).toString(`utf8`))}catch{return null}return u.toolName!==n||typeof u.expiresAt!=`number`||u.expiresAt<Date.now()||L_.has(t)?null:(L_.set(t,u.expiresAt),u)}let r=I_.get(t);return!r||(I_.delete(t),r.toolName!==n)||r.expiresAt<Date.now()?null:r}setInterval(()=>{let e=Date.now();for(let[t,n]of I_)n.expiresAt<e&&I_.delete(t);for(let[t,n]of L_)n<e&&L_.delete(t)},6e4).unref();function U_(e,t){return(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0)(e.modifiedArguments)?{args:e.modifiedArguments,source:`modifiedArguments`}:{args:t.args,source:`tokenSnapshot`}}function W_(e,t){let n={...t};for(let t of e.args||[]){if(t.type!==`array`)continue;let e=n[t.name];typeof e==`string`&&(n[t.name]=e.split(`,`).map(e=>e.trim()).filter(e=>e!==``))}return n}function G_(e,t){let n=e.__userContext;Object.keys(e).forEach(t=>{t!==`__userContext`&&delete e[t]}),Object.assign(e,t),e.__userContext=n}function K_(e,t){if(!e.needsApproval)return!1;let n=t.__userContext,r=n&&n.approval;if(r&&r.approved===!0){let n=H_(r.token,e.name);if(n){let{args:i,source:a}=U_(r,n);return $.info(`[${e.name}] Approval token verified; arg source=${a}`),G_(t,a===`modifiedArguments`?W_(e,i):i),$.info(`[${e.name}] Restored arguments for approved execution:`,Object.keys(i)),!1}$.warn(`[${e.name}] Approval received without valid token (got: ${r.token?`expired/mismatched`:`missing`}); requiring re-approval`)}return typeof e.needsApproval==`function`?e.needsApproval(t):e.needsApproval===!0}function q_(e,t){t.__userContext;let n={...t};delete n.__userContext;let r=V_(e.name,t);return{type:`approval_required`,toolName:e.name,toolDescription:e.description,arguments:n,approvalToken:r,approvalTokenExpiresInSeconds:Math.floor(N_/1e3),approvalConfig:e.approvalConfig||{title:`Approve ${e.name}`,description:`This action requires your approval: ${e.description}`,warningText:`Please review the parameters carefully before proceeding.`,confirmText:`Approve`,cancelText:`Cancel`},fields:(e.args||[]).map(t=>({name:t.name,label:t.description||t.name,type:J_(t.type),required:t.required||!1,value:n[t.name],sensitive:e.approvalConfig?.sensitiveFields?.includes(t.name)||!1}))}}function J_(e){switch(e){case`string`:return`text`;case`integer`:case`number`:return`number`;case`boolean`:return`checkbox`;case`array`:return`textarea`;default:return`text`}}Kh(u_),l_.tools&&l_.tools.length>0&&l_.tools.forEach(e=>{$.info(`Registering tool: ${e.name}`);let t=Fm(e.args||[]),n=Bh(e.name),r=n.mode===`ui`?(()=>{let e=Um(n.shape);return{"openai/outputTemplate":e,"ui/resourceUri":e,ui:{resourceUri:e}}})():void 0;u_.registerTool(e.name,{title:e.name,description:e.description,inputSchema:t,...r?{_meta:r}:{}},async t=>{let n=Date.now(),r=`success`,i=null,a=0,o=0,s=null,c=null;try{$.debug(`[${e.name}] Tool execution started`),$.info(`[${e.name}] Raw args received:`,{argKeys:Object.keys(t),hasUserContextInArgs:!!t.__userContext,userContextInArgs:t.__userContext,approvedInArgs:t.__userContext?.approved});let l=Rm(e,t);if(!l.valid){$.error(`[${e.name}] Tool execution blocked due to invalid arguments (pre-approval):`,l.errors),r=`blocked`,i=`invalid_args: ${l.errors.join(`; `)}`;let t={type:`invalid_arguments`,toolName:e.name,errors:l.errors};return{content:[{type:`text`,text:JSON.stringify(t,null,2)},{type:`text`,text:`ACTION_NOT_EXECUTED — INVALID_ARGUMENTS\n\nTool '${e.name}' was NOT executed because the supplied arguments are invalid or incomplete:\n\n`+l.errors.map((e,t)=>`${t+1}. ${e}`).join(`
|
|
78
|
+
[Response truncated due to length]`),t}catch(e){return console.error(`Response processing error:`,e),`Error processing response`}}};function Pm(e){if(!e||typeof e!=`object`||Array.isArray(e))return nc();let t=e.oneOf||e.anyOf;if(Array.isArray(t)&&t.length>0){let e=t.map(Pm);return e.length===1?e[0]:U(e)}if(Array.isArray(e.enum)&&e.enum.length>0){let t=e.enum.filter(e=>typeof e==`string`);if(t.length===e.enum.length&&t.length>0)return gc(t)}let n,r=Array.isArray(e.type)?e.type[0]:e.type;if(r===`integer`||r===`number`)n=r===`integer`?z().int():z(),typeof e.minimum==`number`&&(n=n.min(e.minimum)),typeof e.maximum==`number`&&(n=n.max(e.maximum));else if(r===`boolean`)n=Qs();else if(r===`array`)n=V(Pm(e.items)),typeof e.minItems==`number`&&(n=n.min(e.minItems)),typeof e.maxItems==`number`&&(n=n.max(e.maxItems));else if(r===`object`){let t=new Set(Array.isArray(e.required)?e.required:[]),r=e.properties||{},i={};Object.entries(r).forEach(([e,n])=>{let r=Pm(n);t.has(e)||(r=r.optional()),i[e]=r}),n=e.additionalProperties===!1?H(i):H(i).passthrough()}else n=L();return e.description&&(n=n.describe(e.description)),n}function Fm(e){let t={};return e.forEach(e=>{let n;n=e.schema?Pm(e.schema):e.type===`integer`||e.type===`number`?z():e.type===`boolean`?Qs():e.type===`object`?W(nc()):e.type===`array`?V(nc()):e.type===`datetime`?U([L(),z()]):L(),e.default!==void 0&&(n=n.default(e.default)),e.required||(n=n.optional()),e.description&&(n=n.describe(e.description)),t[e.name]=n}),t.__userContext=H({userId:L().optional(),authorization:L().optional(),organization:L().optional(),apiKey:L().optional(),headers:H({}).optional(),approval:H({approved:Qs(),token:L().optional(),modifiedArguments:W(nc()).optional(),originalArguments:W(nc()).optional(),toolName:L().optional()}).optional()}).optional().describe(`Internal user context for multi-tenant authentication and approval workflow`),t}function Im(e){let t=String(e).toLowerCase().trim();return t.startsWith(`array(`)?`array`:/bool/.test(t)?`boolean`:/int|float|double|decimal|number/.test(t)?`number`:`string`}function Lm(e){let t=process.env.ZENSKAR_API_BASE_URL||`https://api.zenskar.com`,n=e?.organization||process.env.ZENSKAR_ORGANIZATION,r=e?.authorization||e?.headers?.authorization||e?.headers?.Authorization||process.env.ZENSKAR_AUTH_TOKEN,i=e?.apiKey||e?.headers?.[`x-api-key`]||process.env.ZENSKAR_API_KEY||process.env.ZENSKAR_AUTH_TOKEN;if(!n)throw Error(`Organization ID is required for API access.`);let a={"Content-Type":`application/json`,"User-Agent":`Zenskar-MCP-Server/1.0.0`,apiversion:`20230501`,organisation:n};if(r&&r.startsWith(`eyJ`))a.Authorization=r.startsWith(`Bearer `)?r:`Bearer ${r}`;else if(i)a[`x-api-key`]=i;else throw Error(`Authorization is required for API access.`);if(e?.headers){let t=new Set(Object.keys(a).map(e=>e.toLowerCase())),n=new Set([`__proto__`,`prototype`,`constructor`]);Object.keys(e.headers).forEach(r=>{n.has(r)||Object.prototype.hasOwnProperty.call(e.headers,r)&&e.headers[r]&&!t.has(r.toLowerCase())&&(a[r]=e.headers[r])})}return{baseUrl:t,headers:a}}async function Rm(e,t){try{let{baseUrl:n,headers:r}=Lm(t),i=await fetch(`${n}/rawmetric/slug/${encodeURIComponent(e)}`,{headers:r,signal:AbortSignal.timeout(8e3)});if(i.status===404)return{notFound:!0};if(!i.ok)return{schema:null};let a=await i.json();return typeof a!=`object`||!a?{notFound:!0}:{schema:a.dataschema||null}}catch{return{schema:null}}}const zm=e=>e==null||e===``;function Bm(e){let t=[];return e.forEach((e,n)=>{if(typeof e!=`object`||!e){t.push(`Event ${n}: must be an object.`);return}zm(e.customer_id)&&t.push(`Event ${n}: missing required field 'customer_id'.`),zm(e.timestamp)&&t.push(`Event ${n}: missing required field 'timestamp'.`),(e.data===void 0||typeof e.data!=`object`||e.data===null||Array.isArray(e.data))&&t.push(`Event ${n}: missing required field 'data' (must be an object; an empty object is fine).`)}),t}function Vm(e,t){let n=t.data||{},r=[];return e.forEach((e,t)=>{if(typeof e!=`object`||!e)return;let i=e.data;i===void 0||typeof i!=`object`||!i||Array.isArray(i)||Object.keys(i).forEach(e=>{if(!Object.prototype.hasOwnProperty.call(n,e)){r.push(`Event ${t}: unknown field 'data.${e}' — not part of this raw metric's schema. Valid fields: ${Object.keys(n).join(`, `)||`(none)`}.`);return}if(i[e]===null)return;let a=n[e],o=Im(a),s=Array.isArray(i[e])?`array`:typeof i[e];s!==o&&r.push(`Event ${t}: 'data.${e}' expected ${a} (${o}), got ${s}.`)})}),r}function Hm(e){if(e.length>15){let t=e.slice(0,15);return t.push(`... and ${e.length-15} more schema errors.`),t}return e}const Um={generateInvoice(e){let t=[],n=e=>{if(typeof e==`number`)return Number.isInteger(e)?e:null;if(typeof e==`string`){let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):null}return null},r=n(e.from_date),i=n(e.to_date);return r===null&&t.push(`'from_date' must be either an integer UNIX timestamp (seconds) or an ISO-8601 datetime string. Copy from getContractBillingCycles.start_date.`),i===null&&t.push(`'to_date' must be either an integer UNIX timestamp (seconds) or an ISO-8601 datetime string. Copy from getContractBillingCycles.end_date.`),r!==null&&i!==null&&i<=r&&t.push(`'to_date' must be strictly greater than 'from_date'.`),n(e.bill_for_date)===null&&t.push(`'bill_for_date' is REQUIRED (UNIX seconds or ISO-8601 string). Without it the API returns a $0 invoice. Copy from getContractBillingCycles.bill_for_date — do NOT compute.`),(!Number.isInteger(e.billing_cycle_start_day)||e.billing_cycle_start_day<1||e.billing_cycle_start_day>31)&&t.push(`'billing_cycle_start_day' is REQUIRED and must be an integer 1-31. Copy from getContractBillingCycles.billing_cycle_start_day.`),t},pauseContract(e){let t=[];return e.start_date||t.push(`'start_date' is required (ISO 8601).`),e.unpause_extension_policy||t.push(`'unpause_extension_policy' is required: 'extend' or 'overlap'.`),t},updateContract(e){let t=[],n=Array.isArray(e.phases)?e.phases:null,r=e=>{if(e==null||e===``)return null;let t=Date.parse(e);return Number.isFinite(t)?t:NaN},i=r(e.end_date),a=Number.isFinite(i),o=e=>{let t=r(e&&e.end_date);return Number.isFinite(t)?t:null},s=[];if(Number.isNaN(i)&&s.push(`contract end_date '${e.end_date}'`),n&&n.forEach((e,t)=>{Number.isNaN(r(e&&e.end_date))&&s.push(`phase ${t+1} end_date '${e.end_date}'`)}),s.length>0&&t.push(`Unparseable date(s): ${s.join(`, `)}. Use ISO 8601, e.g. 2026-08-24T00:00:00. Day-first formats such as 24/08/2026 are not accepted, and a date that cannot be parsed is not treated as an absent one.`),a&&i<Date.now()&&t.push(`'end_date' is in the past, which expires the contract. Call expireContract instead — it sets the same end_date and also prunes future phases, trims overlapping phases and caps product dates.`),a&&n){let e=n.filter(e=>{let t=o(e);return t!==null&&t>i});e.length>0&&t.push(`${e.length} phase(s) end after the contract-level 'end_date'. The API rejects this. To shorten contracts call expireContract, which trims phases automatically and accepts several contract ids in one call; otherwise set each phase end_date to at most the contract 'end_date'.`)}return!a&&n&&n.length>0&&n.every(e=>o(e)!==null)&&t.push(`Every phase has an 'end_date' but no contract-level 'end_date' was supplied. Contract status is derived from the contract-level end_date, not from phase dates, so this would leave the contract ACTIVE with no current phase. To expire the contract, call expireContract — it also trims phases and product dates, and accepts several contract ids in one call. To update without expiring, keep a phase open or set 'end_date' explicitly.`),t},expireContract(e){return e.expiry_date===void 0||e.expiry_date===null||Number.isFinite(Date.parse(e.expiry_date))?[]:[`Unparseable 'expiry_date' '${e.expiry_date}'. Use ISO 8601, e.g. 2026-08-24. Day-first formats such as 24/08/2026 are not accepted.`]},async ingestRawMetricEventsBulk(e){let t=e.events;if(!Array.isArray(t))return[`'events' is required and must be an array of Usage Event payloads.`];let n=[];if(t.length===0&&n.push(`'events' is empty — nothing to ingest.`),t.length>500&&n.push(`'events' has ${t.length} entries. The limit is 500 per call. ingestRawMetricEventsBulk sends all events in a single request. Split the events into multiple calls of up to 500 events each.`),n.length>0||!e.rawMetricSlug)return n;n.push(...Bm(t));let{notFound:r,schema:i}=await Rm(e.rawMetricSlug,e.__userContext);return r?(n.push(`Raw metric slug '${e.rawMetricSlug}' was not found — check it via listRawMetrics or getRawMetricBySlug before ingesting.`),Hm(n)):(i&&n.push(...Vm(t,i)),Hm(n))}};function Wm(e,t){let{listArg:n,maxBatch:r}=e.bulkOver,i=t[n];if(!Array.isArray(i))return[];let a=[];i.length===0&&a.push(`'${n}' is empty — nothing to do.`),r!==void 0&&i.length>r&&a.push(`'${n}' has ${i.length} entries. The limit is ${r}. ${e.name} runs one item at a time. A batch must be small enough to review in one approval. It must also complete before the client timeout. Send fewer ids.`);let o=i.filter(e=>typeof e!=`string`||e.trim()===``);o.length>0&&a.push(`'${n}' has ${o.length} empty or non-string entries.`);let s=[...new Set(i.filter((e,t)=>i.indexOf(e)!==t))];return s.length>0&&a.push(`'${n}' repeats ${s.join(`, `)}.`),a}async function Gm(e,t){let n=Um[e.name],r=n?await n(t):[];return e.bulkOver&&r.push(...Wm(e,t)),{valid:r.length===0,errors:r}}function Km(e){return!e||typeof e!=`string`?``:e.replace(/[_-]+/g,` `).replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/\b\w/g,e=>e.toUpperCase()).trim()}const qm=new Set([`getInvoiceSummary`,`getCustomerBalance`,`getPaymentStatus`]),Jm={listCustomers:{shape:`customer-table`,noun:`customer`,toPayload:Zm,threshold:0},listInvoices:{shape:`invoice-table`,noun:`invoice`,toPayload:$m,threshold:0},getInvoiceLineItems:{shape:`invoice-line-items`,noun:`line item`,toPayload:th,threshold:0},listAllPayments:{shape:`payment-table`,noun:`payment`,toPayload:oh,threshold:0},listCreditNotes:{shape:`credit-note-table`,noun:`credit note`,toPayload:ch,threshold:0},listContracts:{shape:`contract-table`,noun:`contract`,toPayload:uh,threshold:0},getCustomerById:{shape:`customer-detail`,noun:`customer`,toPayload:fh,threshold:0},getInvoiceById:{shape:`invoice-detail`,noun:`invoice`,toPayload:ph,threshold:0},getContractById:{shape:`contract-detail`,noun:`contract`,toPayload:mh,threshold:0},getCreditNoteById:{shape:`credit-note-detail`,noun:`credit note`,toPayload:yh,threshold:0},listProducts:{shape:`product-table`,noun:`product`,toPayload:bh,threshold:0},listPlans:{shape:`plan-table`,noun:`plan`,toPayload:Sh,threshold:0},listJournalEntries:{shape:`journal-table`,noun:`journal entry`,toPayload:wh,threshold:0},listJobs:{shape:`job-table`,noun:`job`,toPayload:Eh,threshold:0},listContacts:{shape:`contact-table`,noun:`contact`,toPayload:Oh,threshold:0},listRawMetrics:{shape:`raw-metric-table`,noun:`raw metric`,toPayload:Ah,threshold:0},listAggregates:{shape:`aggregate-table`,noun:`aggregate`,toPayload:Mh,threshold:0},listCustomerAddresses:{shape:`address-list`,noun:`address`,toPayload:Ph,threshold:0},listPaymentMethods:{shape:`payment-method-list`,noun:`payment method`,toPayload:Ih,threshold:0},listBusinessEntities:{shape:`entity-table`,noun:`business entity`,toPayload:Rh,threshold:0},listEntitlements:{shape:`entitlement-table`,noun:`entitlement`,toPayload:Bh,threshold:0},getInvoicePreviewHtml:{shape:`invoice-preview`,noun:`invoice preview`,toPayload:Kh,threshold:0}},Ym=Object.freeze([`app`]);function Xm(e){return`ui://zenskar/app.html`}function Zm(e,t){let n=Qm(e),r=Hh(n,[`customers`,`data`,`results`]),i=Wh(n,[`total`,`count`,`total_count`])??r.length,a=Uh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search_name_external_id||t.search)||void 0;return{customers:r.map(ah),total:i,cursor:{next:o,prev:s},scope:c}}function Qm(e){return e&&typeof e==`object`&&e.api_response&&typeof e.api_response==`object`?e.api_response:e||{}}function $m(e,t){let n=Qm(e),r=Hh(n,[`invoices`,`data`,`results`]),i=Wh(n,[`total`,`count`,`total_count`])??r.length,a=Uh(n,[`cursor`,`pagination`])||{},o=a.next??n.next??null,s=a.prev??n.previous??null;return{invoices:r.map(eh),total:i,cursor:{next:o,prev:s},scope:t&&(t.customer__customer_name__ilike||t.invoice_number__like||t.status)||void 0,default_currency:`USD`}}function eh(e){if(!e||typeof e!=`object`)return{id:``,invoice_number:null,customer_id:null,customer_name:null,status:null,invoice_total:null,amount_due:null,due_date:null,invoice_period_begin:null,invoice_period_end:null,external_id:null,created_at:null,payment_url:null};let t=e.invoice_period||{},n=e.customer&&typeof e.customer==`object`?e.customer:null;return{id:String(e.id||e.invoice_id||``),invoice_number:e.invoice_number??null,customer_id:n?.id??e.customer_id??null,customer_name:n?.customer_name??n?.name??null,status:e.status??null,invoice_total:Gh(e.net_invoice_total??e.invoice_total),amount_due:Gh(e.amount_due),due_date:e.due_date??e.promise_due_date??null,invoice_period_begin:t.begin_date??e.period_begin_date??null,invoice_period_end:t.end_date_exclusive??e.period_end_date??null,external_id:e.external_id??null,created_at:e.created_at??null,payment_url:e.payment_url??null}}function th(e,t){let n=Qm(e),r=Array.isArray(n.lines)?n.lines:Array.isArray(n)?n:[],i=Gh(n.total),a=nh(r)||`USD`;return{invoice_id:t&&t.invoiceId?String(t.invoiceId):void 0,total:i,currency:a,lines:r.map(rh)}}function nh(e){for(let t of e){if(t&&t.subtotal&&t.subtotal.unit)return t.subtotal.unit;if(t&&t.features&&t.features[0]&&t.features[0].currency)return t.features[0].currency}return null}function rh(e){return!e||typeof e!=`object`?{name:``,description:null,pricing_model:null,subtotal:{value:null,unit:null},quantity:{value:null,unit:null},price:null,service_start_date:null,service_end_date:null,is_billed:null}:{name:e.name??e.description??``,description:e.description??null,pricing_model:e.pricing_model??null,subtotal:ih(e.subtotal),quantity:ih(e.quantity),price:e.price?ih(e.price):null,service_start_date:e.service_start_date??e.billing_period_start??null,service_end_date:e.service_end_date??e.billing_period_end??null,is_billed:typeof e.is_billed==`boolean`?e.is_billed:null,line_item_type:e.line_item_type??null,is_adjustment:typeof e.is_adjustment==`boolean`?e.is_adjustment:null,adjustment_type:e.adjustment_type??null}}function ih(e){return e?{value:Gh(e.value),unit:e.unit??null,display:e.display??null}:{value:null,unit:null,display:null}}function ah(e){return!e||typeof e!=`object`?{id:``,name:null,external_id:null,email:null}:{id:String(e.id||e.customer_id||``),name:e.customer_name??e.name??null,external_id:e.external_id??null,email:e.email??e.primary_email??null,created_at:e.created_at??e.created??null}}function oh(e,t){let n=Qm(e),r=Hh(n,[`payments`,`data`,`results`]),i=Wh(n,[`total`,`count`,`total_count`])??r.length,a=Uh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search||t.customer_id||t.type||t.payment_method)||void 0;return{payments:r.map(sh),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0,default_currency:`USD`}}function sh(e){if(!e||typeof e!=`object`)return{id:``,external_id:null,customer_id:null,customer_name:null,invoice_id:null,invoice_name:null,amount:null,currency:null,payment_method:null,type:null,status:null,description:null,payment_date:null,created_at:null};let t=((Array.isArray(e.payment_parts)?e.payment_parts:[]).find(e=>e&&e.invoice_id)||{}).invoice_id||e.invoice_id||null,n=e.customer&&typeof e.customer==`object`?e.customer:null,r=e.invoice&&typeof e.invoice==`object`?e.invoice:null;return{id:String(e.id||e.payment_id||``),external_id:e.external_id??null,customer_id:n?.id??e.customer_id??null,customer_name:n?.customer_name??n?.name??null,invoice_id:r?.id??t,invoice_name:r?.name??r?.invoice_number??null,amount:Gh(e.amount??e.value),currency:e.currency_code??e.currency??null,payment_method:e.payment_method??null,type:e.type??null,status:e.status??null,description:e.description??e.notes??null,payment_date:e.payment_date??e.received_at??e.processed_at??null,created_at:e.created_at??null}}function ch(e,t){let n=Qm(e),r=Hh(n,[`credit_notes`,`creditNotes`,`data`,`results`]),i=Wh(n,[`total`,`count`,`total_count`])??r.length,a=Uh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.customer_id||t.invoice_id||t.status)||void 0;return{credit_notes:r.map(lh),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0,default_currency:`USD`}}function lh(e){if(!e||typeof e!=`object`)return{id:``,credit_note_number:null,customer_id:null,customer_name:null,invoice_id:null,invoice_name:null,status:null,amount:null,currency:null,repayment_method:null,created_at:null};let t=e.customer&&typeof e.customer==`object`?e.customer:null,n=e.invoice&&typeof e.invoice==`object`?e.invoice:null;return{id:String(e.id||e.credit_note_id||``),credit_note_number:e.credit_note_number??null,customer_id:t?.id??e.customer_id??null,customer_name:t?.customer_name??t?.name??null,invoice_id:n?.id??e.invoice_id??null,invoice_name:n?.name??n?.invoice_number??null,status:e.status??null,amount:Gh(e.amount??e.total??e.value),currency:e.currency_code??e.currency??null,repayment_method:e.repayment_method??null,created_at:e.created_at??null}}function uh(e,t){let n=Qm(e),r=Hh(n,[`contracts`,`data`,`results`]),i=Wh(n,[`total`,`count`,`total_count`])??r.length,a=Uh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.customer_id||t.name__ilike||t.status)||void 0;return{contracts:r.map(dh),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0}}function dh(e){if(!e||typeof e!=`object`)return{id:``,customer_id:null,customer_name:null,name:null,status:null,currency:null,start_date:null,end_date:null,created_at:null};let t=e.customer&&typeof e.customer==`object`?e.customer:null;return{id:String(e.id||e.contract_id||``),customer_id:t?.id??e.customer_id??null,customer_name:t?.customer_name??t?.name??null,name:e.name??e.contract_name??null,status:e.status??e.state??null,currency:e.currency??e.currency_code??null,start_date:e.start_date??null,end_date:e.end_date??null,created_at:e.created_at??null}}function fh(e){let t=Qm(e),n=t.customer??t,r=ah(n),i=n.business_entity,a=n.default_payment_method,o=Array.isArray(n.contacts)?n.contacts:[],s=Array.isArray(n.tax_info)?n.tax_info:[];return{customer:{...r,phone:n.phone_number??n.phone??n.primary_phone??null,business_entity_id:n.business_entity_id??null,business_entity_name:(i&&typeof i==`object`?i.name:null)??null,address:n.address??null,ship_to_address:n.ship_to_address??null,communications_enabled:typeof n.communications_enabled==`boolean`?n.communications_enabled:null,auto_charge_enabled:typeof n.auto_charge_enabled==`boolean`?n.auto_charge_enabled:null,custom_data:n.custom_data??null,tax_info:s.length?s.map(e=>({country_code:e.country_code??null,tax_code:e.tax_code??null,tax_id:e.tax_id??null})):null,contacts:o.length?o.map(e=>({name:[e.first_name??``,e.last_name??``].filter(Boolean).join(` `)||null,email:e.email??null,send_invoice:typeof e.send_invoice==`boolean`?e.send_invoice:null,send_contract:typeof e.send_contract==`boolean`?e.send_contract:null})):null,default_payment_method:a&&typeof a==`object`?{type:a.type??null,brand:(a.details&&a.details.brand)??a.brand??null,last4:(a.details&&a.details.last4)??a.last4??null,connector_name:a.connector_name??null}:null,updated_at:n.updated_at??null}}}function ph(e){let t=Qm(e),n=t.invoice??t,r=eh(n),i=n.customer,a=n.contract;return{invoice:{...r,paid_amount:Gh(n.paid_amount??(r.invoice_total!=null&&r.amount_due!=null?r.invoice_total-r.amount_due:null)),currency:n.currency_code??n.currency??null,business_entity_id:n.business_entity_id??null,notes:n.notes??null,custom_data:n.custom_data??n.custom_attributes??null,customer_name:(i&&typeof i==`object`?i.name:null)??null,contract_id:n.contract_id??(a&&typeof a==`object`?a.id:null)??null,contract_name:(a&&typeof a==`object`?a.name:null)??null,invoice_pdf:n.invoice_pdf??null,approved_at:n.approved_at??null,paid_at:n.paid_at??null,sent_at:n.sent_at??null}}}function mh(e){let t=Qm(e),n=t.contract??t,r=dh(n),i=Array.isArray(n.phases)?n.phases:[],a=n.customer,o=Array.isArray(n.tags)?n.tags:[];return{contract:{...r,description:n.description??null,custom_attributes:n.custom_attributes??null,renewal_policy:n.renewal_policy??null,anchor_date:n.anchor_date??null,plan_id:n.plan_id??null,customer_name:(a&&typeof a==`object`?a.customer_name??a.name:null)??null,contract_type:n.contract_type??null,tags:o.length?o:null,contract_link:n.contract_link??null},phases:i.map(hh)}}function hh(e){if(!e||typeof e!=`object`)return{id:null,name:null,start_date:null,end_date:null,pricing_summary:null,product_count:null,pricings:[]};let t=Array.isArray(e.products)?e.products:[],n=Array.isArray(e.pricings)?e.pricings:t;return{id:e.id??null,name:e.name??e.phase_name??null,start_date:e.start_date??null,end_date:e.end_date??null,pricing_summary:e.pricing_summary??null,product_count:n.length||Gh(e.product_count),pricings:n.map(_h)}}function gh(e){return!e||!Array.isArray(e.prices)||!Array.isArray(e.dimensions)||e.prices.length===0?null:e.prices.map((t,n)=>({dimension:e.dimensions[n]?.name??null,display_alias:Array.isArray(e.display_alias)?e.display_alias[n]??null:null,price:typeof t==`number`?t:null}))}function _h(e){if(!e||typeof e!=`object`)return{product_name:null,pricing_model:null};let t=e.pricing??{},n=e.pricing_data??t.pricing_data??e,r=t.quantity??e.quantity??{},i=t.billing_period??e.billing_period??{},a=e.product??{};return{id:e.id??null,product_name:a.name??e.name??e.product_name??null,product_type:a.type??null,description:e.description??t.description??a.description??null,pricing_model:n.pricing_type??e.pricing_model??null,currency:n.currency??null,unit_amount:n.unit_amount??null,tiers:Array.isArray(n.tiers)?n.tiers:null,package_size:n.package_size??null,matrix:gh(n),quantity_type:r.type??null,quantity_value:r.quantity??null,quantity_unit:r.unit??null,meter_name:r.aggregate?.name??r.aggregate_name??null,billing_cadence:i.cadence??null,billing_timing:e.billing_timing??t.billing_timing??null,is_recurring:typeof t.is_recurring==`boolean`?t.is_recurring:typeof e.is_recurring==`boolean`?e.is_recurring:null,start_date:e.start_date??null,end_date:e.end_date??null,features:vh(t)}}function vh(e){let t=[],n=t=>Array.isArray(e[t])?e[t]:[];for(let e of n(`discounts`)){let n=e.type===`percentage`;t.push({type:`Discount`,label:e.label??null,summary:`${e.unit_amount??`?`}${n?`%`:` (Fixed)`}`})}for(let e of n(`taxes`)){let n=e.type===`avalara`;t.push({type:`Tax`,label:e.label??null,summary:n?`Avalara - ${e.code??`?`}`:`${e.unit_amount??`?`}%`})}for(let e of n(`free_units`))t.push({type:`Free Units`,label:e.label??null,summary:`${e.unit_amount??`?`} units`});for(let e of n(`commitments`)){let n=e.type?Km(e.type):`Commitment`;t.push({type:`Commitment`,label:e.label??null,summary:`${n}: ${e.unit_amount??`?`}`})}for(let e of n(`grants`)){let n=e.trigger_event?Km(e.trigger_event):``,r=e.expires_at?`, expires ${Km(e.expires_at)}`:``,i=e.entitlement?.name?` → ${e.entitlement.name}`:``;t.push({type:`Grant`,label:e.label??null,summary:`${e.unit_amount??`?`} units on ${n}${r}${i}`})}for(let e of n(`consumptions`)){let n=e.entitlement?.name??`Entitlement`,r=e.trigger_event?Km(e.trigger_event):``;t.push({type:`Consumption`,label:e.label??null,summary:`${n} (${Km(e.type??``)}) on ${r}`})}for(let e of n(`service_fees`)){let n=e.type===`percentage`;t.push({type:`Service Fee`,label:e.label??null,summary:`${e.unit_amount??`?`}${n?`%`:` (Fixed)`}`})}for(let e of n(`payment_terms`)){let n=e.due_days==null?``:`Due in ${e.due_days} days`;t.push({type:`Payment Terms`,label:e.label??null,summary:n||`Custom`})}return t.length>0?t:null}function yh(e){let t=Qm(e),n=t.credit_note??t.creditNote??t,r=lh(n),i=n.customer,a=n.invoice;return{credit_note:{...r,line_items_url:n.line_items_url??null,credits_returned:Gh(n.credits_returned),custom_data:n.custom_data??null,customer_name:(i&&typeof i==`object`?i.name:null)??null,invoice_number:(a&&typeof a==`object`?a.invoice_number??a.name:null)??null}}}function bh(e,t){let n=Qm(e),r=Hh(n,[`products`,`data`,`results`]),i=Wh(n,[`total`,`count`,`total_count`])??r.length,a=Uh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.name__ilike||void 0;return{products:r.map(xh),total:i,cursor:{next:o,prev:s},scope:c}}function xh(e){return!e||typeof e!=`object`?{id:``,name:null,sku:null,description:null,product_type:null,is_active:null,created_at:null}:{id:String(e.id||e.product_id||``),name:e.name??e.product_name??null,sku:e.sku??null,description:e.description??null,product_type:e.product_type??e.type??null,is_active:typeof e.is_active==`boolean`?e.is_active:null,created_at:e.created_at??null}}function Sh(e,t){let n=Qm(e),r=Hh(n,[`plans`,`data`,`results`]),i=Wh(n,[`total`,`count`,`total_count`])??r.length,a=Uh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.name__ilike||t.status)||void 0;return{plans:r.map(Ch),total:i,cursor:{next:o,prev:s},scope:c}}function Ch(e){return!e||typeof e!=`object`?{id:``,name:null,description:null,status:null,plan_version:null,created_at:null}:{id:String(e.id||e.plan_id||``),name:e.name??e.plan_name??null,description:e.description??null,status:e.status??e.state??null,plan_version:Gh(e.plan_version),created_at:e.created_at??null}}function wh(e,t){let n=Qm(e),r=Hh(n,[`entries`,`journal_entries`,`data`,`results`]),i=Wh(n,[`total`,`count`,`total_count`])??r.length,a=Uh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.search_query||void 0;return{entries:r.map(Th),total:i,cursor:{next:o,prev:s},scope:c,default_currency:`USD`}}function Th(e){if(!e||typeof e!=`object`)return{id:``,posted_at:null,event:null,description:null,status_type:null,currency:null,total_debit:null,total_credit:null,line_count:null,created_at:null};let t=Array.isArray(e.journal_lines)?e.journal_lines:[],n=0,r=0;for(let e of t)Number.isFinite(e?.debits)&&(n+=e.debits),Number.isFinite(e?.credits)&&(r+=e.credits);return{id:String(e.id||e.journal_entry_id||``),posted_at:e.posted_at??null,event:e.event??null,description:e.description??null,status_type:e.status_type??null,currency:e.currency??e.currency_code??null,total_debit:t.length?n:null,total_credit:t.length?r:null,line_count:t.length||null,created_at:e.created_at??null}}function Eh(e,t){let n=Qm(e),r=Hh(n,[`jobs`,`data`,`results`]),i=Wh(n,[`total`,`count`,`total_count`])??r.length,a=Uh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.search||void 0,l={};for(let e of r){let t=e&&e.status||`unknown`;l[t]=(l[t]||0)+1}return{jobs:r.map(Dh),total:i,cursor:{next:o,prev:s},scope:c,status_counts:l}}function Dh(e){return!e||typeof e!=`object`?{id:``,name:null,description:null,job_type:null,resource:null,status:null,created_at:null}:{id:String(e.id||e.job_id||``),name:e.name??null,description:e.description??null,job_type:e.job_type??e.type??null,resource:e.resource??null,status:e.status??null,created_at:e.created_at??null}}function Oh(e,t){let n=Qm(e),r=Hh(n,[`contacts`,`data`,`results`]),i=Wh(n,[`total`,`count`,`total_count`])??r.length,a=Uh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&t.customer_id||void 0;return{contacts:r.map(kh),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0}}function kh(e){if(!e||typeof e!=`object`)return{id:``,name:null,email:null,customer_id:null,send_invoice:null,send_contract:null};let t=[e.first_name??``,e.last_name??``].filter(Boolean).join(` `).trim(),n=e.customer,r=typeof n==`string`?n:(n&&typeof n==`object`?n.id:null)??e.customer_id??null;return{id:String(e.id||e.contact_id||``),name:e.name??(t||null),email:e.email??e.primary_email??null,customer_id:r??null,send_invoice:typeof e.send_invoice==`boolean`?e.send_invoice:null,send_contract:typeof e.send_contract==`boolean`?e.send_contract:null}}function Ah(e,t){let n=Qm(e),r=Hh(n,[`raw_metrics`,`rawmetrics`,`rawMetrics`,`data`,`results`]),i=Wh(n,[`total`,`count`,`total_count`])??r.length,a=Uh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search||t.name__ilike)||void 0;return{raw_metrics:r.map(jh),total:i,cursor:{next:o,prev:s},scope:c}}function jh(e){return!e||typeof e!=`object`?{id:``,name:null,api_slug:null,usage_upload_enabled:null,created_at:null}:{id:String(e.id||e.raw_metric_id||``),name:e.name??null,api_slug:e.api_slug??null,usage_upload_enabled:typeof e.usage_upload_enabled==`boolean`?e.usage_upload_enabled:null,created_at:e.created_at??null}}function Mh(e,t){let n=Qm(e),r=Hh(n,[`aggregates`,`data`,`results`]),i=Wh(n,[`total`,`count`,`total_count`])??r.length,a=Uh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.name__ilike||t.datasource)||void 0;return{aggregates:r.map(Nh),total:i,cursor:{next:o,prev:s},scope:c}}function Nh(e){return!e||typeof e!=`object`?{id:``,name:null,datasource:null,created_at:null}:{id:String(e.id||e.aggregate_id||``),name:e.name??null,datasource:e.datasource??e.data_source??e.raw_metric_name??null,created_at:e.created_at??null}}function Ph(e,t){let n=Hh(Qm(e),[`addresses`,`data`,`results`]);return{customer_id:t&&t.customerId?String(t.customerId):void 0,addresses:n.map(Fh),total:n.length}}function Fh(e){return!e||typeof e!=`object`?{id:``,label:null,line1:null,line2:null,city:null,state:null,zip_code:null,country:null,is_primary:null}:{id:String(e.id||``),label:e.label??e.name??e.address_type??null,line1:e.line1??e.address_line_1??null,line2:e.line2??e.address_line_2??null,line3:e.line3??null,city:e.city??null,state:e.state??null,zip_code:e.zipCode??e.zip_code??e.postal_code??null,country:e.country??e.country_code??null,validation_status:e.validation_status??null,is_primary:typeof e.is_primary==`boolean`?e.is_primary:typeof e.primary==`boolean`?e.primary:null}}function Ih(e,t){let n=Hh(Qm(e),[`payment_methods`,`paymentMethods`,`data`,`results`]);return{customer_id:t&&t.customerId?String(t.customerId):void 0,payment_methods:n.map(Lh),total:n.length}}function Lh(e){if(!e||typeof e!=`object`)return{id:``,type:null,brand:null,last4:null,exp_month:null,exp_year:null,is_default:null,created_at:null};let t=e.card||e.details||{};return{id:String(e.id||``),type:e.type??e.payment_method_type??null,brand:t.brand??e.brand??null,last4:t.last4??e.last4??null,exp_month:Gh(t.exp_month??e.exp_month),exp_year:Gh(t.exp_year??e.exp_year),is_default:typeof e.is_default==`boolean`?e.is_default:typeof e.default==`boolean`?e.default:null,created_at:e.created_at??null,connector_name:e.connector_name??null,status:e.status??null}}function Rh(e,t){let n=Qm(e),r=Hh(n,[`business_entities`,`businessEntities`,`entities`,`data`,`results`]),i=Wh(n,[`total`,`count`,`total_count`])??r.length,a=Uh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null;return{entities:r.map(zh),total:i,cursor:{next:o,prev:s}}}function zh(e){return!e||typeof e!=`object`?{id:``,name:null,email:null,phone_number:null,country:null,is_default:null}:{id:String(e.id||e.business_entity_id||``),name:e.name??e.business_entity_name??null,email:e.email??null,phone_number:e.phone_number??null,country:(e.address&&e.address.country)??e.country??null,is_default:typeof e.is_default==`boolean`?e.is_default:null}}function Bh(e,t){let n=Qm(e),r=Hh(n,[`entitlements`,`data`,`results`]),i=Wh(n,[`total`,`count`,`total_count`])??r.length,a=Uh(n,[`cursor`,`pagination`])||{},o=a.next??a.next_cursor??n.next??null,s=a.prev??a.prev_cursor??n.previous??null,c=t&&(t.search||t.name__ilike)||void 0;return{entitlements:r.map(Vh),total:i,cursor:{next:o,prev:s},scope:c}}function Vh(e){return!e||typeof e!=`object`?{id:``,name:null,entitlement_type:null,units:null,is_active:null,product_name:null,created_at:null}:{id:String(e.id||e.entitlement_id||``),name:e.name??null,entitlement_type:e.entitlement_type??null,units:e.units??null,is_active:typeof e.is_active==`boolean`?e.is_active:null,product_name:(e.product&&(e.product.name??e.product.product_name))??null,created_at:e.created_at??null}}function Hh(e,t){if(Array.isArray(e))return e;for(let n of t)if(e&&Array.isArray(e[n]))return e[n];return[]}function Uh(e,t){for(let n of t)if(e&&e[n]&&typeof e[n]==`object`)return e[n];return null}function Wh(e,t){for(let n of t)if(e&&Number.isFinite(e[n]))return e[n];return null}function Gh(e){return Number.isFinite(e)?e:null}function Kh(e,t){let n=Qm(e);return{html:n.html??(typeof n==`string`?n:``),invoice_id:t&&t.invoiceId?String(t.invoiceId):void 0}}function qh(e){if(qm.has(e))return{mode:`text-only`};let t=Jm[e];return t?{mode:`ui`,...t}:{mode:`unmapped`}}const Jh=a(s(import.meta.url)),Yh=[o(Jh,`..`,`..`,`..`,`dist`,`ui`),o(Jh,`ui`)];function Xh(e){for(let t of Yh){let i=o(t,`${e}.html`);if(n(i))return r(i,`utf8`)}return`<!doctype html><html><body style="font-family:sans-serif;padding:16px;">UI bundle missing: ${e}.html. Run <code>pnpm run build:ui</code>.</body></html>`}function Zh(){let e=new Set,t=t=>{if(t)try{e.add(new URL(t).origin)}catch{}};return t(process.env.ZENSKAR_MCP_PUBLIC_BASE_URL||process.env.MCP_PUBLIC_BASE_URL),t(process.env.ZENSKAR_API_BASE_URL),t(process.env.ZENSKAR_APP_BASE_URL),Array.from(e)}function Qh(){let e={prefersBorder:!0},t=Zh();return t.length>0&&(e.csp={connectDomains:t,resourceDomains:t}),e}function $h(e){for(let t of Ym){let n=Xm(t);e.registerResource(`zenskar-app`,n,{},async()=>({contents:[{uri:n,mimeType:`text/html;profile=mcp-app`,text:Xh(t),_meta:{"openai/widgetPrefersBorder":!0,ui:Qh()}}]}))}}const eg=[`claude-code`,`cline`,`roo-code`,`continue`,`codex`,`windsurf`,`zed`,`aider`,`copilot`,`gemini-cli`],tg=[`claude-desktop`,`claude-ai`,`chatgpt`,`mcp-inspector`,`toon`,`cursor`];let ng=null,rg=null;function ig(e){ng=e?String(e).toLowerCase().trim():null}function ag(e){rg=e}function og(){if(ng==null&&rg){let e=rg();e&&ig(e)}return ng}function sg(e){let t=(e??ng??``).toLowerCase().trim();return t?eg.some(e=>t.includes(e))?`coding-agent`:tg.some(e=>t.includes(e))?`widget-host`:`default`:`default`}const cg={comma:`,`,tab:` `,pipe:`|`}.comma;function lg(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}function ug(e){return e===`true`||e===`false`||e===`null`}function dg(e){if(e===null)return null;if(typeof e==`object`&&e&&`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();if(t!==e)return dg(t)}if(typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e==`bigint`)return e>=-(2**53-1)&&e<=2**53-1?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(dg);if(e instanceof Set)return Array.from(e).map(dg);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),dg(t)]));if(gg(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&(t[n]=dg(e[n]));return t}return null}function fg(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function pg(e){return Array.isArray(e)}function mg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hg(e){return Object.keys(e).length===0}function gg(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function _g(e){return e.length===0||e.every(e=>fg(e))}function vg(e){return e.length===0||e.every(e=>pg(e))}function yg(e){return e.length===0||e.every(e=>mg(e))}const bg=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,xg=/^0\d+$/;function Sg(e){return/^[A-Z_][\w.]*$/i.test(e)}function Cg(e){return/^[A-Z_]\w*$/i.test(e)}function wg(e,t=cg){return!(!e||e!==e.trim()||ug(e)||Tg(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\n\r\t]/.test(e)||e.includes(t)||e.startsWith(`-`))}function Tg(e){return bg.test(e)||xg.test(e)}function Eg(e,t,n,r,i,a,o){if(r.keyFolding!==`safe`||!mg(t))return;let{segments:s,tail:c,leafValue:l}=Dg(e,t,o??r.flattenDepth);if(s.length<2||!s.every(e=>Cg(e)))return;let u=Og(s),d=a?`${a}.${u}`:u;if(!n.includes(u)&&!(i&&i.has(d)))return{foldedKey:u,remainder:c,leafValue:l,segmentCount:s.length}}function Dg(e,t,n){let r=[e],i=t;for(;r.length<n&&mg(i);){let e=Object.keys(i);if(e.length!==1)break;let t=e[0],n=i[t];r.push(t),i=n}return!mg(i)||hg(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function Og(e){return e.join(`.`)}function kg(e,t){return e===null?`null`:typeof e==`boolean`||typeof e==`number`?String(e):Ag(e,t)}function Ag(e,t=cg){return wg(e,t)?e:`"${lg(e)}"`}function jg(e){return Sg(e)?e:`"${lg(e)}"`}function Mg(e,t=cg){return e.map(e=>kg(e,t)).join(t)}function Ng(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;if(n!=null&&(a+=jg(n)),a+=`[${e}${i===cg?``:i}]`,r){let e=r.map(e=>jg(e));a+=`{${e.join(i)}}`}return a+=`:`,a}function*Pg(e,t,n){if(fg(e)){let n=kg(e,t.delimiter);n!==``&&(yield n);return}pg(e)?yield*Lg(void 0,e,n,t):mg(e)&&(yield*Fg(e,n,t))}function*Fg(e,t,n,r,i,a){let o=Object.keys(e);t===0&&!r&&(r=new Set(o.filter(e=>e.includes(`.`))));let s=a??n.flattenDepth;for(let[a,c]of Object.entries(e))yield*Ig(a,c,t,n,o,r,i,s)}function*Ig(e,t,n,r,i,a,o,s){let c=o?`${o}.${e}`:e,l=s??r.flattenDepth;if(r.keyFolding===`safe`&&i){let s=Eg(e,t,i,r,a,o,l);if(s){let{foldedKey:e,remainder:t,leafValue:i,segmentCount:c}=s,u=jg(e);if(t===void 0){if(fg(i)){yield qg(n,`${u}: ${kg(i,r.delimiter)}`,r.indent);return}else if(pg(i)){yield*Lg(e,i,n,r);return}else if(mg(i)&&hg(i)){yield qg(n,`${u}:`,r.indent);return}}if(mg(t)){yield qg(n,`${u}:`,r.indent);let i=l-c,s=o?`${o}.${e}`:e;yield*Fg(t,n+1,r,a,s,i);return}}}let u=jg(e);fg(t)?yield qg(n,`${u}: ${kg(t,r.delimiter)}`,r.indent):pg(t)?yield*Lg(e,t,n,r):mg(t)&&(yield qg(n,`${u}:`,r.indent),hg(t)||(yield*Fg(t,n+1,r,a,c,l)))}function*Lg(e,t,n,r){if(t.length===0){yield qg(n,Ng(0,{key:e,delimiter:r.delimiter}),r.indent);return}if(_g(t)){yield qg(n,zg(t,r.delimiter,e),r.indent);return}if(vg(t)&&t.every(e=>_g(e))){yield*Rg(e,t,n,r);return}if(yg(t)){let i=Vg(t);i?yield*Bg(e,t,i,n,r):yield*Wg(e,t,n,r);return}yield*Wg(e,t,n,r)}function*Rg(e,t,n,r){yield qg(n,Ng(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)if(_g(e)){let t=zg(e,r.delimiter);yield Jg(n+1,t,r.indent)}}function zg(e,t,n){let r=Ng(e.length,{key:n,delimiter:t}),i=Mg(e,t);return e.length===0?r:`${r} ${i}`}function*Bg(e,t,n,r,i){yield qg(r,Ng(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*Ug(t,n,r+1,i)}function Vg(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&Hg(e,n))return n}function Hg(e,t){for(let n of e){if(Object.keys(n).length!==t.length)return!1;for(let e of t)if(!(e in n)||!fg(n[e]))return!1}return!0}function*Ug(e,t,n,r){for(let i of e)yield qg(n,Mg(t.map(e=>i[e]),r.delimiter),r.indent)}function*Wg(e,t,n,r){yield qg(n,Ng(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)yield*Kg(e,n+1,r)}function*Gg(e,t,n){if(hg(e)){yield qg(t,`-`,n.indent);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(pg(a)&&yg(a)){let e=Vg(a);if(e){yield Jg(t,Ng(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indent),yield*Ug(a,e,t+2,n),o.length>0&&(yield*Fg(Object.fromEntries(o),t+1,n));return}}let s=jg(i);if(fg(a))yield Jg(t,`${s}: ${kg(a,n.delimiter)}`,n.indent);else if(pg(a))if(a.length===0)yield Jg(t,`${s}${Ng(0,{delimiter:n.delimiter})}`,n.indent);else if(_g(a))yield Jg(t,`${s}${zg(a,n.delimiter)}`,n.indent);else{yield Jg(t,`${s}${Ng(a.length,{delimiter:n.delimiter})}`,n.indent);for(let e of a)yield*Kg(e,t+2,n)}else mg(a)&&(yield Jg(t,`${s}:`,n.indent),hg(a)||(yield*Fg(a,t+2,n)));o.length>0&&(yield*Fg(Object.fromEntries(o),t+1,n))}function*Kg(e,t,n){if(fg(e))yield Jg(t,kg(e,n.delimiter),n.indent);else if(pg(e))if(_g(e))yield Jg(t,zg(e,n.delimiter),n.indent);else{yield Jg(t,Ng(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*Kg(r,t+1,n)}else mg(e)&&(yield*Gg(e,t,n))}function qg(e,t,n){return` `.repeat(n*e)+t}function Jg(e,t,n){return qg(e,`- `+t,n)}function Yg(e,t){let n=t(``,e,[]);return Xg(n===void 0?e:dg(n),t,[])}function Xg(e,t,n){return mg(e)?Zg(e,t,n):pg(e)?Qg(e,t,n):e}function Zg(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=[...n,i],o=t(i,a,e);o!==void 0&&(r[i]=Xg(dg(o),t,e))}return r}function Qg(e,t,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i],o=[...n,i],s=t(String(i),a,o);if(s===void 0)continue;let c=dg(s);r.push(Xg(c,t,o))}return r}function $g(e,t){return Array.from(e_(e,t)).join(`
|
|
79
|
+
`)}function e_(e,t){let n=dg(e),r=t_(t);return Pg(r.replacer?Yg(n,r.replacer):n,r,0)}function t_(e){return{indent:e?.indent??2,delimiter:e?.delimiter??cg,keyFolding:e?.keyFolding??`off`,flattenDepth:e?.flattenDepth??1/0,replacer:e?.replacer}}function n_(e){return typeof e==`string`?e:$g(e)}function r_(){let e=process.env.ZENSKAR_MCP_UI_ENABLED;return e==null||e===``?!0:!/^(0|false|no|off)$/i.test(String(e).trim())}function i_(){let e=process.env.ZENSKAR_MCP_UI_DISABLED_TOOLS;return e?new Set(String(e).split(`,`).map(e=>e.trim()).filter(Boolean)):new Set}const a_=process.env.ZENSKAR_MCP_UI_DEBUG===`true`||process.env.MCP_DEBUG===`true`;function o_(...e){a_&&console.error(`[ui-wrap]`,...e)}function s_(e,t,n,r){if(!r_())return o_(e,`skipped: ZENSKAR_MCP_UI_ENABLED explicitly disabled`),l_(n);let i=qh(e);if(i.mode!==`ui`)return o_(e,`skipped: not in registry, mode=`,i.mode),l_(n);if(i_().has(e))return o_(e,`skipped: in ZENSKAR_MCP_UI_DISABLED_TOOLS`),l_(n);let a;try{a=i.toPayload(t,r)}catch(t){return o_(e,`toPayload threw:`,t.message),l_(n)}let o=c_(a);if(o<(i.threshold??0))return o_(e,`below threshold:`,o,`<`,i.threshold),l_(n);let s=sg(og());return o_(e,`OK shape=`,i.shape,`items=`,o,`client=`,s),s===`coding-agent`?l_(n):s===`widget-host`?{content:[{type:`text`,text:(o<=1&&i.shape.includes(`detail`)?`Full detail rendered in widget above — user already sees every field. Do not summarize or restate. Only respond if user asks a specific question. Reference data below for follow-ups.`:`Data rendered in table widget above. Use values below for follow-up questions — do not restate rows.`)+`
|
|
80
|
+
`+n_(a)}],structuredContent:a}:l_(n)}function c_(e){if(!e||typeof e!=`object`)return 0;for(let t of[`customers`,`invoices`,`lines`,`payments`,`credit_notes`,`contracts`,`transactions`,`rows`,`items`,`data`,`addresses`,`payment_methods`,`products`,`plans`,`entries`,`jobs`,`contacts`,`raw_metrics`,`aggregates`,`entities`])if(Array.isArray(e[t]))return e[t].length;if(Number.isFinite(e.total))return e.total;for(let t of[`customer`,`invoice`,`contract`,`credit_note`])if(e[t]&&typeof e[t]==`object`)return 1;return+!!e.html}function l_(e){return{content:[{type:`text`,text:e}]}}const u_=s(import.meta.url),d_=i.dirname(u_),f_={logUsage:async()=>{}},p_=(e,t)=>({valid:!0,adjustedArgs:t,warnings:[],errors:[]}),m_=()=>({message:`Limits validation unavailable`,severity:`info`,suggestions:[]}),$={debug:(e,t)=>{if(process.env.MCP_DEBUG===`true`){let n=new Date().toISOString();console.error(`[${n}] [MCP-DEBUG] ${e}`,t?JSON.stringify(t,null,2):``)}},info:(e,t)=>{let n=new Date().toISOString();console.error(`[${n}] [MCP-INFO] ${e}`,t?JSON.stringify(t,null,2):``)},error:(e,t)=>{let n=new Date().toISOString();console.error(`[${n}] [MCP-ERROR] ${e}`,t?JSON.stringify(t,null,2):``)},warn:(e,t)=>{let n=new Date().toISOString();console.error(`[${n}] [MCP-WARN] ${e}`,t?JSON.stringify(t,null,2):``)}},h_=i.join(d_,`mcp-config.json`);let g_;try{g_=JSON.parse(t.readFileSync(h_,`utf8`))}catch(e){console.error(`Failed to load MCP config:`,e.message),console.error(`Please ensure mcp-config.json exists in the project root`),process.exit(1)}const __=new pm({name:g_.server?.name||`zenskar-api-server`,version:`1.0.0`});ag(()=>{let e=__.server.getClientVersion();return e&&e.name?e.name:null});const v_=new Nm;function y_(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t={...e};return typeof t.timestamp==`string`&&(t.timestamp=b_(t.timestamp)),t.data&&typeof t.data==`object`&&!Array.isArray(t.data)&&(t.data={...t.data},[`DateTime64`,`DateTime`,`DateTime32`].forEach(e=>{typeof t.data[e]==`string`&&(t.data[e]=b_(t.data[e]))})),t}function b_(e){return typeof e==`string`?e.replace(`T`,` `).replace(`t`,` `).replace(/Z$/i,``).trim():e}function x_(e){if(typeof e!=`string`)return e;let t=e.trim();if(!t)return e;switch(t.toLowerCase()){case`boolean`:return`Bool`;case`string`:return`String`;case`int`:case`int64`:return`Int64`;case`float`:case`float64`:case`double`:return`Float64`;case`date`:case`date32`:return`Date32`;case`datetime`:case`datetime64`:return`DateTime64`;case`uuid`:return`UUID`;default:return t}}function S_(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t={...e};if(t.customer_id&&=x_(t.customer_id),t.timestamp&&=x_(t.timestamp),t.data&&typeof t.data==`object`&&!Array.isArray(t.data)){let e={};Object.entries(t.data).forEach(([t,n])=>{e[t]=x_(n)}),t.data=e}return t}function C_(e){return e?Array.isArray(e)?e:Array.isArray(e.results)?e.results:e.api_response===void 0?[]:C_(e.api_response):[]}function w_(e){return!e||typeof e!=`string`?`Uncategorized`:e.trim()||`Uncategorized`}function T_(e){let t=Number(e);return Number.isFinite(t)?t/100:null}function E_(e,t){let n=w_(t);return e===`getBalanceSheet`&&n===`Liabilities`?`Liabilities & Equity`:n}function D_(e,t){return(e===`getBalanceSheet`?{Assets:1,Liabilities:2,Equity:3}:{Income:1,Revenue:1,"Cost of Goods Sold":2,Expense:3,Expenses:3,"Other Income":4,"Other Expense":5,"Other Expenses":5})[t]||999}function O_(e){return`${e?.interval_start||`unknown_start`}__${e?.interval_end||`unknown_end`}`}function k_(e){return Object.values(e).sort((e,t)=>String(e.interval_start).localeCompare(String(t.interval_start)))}function A_(e,t,n){let r=new Map,i=new Map;t.forEach(t=>{let a=E_(e,t.account_category),o=O_(t),s=r.get(o)||{key:o,interval_start:t.interval_start||null,interval_end:t.interval_end||null};r.set(o,s),i.has(a)||i.set(a,{category:a,accounts:new Map,totals_by_period:{},total_balance:0,total_debits:0,total_credits:0});let c=i.get(a),l=t.account_id||`unknown_account`,u=n.get(l)||{};c.accounts.has(l)||c.accounts.set(l,{account_id:l,account_name:t.account_name||u.name||l,account_description:t.account_description||u.description||null,account_category:a,parent_path:t.account_parent_path||u.parent_path||null,balance_normality:t.balance_normality||u.balance_normality||null,periods:{},total_balance:0,total_debits:0,total_credits:0});let d=c.accounts.get(l);d.periods[o]={interval_start:t.interval_start||null,interval_end:t.interval_end||null,balance:t.balance??0,display_balance:T_(t.balance??0),debits:t.debits??0,display_debits:T_(t.debits??0),credits:t.credits??0,display_credits:T_(t.credits??0)},d.total_balance+=Number(t.balance||0),d.total_debits+=Number(t.debits||0),d.total_credits+=Number(t.credits||0);let f=c.totals_by_period[o]||{interval_start:t.interval_start||null,interval_end:t.interval_end||null,balance:0,debits:0,credits:0,display_balance:0,display_debits:0,display_credits:0};f.balance+=Number(t.balance||0),f.debits+=Number(t.debits||0),f.credits+=Number(t.credits||0),f.display_balance=T_(f.balance),f.display_debits=T_(f.debits),f.display_credits=T_(f.credits),c.totals_by_period[o]=f,c.total_balance+=Number(t.balance||0),c.total_debits+=Number(t.debits||0),c.total_credits+=Number(t.credits||0)});let a=Array.from(i.values()).sort((t,n)=>{let r=D_(e,t.category)-D_(e,n.category);return r===0?t.category.localeCompare(n.category):r}).map(e=>({category:e.category,accounts:Array.from(e.accounts.values()).sort((e,t)=>e.account_name.localeCompare(t.account_name)).map(e=>({...e,periods:k_(e.periods)})),totals_by_period:k_(e.totals_by_period),total_balance:e.total_balance,display_total_balance:T_(e.total_balance),total_debits:e.total_debits,display_total_debits:T_(e.total_debits),total_credits:e.total_credits,display_total_credits:T_(e.total_credits)}));return{report_type:e===`getBalanceSheet`?`balance_sheet`:`income_statement`,periods:Array.from(r.values()).sort((e,t)=>String(e.interval_start).localeCompare(String(t.interval_start))),sections:a}}function j_(e){if(!e)return``;let t=e.account_category||``;return t===`Liabilities`?`Liabilities & Equity`:t}function M_(e){let t=[...e].map(e=>({...e,account_category:j_(e)})).sort((e,t)=>{let n=j_(e).localeCompare(j_(t));return n===0?String(e.name||``).localeCompare(String(t.name||``)):n}),n=new Map;t.forEach(e=>{let t=j_(e)||`Uncategorized`;n.has(t)||n.set(t,[]),n.get(t).push(e)}),[`Assets`,`Liabilities & Equity`,`Equity`,`Income`,`Expenses`].forEach(e=>{n.has(e)||n.set(e,[])});let r=Array.from(n.entries()).sort((e,t)=>e[0].localeCompare(t[0])).map(([e,t])=>({id:e,name:e,description:e,account_category:e,is_parent:!0,parent_path:null,children:t.map(t=>({...t,parent_path:t.parent_path||e}))})),i=r.find(e=>e.name===`Liabilities & Equity`);return i&&(i.children.some(e=>e.name===`Equity`)||(i.children.push({id:`Equity`,name:`Equity`,description:`Equity`,account_category:`Liabilities & Equity`,balance_normality:`credit`,is_parent:!0,parent_path:`Liabilities & Equity`,custom_data:{default_account:!1},children:[]}),i.children.push({id:`Equity:Retained Earnings`,name:`Retained Earnings`,description:`Retained Earnings`,account_category:`Liabilities & Equity`,balance_normality:`credit`,is_parent:!1,parent_path:`Equity`,custom_data:{default_account:!1}}))),r}function N_(e){if(!e||!Array.isArray(e.results))return e;let t=e.results.reduce((e,t)=>{let n=t.status||`unknown`;return e[n]=(e[n]||0)+1,e},{});return{...e,summary:{total_count:e.total_count??e.results.length,returned_count:e.results.length,page_status_counts:t,has_more:!!e.next,note:e.next?`Showing ${e.results.length} jobs from the current page. Use the cursor to continue through the remaining jobs.`:`Showing ${e.results.length} jobs from the current page.`}}}function P_(e){if(!e||!Array.isArray(e.results))return e;let t=[...e.results].sort((e,t)=>{let n=w_(e.account_category),r=w_(t.account_category),i=n.localeCompare(r);return i===0?String(e.name||``).localeCompare(String(t.name||``)):i}),n=t.reduce((e,t)=>{let n=w_(t.account_category);return e[n]=e[n]||[],e[n].push(t),e},{});return{...e,results:t,grouped_view:n}}async function F_(e,t){let n=await fetch(e,{method:`GET`,headers:t}),r=await n.text();if(!n.ok)throw Error(`Supplemental fetch failed: ${n.status} ${n.statusText}\nResponse: ${r}`);try{return JSON.parse(r)}catch{throw Error(`Supplemental fetch returned non-JSON response: ${r}`)}}async function I_(e,t,n){let r=e.rawMetricId,i=await F_(`${n}/rawmetric/${encodeURIComponent(r)}`,t);if(!i?.api_slug)throw Error(`Unable to resolve api_slug for raw metric ${r}`);let a={...t,apiversion:`20240301`},o={limit:e.limit??20,offset:e.offset??0,order_by:e.order_by??[{column:`timestamp`,type:`DESC`}],aggregate_operation:e.aggregate_operation??null,customer_mapping:null,end_date_mapping:null,start_date_mapping:null,table_name:`raw_metric_${i.api_slug}`,visual_query:{groups:[{filters:Array.isArray(e.filters)?e.filters:[],logic:`AND`}],logic:`AND`}},s=await fetch(`${n}/aggregate/visualquery/preview`,{method:`POST`,headers:a,body:JSON.stringify(o)}),c=await s.text();if(!s.ok)throw Error(`API request failed: ${s.status} ${s.statusText}\nResponse: ${c}`);try{return JSON.parse(c)}catch{return c}}async function L_(e,t,n,r){if(!t||!Array.isArray(t.results))return t;try{let i=C_(await F_(`${r}/accounting_new/chart_of_accounts`,n)),a=new Map(i.filter(e=>e&&e.id).map(e=>[e.id,e])),o=t.results.map(t=>{let n=a.get(t.account_id)||{};return{...t,account_name:n.name||t.account_id||null,account_description:n.description||null,account_category:E_(e,n.account_category),account_parent_path:n.parent_path||null,balance_normality:n.balance_normality||null,display_balance:T_(t.balance??0),display_debits:T_(t.debits??0),display_credits:T_(t.credits??0)}}),s=A_(e,o,a);if(e===`getBalanceSheet`){let e=new URLSearchParams;n.apiversion&&e.set(`apiversion`,n.apiversion);let t=await F_(`${r}/accounting_new/income_statement/v2`,n),i=Array.isArray(t?.results)?t.results:[],a={};i.forEach(e=>{let t=O_(e),n=a[t]||{interval_start:e.interval_start||null,interval_end:e.interval_end||null,balance:0,debits:0,credits:0};n.balance+=Number(e.balance||0),n.debits+=Number(e.debits||0),n.credits+=Number(e.credits||0),a[t]=n});let o=k_(Object.fromEntries(Object.entries(a).map(([e,t])=>[e,{...t,display_balance:T_(t.balance),display_debits:T_(t.debits),display_credits:T_(t.credits)}]))),c={account_id:`Equity:Retained Earnings`,account_name:`Retained Earnings (Derived)`,account_description:`Derived from the companion income statement for MCP presentation.`,account_category:`Liabilities & Equity`,parent_path:`Equity`,balance_normality:`credit`,periods:o,total_balance:o.reduce((e,t)=>e+Number(t.balance||0),0),display_total_balance:T_(o.reduce((e,t)=>e+Number(t.balance||0),0)),total_debits:o.reduce((e,t)=>e+Number(t.debits||0),0),display_total_debits:T_(o.reduce((e,t)=>e+Number(t.debits||0),0)),total_credits:o.reduce((e,t)=>e+Number(t.credits||0),0),display_total_credits:T_(o.reduce((e,t)=>e+Number(t.credits||0),0))},l=s.sections.find(e=>e.category===`Liabilities & Equity`);l||(l={category:`Liabilities & Equity`,accounts:[],totals_by_period:[],total_balance:0,display_total_balance:0,total_debits:0,display_total_debits:0,total_credits:0,display_total_credits:0},s.sections.push(l)),l.accounts.push(c)}return{...t,results:o,statement_view:s}}catch(n){return $.warn(`[${e}] Failed to enrich accounting report output; returning raw report`,{error:n.message}),t}}async function R_(e,t){let n=Date.now();if(e.name===`getCurrentDateTime`){let e=new Date;return{currentDate:e.toISOString().split(`T`)[0],currentDateTime:e.toISOString(),timestamp:e.getTime(),timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,humanReadable:e.toLocaleString()}}$.debug(`[${e.name}] Raw args received:`,{argKeys:Object.keys(t),argValues:JSON.stringify(t,null,2)});let r=t.__userContext,i={...t};delete i.__userContext,$.debug(`[${e.name}] User context received:`,r?{hasUserId:!!r.userId,hasAuthorization:!!r.authorization,hasOrganization:!!r.organization,authPrefix:r.authorization?r.authorization.substring(0,20)+`...`:`none`}:`NO USER CONTEXT`);let a=e.requestTemplate?.url||`/`,o=e.requestTemplate?.method||`GET`,s=a.startsWith(`http://`)||a.startsWith(`https://`);$.debug(`[${e.name}] Executing ${o} request with args:`,JSON.stringify(i,null,2)),r&&$.debug(`[${e.name}] Using user context:`,{hasApiKey:!!r.apiKey,hasOrganization:!!r.organization,userId:r.userId}),e.args&&e.args.forEach(e=>{e.position===`path`&&i[e.name]!==void 0&&(a=a.replace(`{${e.name}}`,encodeURIComponent(i[e.name])))});let c=new URLSearchParams;e.args&&e.args.forEach(e=>{e.position===`query`&&i[e.name]!==void 0&&i[e.name]!==null&&i[e.name]!==``&&(typeof i[e.name]==`boolean`?c.append(e.name,i[e.name].toString()):Array.isArray(i[e.name])?i[e.name].forEach(t=>{c.append(e.name,t)}):c.append(e.name,i[e.name]))}),Object.keys(i).forEach(t=>{if(!c.has(t)&&i[t]!==void 0&&i[t]!==null&&i[t]!==``){let n=e.args?.some(e=>e.position===`path`&&e.name===t),r=e.args?.some(e=>e.position===`body`&&e.name===t);!n&&!r&&(typeof i[t]==`boolean`?c.append(t,i[t].toString()):Array.isArray(i[t])?i[t].forEach(e=>{c.append(t,e)}):c.append(t,i[t]))}}),c.toString()&&(a+=`?`+c.toString());let l=null;if(o!==`GET`&&o!==`DELETE`&&e.args){let t=e=>{if(typeof e==`number`)return Number.isFinite(e)?Math.floor(e):e;if(typeof e==`string`){let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):e}return e},n={},a=null;if(e.args.forEach(r=>{if(r.position===`body`&&i[r.name]!==void 0){if(r.type===`datetime`){n[r.name]=t(i[r.name]);return}if(e.name===`ingestRawMetricEvent`&&r.name===`event`){let e=y_(i[r.name]);e&&typeof e==`object`&&!Array.isArray(e)?Object.entries(e).forEach(([e,t])=>{t!==void 0&&(n[e]=t)}):n[r.name]=e}else e.name===`ingestRawMetricEventsBulk`&&r.name===`events`?a=(Array.isArray(i[r.name])?i[r.name]:[]).map(e=>y_(e)):n[r.name]=i[r.name]}}),e.name===`createCustomer`||e.name===`updateCustomer`){let t=(t,r)=>{let i={[`${t}line1`]:`line1`,[`${t}line2`]:`line2`,[`${t}line3`]:`line3`,[`${t}city`]:`city`,[`${t}state`]:`state`,[`${t}zipCode`]:`zipCode`,[`${t}country`]:`country`,[`${t}country_code`]:`country_code`},a={},o=!1;Object.entries(i).forEach(([e,t])=>{n[e]!==void 0&&(a[t]=n[e],delete n[e],o=!0)}),o&&(n[r]=a,$.debug(`[${e.name}] Transformed flat ${t}* fields into ${r} object`))};t(`address_`,`address`),t(`ship_to_`,`ship_to_address`)}if(e.name===`createBusinessEntity`&&((t,r)=>{let i={[`${t}line1`]:`line1`,[`${t}line2`]:`line2`,[`${t}line3`]:`line3`,[`${t}city`]:`city`,[`${t}state`]:`state`,[`${t}zipCode`]:`zipCode`,[`${t}country`]:`country`},a={},o=!1;Object.entries(i).forEach(([e,t])=>{n[e]!==void 0&&(a[t]=n[e],delete n[e],o=!0)}),o&&(n[r]=a,$.debug(`[${e.name}] Transformed flat ${t}* fields into ${r} object`))})(`address_`,`address`),e.name===`getInvoicePreviewHtml`&&!i.orgId){let e=r?.organization||process.env.ZENSKAR_ORGANIZATION;e&&(i.orgId=e)}if(e.name===`extractContractFromRaw`&&!n.organization_id){let t=r?.organization||process.env.ZENSKAR_ORGANIZATION;t&&(n.organization_id=t,$.debug(`[${e.name}] Auto-populated organization_id: ${t}`))}e.name===`createRawMetric`&&(n.connector||=i.connector||`push_to_zenskar`,n.api_type||=i.api_type||`PUSH`,n.dataschema||={customer_id:`string`,timestamp:`timestamp`,data:{usage_amount:`decimal`,feature_id:`string`}},n.dataschema&&=S_(n.dataschema),n.column_order=[`timestamp`]),e.name===`ingestRawMetricEventsBulk`?l=JSON.stringify(a||[]):Object.keys(n).length>0?l=JSON.stringify(n):(o===`PATCH`||o===`POST`||o===`PUT`)&&(l=`{}`)}let u={"Content-Type":`application/json`,"User-Agent":`Zenskar-MCP-Server/1.0.0`,apiversion:`20230501`},d=r?.organization||process.env.ZENSKAR_ORGANIZATION,f=r?.authorization||r?.headers?.authorization||r?.headers?.Authorization||process.env.ZENSKAR_AUTH_TOKEN,p=r?.apiKey||r?.headers?.[`x-api-key`]||process.env.ZENSKAR_API_KEY||process.env.ZENSKAR_AUTH_TOKEN;if(d)u.organisation=d;else throw $.error(`[${e.name}] SECURITY ERROR: No organization ID provided`),Error(`Organization ID is required for API access. Set ZENSKAR_ORGANIZATION env var or provide in user context.`);if(f&&f.startsWith(`eyJ`))u.Authorization=f.startsWith(`Bearer `)?f:`Bearer ${f}`;else if(p)u[`x-api-key`]=p;else throw $.error(`[${e.name}] SECURITY ERROR: No authorization provided`),Error(`Authorization is required. Set ZENSKAR_AUTH_TOKEN (JWT) or ZENSKAR_API_KEY env var.`);if(r?.headers){let e=new Set(Object.keys(u).map(e=>e.toLowerCase())),t=new Set([`__proto__`,`prototype`,`constructor`]);Object.keys(r.headers).forEach(n=>{t.has(n)||Object.prototype.hasOwnProperty.call(r.headers,n)&&r.headers[n]&&!e.has(n.toLowerCase())&&(u[n]=r.headers[n])})}$.debug(`[${e.name}] Using headers:`,{hasOrganization:!!u.organisation,hasAuthorization:!!u.Authorization,hasApiKey:!!u[`x-api-key`],source:r?.organization?`userContext`:`env`}),e.requestTemplate?.headers&&(Array.isArray(e.requestTemplate.headers)?e.requestTemplate.headers.forEach(e=>{u[e.key]=e.value}):Object.keys(e.requestTemplate.headers).forEach(t=>{u[t]=e.requestTemplate.headers[t]}));let m;if(s)m=a,$.debug(`[${e.name}] Using absolute URL: ${m}`);else{let t=process.env.ZENSKAR_API_BASE_URL||`https://api.zenskar.com`;m=t+a,$.debug(`[${e.name}] Using relative URL with base: ${t} + ${a} = ${m}`)}$.debug(`[${e.name}] Making ${o} request to: ${m}`),$.info(`[${e.name}] MULTI-TENANT SECURITY CHECK - Headers being sent:`,{organization:u.organisation||`MISSING`,hasAuth:!!u.Authorization,authPrefix:u.Authorization?u.Authorization.substring(0,30)+`...`:`NONE`,allHeaders:JSON.stringify(u,null,2)});try{if(e.name===`getRawMetricLogs`){let t=await I_(i,u,process.env.ZENSKAR_API_BASE_URL||`https://api.zenskar.com`);return $.debug(`[${e.name}] Successfully processed frontend-style usage-event logs`),t}let t=await fetch(m,{method:o,headers:u,body:l}),r=await t.text(),a=Date.now()-n;if($.info(`[${e.name}] Response received in ${a}ms - Status: ${t.status}, Size: ${r.length} chars`),$.info(`[${e.name}] Raw response body:`,r),!t.ok){$.error(`[${e.name}] API Error Response:`,r);let n=`API request failed: ${t.status} ${t.statusText}\nResponse: ${r}`;throw Error(n)}let s;try{s=JSON.parse(r)}catch{$.debug(`[${e.name}] Failed to parse JSON response, returning as text`),s=r}if(e.name===`getInvoicePreviewHtml`)if(typeof s==`string`)try{let e=Buffer.from(s,`base64`).toString(`utf8`);s=e.includes(`<`)?{html:e}:{html:s}}catch{s={html:s}}else s={html:``};if(e.name===`getBalanceSheet`||e.name===`getIncomeStatement`){let t=process.env.ZENSKAR_API_BASE_URL||`https://api.zenskar.com`;s=await L_(e.name,s,u,t)}return e.name===`listJobs`&&(s=N_(s)),e.name===`listAccounts`&&(s=P_(s)),e.name===`getChartOfAccounts`&&Array.isArray(s)&&(s={raw_accounts:s,chart_view:M_(s)}),e.responseTemplate?.prependBody&&(s={template_info:e.responseTemplate.prependBody,api_response:s}),$.debug(`[${e.name}] Successfully processed response`),s}catch(t){throw $.error(`[${e.name}] Network error:`,t),Error(`Network error: ${t.message}`)}}async function z_(e,t){let{listArg:n}=e.bulkOver,r=[];for(let i of t[n])try{r.push({id:i,status:`succeeded`,response:await R_(e,{...t,[n]:i})})}catch(t){$.error(`[${e.name}] ${i} failed:`,t),r.push({id:i,status:`failed`,error:t.message})}let i=r.filter(e=>e.status===`failed`);return $.info(`[${e.name}] bulk complete: ${r.length-i.length}/${r.length} succeeded`),{summary:{requested:r.length,succeeded:r.length-i.length,failed:i.length},results:r}}const B_=300*1e3,V_=process.env.APPROVAL_HMAC_SECRET,H_=!!V_,U_=new Map,W_=new Map;function G_(e){if(e==null)return e;if(typeof structuredClone==`function`)try{return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}function K_(e){let t=e?G_(e):{};return delete t.__userContext,t}function q_(t){return e.createHmac(`sha256`,V_).update(t).digest(`base64url`)}function J_(t,n){let r=Date.now(),i=r+B_,a=K_(n);if(H_){let n={toolName:t,args:a,issuedAt:r,expiresAt:i,nonce:e.randomBytes(12).toString(`base64url`)},o=Buffer.from(JSON.stringify(n),`utf8`).toString(`base64url`);return`v1.${o}.${q_(o)}`}let o=jm();return U_.set(o,{toolName:t,issuedAt:r,expiresAt:i,args:a}),o}function Y_(t,n){if(!t||typeof t!=`string`)return null;if(H_){let r=t.split(`.`);if(r.length!==3)return null;let[i,a,o]=r;if(i!==`v1`)return null;let s=q_(a),c=Buffer.from(o,`base64url`),l=Buffer.from(s,`base64url`);if(c.length!==l.length||!e.timingSafeEqual(c,l))return null;let u;try{u=JSON.parse(Buffer.from(a,`base64url`).toString(`utf8`))}catch{return null}return u.toolName!==n||typeof u.expiresAt!=`number`||u.expiresAt<Date.now()||W_.has(t)?null:(W_.set(t,u.expiresAt),u)}let r=U_.get(t);return!r||(U_.delete(t),r.toolName!==n)||r.expiresAt<Date.now()?null:r}setInterval(()=>{let e=Date.now();for(let[t,n]of U_)n.expiresAt<e&&U_.delete(t);for(let[t,n]of W_)n<e&&W_.delete(t)},6e4).unref();function X_(e,t){return(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0)(e.modifiedArguments)?{args:e.modifiedArguments,source:`modifiedArguments`}:{args:t.args,source:`tokenSnapshot`}}function Z_(e,t){let n={...t};for(let t of e.args||[]){if(t.type!==`array`)continue;let e=n[t.name];if(typeof e==`string`){try{let r=JSON.parse(e);if(Array.isArray(r)){n[t.name]=r;continue}}catch{}n[t.name]=e.split(`,`).map(e=>e.trim()).filter(e=>e!==``)}}return n}function Q_(e,t){let n=e.__userContext;Object.keys(e).forEach(t=>{t!==`__userContext`&&delete e[t]}),Object.assign(e,t),e.__userContext=n}function $_(e,t){if(!e.needsApproval)return!1;let n=t.__userContext,r=n&&n.approval;if(r&&r.approved===!0){let n=Y_(r.token,e.name);if(n){let{args:i,source:a}=X_(r,n);return $.info(`[${e.name}] Approval token verified; arg source=${a}`),Q_(t,a===`modifiedArguments`?Z_(e,i):i),$.info(`[${e.name}] Restored arguments for approved execution:`,Object.keys(i)),!1}$.warn(`[${e.name}] Approval received without valid token (got: ${r.token?`expired/mismatched`:`missing`}); requiring re-approval`)}return typeof e.needsApproval==`function`?e.needsApproval(t):e.needsApproval===!0}function ev(e,t){t.__userContext;let n={...t};delete n.__userContext;let r=J_(e.name,t);return{type:`approval_required`,toolName:e.name,toolDescription:e.description,arguments:n,approvalToken:r,approvalTokenExpiresInSeconds:Math.floor(B_/1e3),approvalConfig:e.approvalConfig||{title:`Approve ${e.name}`,description:`This action requires your approval: ${e.description}`,warningText:`Please review the parameters carefully before proceeding.`,confirmText:`Approve`,cancelText:`Cancel`},fields:(e.args||[]).map(t=>({name:t.name,label:t.description||t.name,type:tv(t.type),required:t.required||!1,value:n[t.name],sensitive:e.approvalConfig?.sensitiveFields?.includes(t.name)||!1}))}}function tv(e){switch(e){case`string`:return`text`;case`integer`:case`number`:return`number`;case`boolean`:return`checkbox`;case`array`:return`textarea`;default:return`text`}}$h(__),g_.tools&&g_.tools.length>0&&g_.tools.forEach(e=>{$.info(`Registering tool: ${e.name}`);let t=Fm(e.args||[]),n=qh(e.name),r=n.mode===`ui`?(()=>{let e=Xm(n.shape);return{"openai/outputTemplate":e,"ui/resourceUri":e,ui:{resourceUri:e}}})():void 0;__.registerTool(e.name,{title:e.name,description:e.description,inputSchema:t,...r?{_meta:r}:{}},async t=>{let n=Date.now(),r=`success`,i=null,a=0,o=0,s=null,c=null;try{$.debug(`[${e.name}] Tool execution started`),$.info(`[${e.name}] Raw args received:`,{argKeys:Object.keys(t),hasUserContextInArgs:!!t.__userContext,userContextInArgs:t.__userContext,approvedInArgs:t.__userContext?.approved});let l=await Gm(e,t);if(!l.valid){$.error(`[${e.name}] Tool execution blocked due to invalid arguments (pre-approval):`,l.errors),r=`blocked`,i=`invalid_args: ${l.errors.join(`; `)}`;let t={type:`invalid_arguments`,toolName:e.name,errors:l.errors};return{content:[{type:`text`,text:JSON.stringify(t,null,2)},{type:`text`,text:`ACTION_NOT_EXECUTED — INVALID_ARGUMENTS\n\nTool '${e.name}' was NOT executed because the supplied arguments are invalid or incomplete:\n\n`+l.errors.map((e,t)=>`${t+1}. ${e}`).join(`
|
|
81
81
|
`)+`
|
|
82
82
|
|
|
83
|
-
Fix the arguments and call again. Do NOT report success to the user.`}],isError:!0}}let u
|
|
83
|
+
Fix the arguments and call again. Do NOT report success to the user.`}],isError:!0}}let u=$_(e,t),d=t.__userContext;if($.info(`[${e.name}] Approval check:`,{needsApproval:u,hasUserContext:!!d,userContextKeys:d?Object.keys(d):[],hasApprovalBlock:!!(d&&d.approval),hasToken:!!(d&&d.approval&&d.approval.token)}),u){$.info(`[${e.name}] Tool requires approval, generating approval request`);let n=ev(e,t);return{content:[{type:`text`,text:JSON.stringify(n,null,2)},{type:`text`,text:`ACTION_NOT_EXECUTED — APPROVAL_REQUIRED\n\nTool '${e.name}' was NOT executed. The host must render an approval dialog from the JSON payload above and re-invoke this tool with __userContext.approval = {approved: true, token: '<approvalToken from payload>'} to actually perform the action. The token is single-use and expires in ${Math.floor(B_/1e3)}s. Do NOT fabricate the token. Do NOT report success to the user; surface the dialog instead.`}],isApprovalRequired:!0,approvalRequest:n}}let f=await Gm(e,t);if(!f.valid)return $.error(`[${e.name}] Approved arguments failed validation:`,f.errors),r=`blocked`,i=`invalid_args_post_approval: ${f.errors.join(`; `)}`,{content:[{type:`text`,text:JSON.stringify({type:`invalid_arguments`,toolName:e.name,errors:f.errors},null,2)},{type:`text`,text:`ACTION_NOT_EXECUTED — INVALID_ARGUMENTS
|
|
84
84
|
|
|
85
85
|
Approved arguments failed validation. The user-edited values from the approval dialog do not satisfy the tool schema:
|
|
86
86
|
|
|
87
87
|
`+f.errors.map((e,t)=>`${t+1}. ${e}`).join(`
|
|
88
88
|
`)+`
|
|
89
89
|
|
|
90
|
-
Re-issue the call with corrected arguments; a new approval gate will be required.`}],isError:!0};let p=d?.userId||`unknown`,m=d?.chatId||null,h=JSON.stringify(t);a=Math.ceil(h.length/4);let g=
|
|
90
|
+
Re-issue the call with corrected arguments; a new approval gate will be required.`}],isError:!0};let p=d?.userId||`unknown`,m=d?.chatId||null,h=JSON.stringify(t);a=Math.ceil(h.length/4);let g=p_(e.name,t);if(!g.valid){e.name,$.error(`[${e.name}] Tool execution blocked due to limits:`,g.errors),r=`blocked`,i=g.errors.join(`; `),o=200;try{await f_.logUsage({userId:p,chatId:m,tool:e.name,requestTokens:a,responseTokens:o,totalTokens:a+o,status:r,reason:i,limitRequested:t.limit,limitApplied:null})}catch(t){$.error(`[${e.name}] Failed to log token usage:`,t)}return{content:[{type:`text`,text:`I'm sorry, but this request is too large to process efficiently. To get better results, please try:
|
|
91
91
|
|
|
92
92
|
• Using smaller numbers when asking for lists (try 10-20 items instead of larger amounts)
|
|
93
93
|
• Being more specific with your search criteria
|
|
94
94
|
• Breaking your request into smaller parts
|
|
95
95
|
|
|
96
|
-
For example, instead of asking for all customers, try asking for "customers created this month" or "customers from a specific region."`}],isError:!0}}let _=g.adjustedArgs;t.limit&&_.limit&&t.limit!==_.limit&&(s=t.limit,c=_.limit);let v=
|
|
96
|
+
For example, instead of asking for all customers, try asking for "customers created this month" or "customers from a specific region."`}],isError:!0}}let _=g.adjustedArgs;t.limit&&_.limit&&t.limit!==_.limit&&(s=t.limit,c=_.limit);let v=m_(e.name,_);$.info(`[${e.name}] Token usage assessment:`,{estimatedTokens:v.message,severity:v.severity,suggestions:v.suggestions,originalArgs:JSON.stringify(t),adjustedArgs:JSON.stringify(_)});let y=e.bulkOver?await z_(e,_):await R_(e,_),b=e.bulkOver&&y.summary.requested>0&&y.summary.succeeded===0,x=v_.processResponse(y,e.name),S=Date.now()-n;$.info(`[${e.name}] Tool execution completed in ${S}ms`);let C=typeof x==`string`?x:JSON.stringify(x,null,2);(g.warnings.length>0||v.severity===`warning`)&&(r=`truncated`,i=`Response optimized due to size limits`,C+=`
|
|
97
97
|
|
|
98
98
|
---
|
|
99
99
|
**📋 Response Summary:**
|
|
@@ -105,8 +105,8 @@ Your request returned a large amount of data, so I've shown you a summary with t
|
|
|
105
105
|
|
|
106
106
|
This helps ensure faster and more focused results.`),b&&(C=`ACTION_NOT_EXECUTED — every item in the batch failed. Do NOT report success to the user.
|
|
107
107
|
|
|
108
|
-
`+C),o=Math.ceil(C.length/4);try{await
|
|
109
|
-
Available tools:`),
|
|
108
|
+
`+C),o=Math.ceil(C.length/4);try{await f_.logUsage({userId:p,chatId:m,tool:e.name,requestTokens:a,responseTokens:o,totalTokens:a+o,status:r,reason:i,limitRequested:s,limitApplied:c})}catch(t){$.error(`[${e.name}] Failed to log token usage:`,t)}let ee=s_(e.name,y,C,_);return b?{...ee,isError:!0}:ee}catch(r){let i=Date.now()-n;$.error(`[${e.name}] Tool execution failed after ${i}ms:`,r);let l=t.__userContext,u=l?.userId||`unknown`,d=l?.chatId||null,f=`Error executing ${e.name}: ${r.message}\n\nThis might be due to:\n- Invalid parameters\n- API rate limiting\n- Network connectivity issues\n- Authentication problems\n- Token usage limits exceeded\n\nPlease check the parameters and try again with smaller limits if needed.`;o=Math.ceil(f.length/4);try{await f_.logUsage({userId:u,chatId:d,tool:e.name,requestTokens:a,responseTokens:o,totalTokens:a+o,status:`blocked`,reason:`Execution failed: ${r.message}`,limitRequested:s,limitApplied:c})}catch(t){$.error(`[${e.name}] Failed to log token usage:`,t)}return{content:[{type:`text`,text:f}],isError:!0}}})});async function nv(){let e=new Em;await __.connect(e),console.error(`Zenskar Intelligent MCP Server running on stdio`),console.error(`Loaded ${g_.tools?.length||0} tools from config`),console.error(`Response optimization: Advanced processor with config-driven optimizations enabled`),g_.tools?.length>0&&(console.error(`
|
|
109
|
+
Available tools:`),g_.tools.forEach(e=>{console.error(` • ${e.name}: ${e.description}`)})),console.error(`
|
|
110
110
|
Server ready to handle requests`)}process.on(`SIGINT`,()=>{console.error(`
|
|
111
111
|
Received SIGINT, shutting down gracefully...`),process.exit(0)}),process.on(`SIGTERM`,()=>{console.error(`
|
|
112
|
-
Received SIGTERM, shutting down gracefully...`),process.exit(0)}),
|
|
112
|
+
Received SIGTERM, shutting down gracefully...`),process.exit(0)}),nv().catch(e=>{console.error(`Server failed to start:`,e),process.exit(1)});export{};
|
package/package.json
CHANGED