mcp-zenskar 2.2.3 → 2.2.4
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/dist/mcp-config.json +496 -2
- package/dist/server.mjs +2 -2
- package/package.json +3 -2
package/dist/mcp-config.json
CHANGED
|
@@ -3044,6 +3044,77 @@
|
|
|
3044
3044
|
"name": "phases",
|
|
3045
3045
|
"description": "Array of contract phases with pricing details. Each phase includes name, start_date, end_date, phase_type, and pricings array. Defaults to empty array if omitted.",
|
|
3046
3046
|
"type": "array",
|
|
3047
|
+
"schema": {
|
|
3048
|
+
"type": "array",
|
|
3049
|
+
"items": {
|
|
3050
|
+
"type": "object",
|
|
3051
|
+
"additionalProperties": true,
|
|
3052
|
+
"properties": {
|
|
3053
|
+
"name": { "type": "string" },
|
|
3054
|
+
"start_date": { "type": "string" },
|
|
3055
|
+
"end_date": { "type": "string" },
|
|
3056
|
+
"phase_type": {
|
|
3057
|
+
"type": "string",
|
|
3058
|
+
"enum": ["active", "pause", "trial"]
|
|
3059
|
+
},
|
|
3060
|
+
"pricings": {
|
|
3061
|
+
"type": "array",
|
|
3062
|
+
"items": {
|
|
3063
|
+
"type": "object",
|
|
3064
|
+
"additionalProperties": true,
|
|
3065
|
+
"properties": {
|
|
3066
|
+
"pricing_id": { "type": "string" },
|
|
3067
|
+
"product_id": { "type": "string" },
|
|
3068
|
+
"pricing": {
|
|
3069
|
+
"type": "object",
|
|
3070
|
+
"additionalProperties": true,
|
|
3071
|
+
"required": ["pricing_data"],
|
|
3072
|
+
"properties": {
|
|
3073
|
+
"pricing_data": {
|
|
3074
|
+
"type": "object",
|
|
3075
|
+
"additionalProperties": true,
|
|
3076
|
+
"required": ["pricing_type", "currency"],
|
|
3077
|
+
"properties": {
|
|
3078
|
+
"pricing_type": {
|
|
3079
|
+
"type": "string"
|
|
3080
|
+
},
|
|
3081
|
+
"currency": {
|
|
3082
|
+
"type": "string"
|
|
3083
|
+
}
|
|
3084
|
+
}
|
|
3085
|
+
}
|
|
3086
|
+
}
|
|
3087
|
+
},
|
|
3088
|
+
"product": {
|
|
3089
|
+
"type": "object",
|
|
3090
|
+
"additionalProperties": true
|
|
3091
|
+
}
|
|
3092
|
+
}
|
|
3093
|
+
}
|
|
3094
|
+
},
|
|
3095
|
+
"features": {
|
|
3096
|
+
"type": "object",
|
|
3097
|
+
"additionalProperties": true,
|
|
3098
|
+
"required": ["pricing_data"],
|
|
3099
|
+
"properties": {
|
|
3100
|
+
"pricing_data": {
|
|
3101
|
+
"type": "object",
|
|
3102
|
+
"additionalProperties": true,
|
|
3103
|
+
"required": ["pricing_type", "currency"],
|
|
3104
|
+
"properties": {
|
|
3105
|
+
"pricing_type": {
|
|
3106
|
+
"type": "string"
|
|
3107
|
+
},
|
|
3108
|
+
"currency": {
|
|
3109
|
+
"type": "string"
|
|
3110
|
+
}
|
|
3111
|
+
}
|
|
3112
|
+
}
|
|
3113
|
+
}
|
|
3114
|
+
}
|
|
3115
|
+
}
|
|
3116
|
+
}
|
|
3117
|
+
},
|
|
3047
3118
|
"required": false,
|
|
3048
3119
|
"position": "body"
|
|
3049
3120
|
},
|
|
@@ -3182,6 +3253,77 @@
|
|
|
3182
3253
|
"name": "phases",
|
|
3183
3254
|
"description": "Array of contract phases. Each phase needs at minimum: name, start_date, end_date. Include pricings array if the phase has pricing. Defaults to empty array if omitted.",
|
|
3184
3255
|
"type": "array",
|
|
3256
|
+
"schema": {
|
|
3257
|
+
"type": "array",
|
|
3258
|
+
"items": {
|
|
3259
|
+
"type": "object",
|
|
3260
|
+
"additionalProperties": true,
|
|
3261
|
+
"properties": {
|
|
3262
|
+
"name": { "type": "string" },
|
|
3263
|
+
"start_date": { "type": "string" },
|
|
3264
|
+
"end_date": { "type": "string" },
|
|
3265
|
+
"phase_type": {
|
|
3266
|
+
"type": "string",
|
|
3267
|
+
"enum": ["active", "pause", "trial"]
|
|
3268
|
+
},
|
|
3269
|
+
"pricings": {
|
|
3270
|
+
"type": "array",
|
|
3271
|
+
"items": {
|
|
3272
|
+
"type": "object",
|
|
3273
|
+
"additionalProperties": true,
|
|
3274
|
+
"properties": {
|
|
3275
|
+
"pricing_id": { "type": "string" },
|
|
3276
|
+
"product_id": { "type": "string" },
|
|
3277
|
+
"pricing": {
|
|
3278
|
+
"type": "object",
|
|
3279
|
+
"additionalProperties": true,
|
|
3280
|
+
"required": ["pricing_data"],
|
|
3281
|
+
"properties": {
|
|
3282
|
+
"pricing_data": {
|
|
3283
|
+
"type": "object",
|
|
3284
|
+
"additionalProperties": true,
|
|
3285
|
+
"required": ["pricing_type", "currency"],
|
|
3286
|
+
"properties": {
|
|
3287
|
+
"pricing_type": {
|
|
3288
|
+
"type": "string"
|
|
3289
|
+
},
|
|
3290
|
+
"currency": {
|
|
3291
|
+
"type": "string"
|
|
3292
|
+
}
|
|
3293
|
+
}
|
|
3294
|
+
}
|
|
3295
|
+
}
|
|
3296
|
+
},
|
|
3297
|
+
"product": {
|
|
3298
|
+
"type": "object",
|
|
3299
|
+
"additionalProperties": true
|
|
3300
|
+
}
|
|
3301
|
+
}
|
|
3302
|
+
}
|
|
3303
|
+
},
|
|
3304
|
+
"features": {
|
|
3305
|
+
"type": "object",
|
|
3306
|
+
"additionalProperties": true,
|
|
3307
|
+
"required": ["pricing_data"],
|
|
3308
|
+
"properties": {
|
|
3309
|
+
"pricing_data": {
|
|
3310
|
+
"type": "object",
|
|
3311
|
+
"additionalProperties": true,
|
|
3312
|
+
"required": ["pricing_type", "currency"],
|
|
3313
|
+
"properties": {
|
|
3314
|
+
"pricing_type": {
|
|
3315
|
+
"type": "string"
|
|
3316
|
+
},
|
|
3317
|
+
"currency": {
|
|
3318
|
+
"type": "string"
|
|
3319
|
+
}
|
|
3320
|
+
}
|
|
3321
|
+
}
|
|
3322
|
+
}
|
|
3323
|
+
}
|
|
3324
|
+
}
|
|
3325
|
+
}
|
|
3326
|
+
},
|
|
3185
3327
|
"required": false,
|
|
3186
3328
|
"position": "body"
|
|
3187
3329
|
},
|
|
@@ -3388,6 +3530,41 @@
|
|
|
3388
3530
|
"name": "pricings",
|
|
3389
3531
|
"description": "Array of pricing configurations for this phase.",
|
|
3390
3532
|
"type": "array",
|
|
3533
|
+
"schema": {
|
|
3534
|
+
"type": "array",
|
|
3535
|
+
"items": {
|
|
3536
|
+
"type": "object",
|
|
3537
|
+
"additionalProperties": true,
|
|
3538
|
+
"properties": {
|
|
3539
|
+
"pricing_id": { "type": "string" },
|
|
3540
|
+
"product_id": { "type": "string" },
|
|
3541
|
+
"pricing": {
|
|
3542
|
+
"type": "object",
|
|
3543
|
+
"additionalProperties": true,
|
|
3544
|
+
"required": ["pricing_data"],
|
|
3545
|
+
"properties": {
|
|
3546
|
+
"pricing_data": {
|
|
3547
|
+
"type": "object",
|
|
3548
|
+
"additionalProperties": true,
|
|
3549
|
+
"required": ["pricing_type", "currency"],
|
|
3550
|
+
"properties": {
|
|
3551
|
+
"pricing_type": {
|
|
3552
|
+
"type": "string"
|
|
3553
|
+
},
|
|
3554
|
+
"currency": {
|
|
3555
|
+
"type": "string"
|
|
3556
|
+
}
|
|
3557
|
+
}
|
|
3558
|
+
}
|
|
3559
|
+
}
|
|
3560
|
+
},
|
|
3561
|
+
"product": {
|
|
3562
|
+
"type": "object",
|
|
3563
|
+
"additionalProperties": true
|
|
3564
|
+
}
|
|
3565
|
+
}
|
|
3566
|
+
}
|
|
3567
|
+
},
|
|
3391
3568
|
"required": false,
|
|
3392
3569
|
"position": "body"
|
|
3393
3570
|
},
|
|
@@ -3456,7 +3633,21 @@
|
|
|
3456
3633
|
"schema": {
|
|
3457
3634
|
"type": "object",
|
|
3458
3635
|
"additionalProperties": true,
|
|
3636
|
+
"required": ["pricing_data"],
|
|
3459
3637
|
"properties": {
|
|
3638
|
+
"pricing_data": {
|
|
3639
|
+
"type": "object",
|
|
3640
|
+
"additionalProperties": true,
|
|
3641
|
+
"required": ["pricing_type", "currency"],
|
|
3642
|
+
"properties": {
|
|
3643
|
+
"pricing_type": {
|
|
3644
|
+
"type": "string"
|
|
3645
|
+
},
|
|
3646
|
+
"currency": {
|
|
3647
|
+
"type": "string"
|
|
3648
|
+
}
|
|
3649
|
+
}
|
|
3650
|
+
},
|
|
3460
3651
|
"payment_terms": {
|
|
3461
3652
|
"type": "array",
|
|
3462
3653
|
"items": {
|
|
@@ -5230,6 +5421,36 @@
|
|
|
5230
5421
|
"name": "pricing_data",
|
|
5231
5422
|
"description": "Pricing data object (required). MUST include 'pricing_type' discriminator AND 'currency' (ISO 4217, e.g. 'USD'). 'unit_amount' is in MAJOR currency units (float) — 3 means $3, NOT 300 cents. Do NOT convert to cents. Supported pricing_type values with examples: flat_fee: {pricing_type:'flat_fee', unit_amount:100, currency:'USD'}. per_unit: {pricing_type:'per_unit', unit_amount:3, currency:'USD'}. tiered: {pricing_type:'tiered', unit_amount:[10,5], up_to:[100,null], currency:'USD'}. volume: {pricing_type:'volume', unit_amount:[10,5], up_to:[100,null], currency:'USD'}. percent: {pricing_type:'percent', percentage:5.0, currency:'USD'}. package: {pricing_type:'package', package_size:10, unit_amount:50, currency:'USD'}. step: {pricing_type:'step', unit_amount:[...], up_to:[...], currency:'USD'}. matrix: {pricing_type:'matrix', dimensions:[...], values:[...], currency:'USD'}. Optional inside pricing_data for per_unit: 'proration_type' ('day_based'|'cadence_based'), 'charge_full_amount' (bool).",
|
|
5232
5423
|
"type": "object",
|
|
5424
|
+
"schema": {
|
|
5425
|
+
"type": "object",
|
|
5426
|
+
"additionalProperties": true,
|
|
5427
|
+
"required": ["pricing_type", "currency"],
|
|
5428
|
+
"properties": {
|
|
5429
|
+
"pricing_type": {
|
|
5430
|
+
"type": "string",
|
|
5431
|
+
"enum": [
|
|
5432
|
+
"percent",
|
|
5433
|
+
"per_unit",
|
|
5434
|
+
"volume",
|
|
5435
|
+
"volume_with_flat_fee",
|
|
5436
|
+
"tiered",
|
|
5437
|
+
"tiered_with_flat_fee",
|
|
5438
|
+
"step",
|
|
5439
|
+
"matrix",
|
|
5440
|
+
"custom_tiered",
|
|
5441
|
+
"package",
|
|
5442
|
+
"flat_fee",
|
|
5443
|
+
"features",
|
|
5444
|
+
"two_dimensional_tiered",
|
|
5445
|
+
"custom_pricing",
|
|
5446
|
+
"bundle"
|
|
5447
|
+
]
|
|
5448
|
+
},
|
|
5449
|
+
"currency": {
|
|
5450
|
+
"type": "string"
|
|
5451
|
+
}
|
|
5452
|
+
}
|
|
5453
|
+
},
|
|
5233
5454
|
"required": true,
|
|
5234
5455
|
"position": "body"
|
|
5235
5456
|
},
|
|
@@ -5237,13 +5458,65 @@
|
|
|
5237
5458
|
"name": "quantity",
|
|
5238
5459
|
"description": "Quantity configuration (REQUIRED — ask the user; do not omit). Top-level object, NOT inside pricing_data. Shape: {type: 'fixed'|'metered', quantity?: number, unit?: string, aggregate_id?: UUID}. 'fixed' = static quantity (e.g. seats); also set 'unit' (label like 'user') and 'quantity' (number). 'metered' = consumption tracked via a billable metric; set aggregate_id to the billable-metric UUID. Omitting this object causes the UI to show 0 for billing metric.",
|
|
5239
5460
|
"type": "object",
|
|
5461
|
+
"schema": {
|
|
5462
|
+
"oneOf": [
|
|
5463
|
+
{
|
|
5464
|
+
"type": "object",
|
|
5465
|
+
"additionalProperties": true,
|
|
5466
|
+
"required": ["type", "quantity", "unit"],
|
|
5467
|
+
"properties": {
|
|
5468
|
+
"type": {
|
|
5469
|
+
"type": "string",
|
|
5470
|
+
"enum": ["fixed"]
|
|
5471
|
+
},
|
|
5472
|
+
"quantity": {
|
|
5473
|
+
"type": "number"
|
|
5474
|
+
},
|
|
5475
|
+
"unit": {
|
|
5476
|
+
"type": "string"
|
|
5477
|
+
}
|
|
5478
|
+
}
|
|
5479
|
+
},
|
|
5480
|
+
{
|
|
5481
|
+
"type": "object",
|
|
5482
|
+
"additionalProperties": true,
|
|
5483
|
+
"required": ["type", "aggregate_id"],
|
|
5484
|
+
"properties": {
|
|
5485
|
+
"type": {
|
|
5486
|
+
"type": "string",
|
|
5487
|
+
"enum": ["metered"]
|
|
5488
|
+
},
|
|
5489
|
+
"aggregate_id": {
|
|
5490
|
+
"type": "string"
|
|
5491
|
+
},
|
|
5492
|
+
"unit": {
|
|
5493
|
+
"type": "string"
|
|
5494
|
+
}
|
|
5495
|
+
}
|
|
5496
|
+
}
|
|
5497
|
+
]
|
|
5498
|
+
},
|
|
5240
5499
|
"required": true,
|
|
5241
5500
|
"position": "body"
|
|
5242
5501
|
},
|
|
5243
5502
|
{
|
|
5244
5503
|
"name": "billing_period",
|
|
5245
|
-
"description": "Billing cadence (REQUIRED — ask the user; do not omit).
|
|
5504
|
+
"description": "Billing cadence (REQUIRED — ask the user; do not omit). Backend shape: {cadence: ISO-8601 duration ('P1M'=monthly, 'P3M'=quarterly, 'P1Y'=annually), offset: 'prepaid'|'postpaid'}. Both fields needed. Example: {\"cadence\":\"P1M\",\"offset\":\"prepaid\"}. Omitting this causes the UI to render 'Undefined- Every Undefined Undefined'.",
|
|
5246
5505
|
"type": "object",
|
|
5506
|
+
"schema": {
|
|
5507
|
+
"type": "object",
|
|
5508
|
+
"additionalProperties": true,
|
|
5509
|
+
"required": ["cadence", "offset"],
|
|
5510
|
+
"properties": {
|
|
5511
|
+
"cadence": {
|
|
5512
|
+
"type": "string"
|
|
5513
|
+
},
|
|
5514
|
+
"offset": {
|
|
5515
|
+
"type": "string",
|
|
5516
|
+
"enum": ["prepaid", "postpaid"]
|
|
5517
|
+
}
|
|
5518
|
+
}
|
|
5519
|
+
},
|
|
5247
5520
|
"required": true,
|
|
5248
5521
|
"position": "body"
|
|
5249
5522
|
},
|
|
@@ -5363,6 +5636,23 @@
|
|
|
5363
5636
|
"name": "schedule",
|
|
5364
5637
|
"description": "Plan-level schedule (required). Object: {duration: ISO-8601 e.g. 'P1Y'|'P1M', start_offset?: ISO-8601 e.g. 'P0D', trigger_type?: 'time_based'}. Example: {\"duration\":\"P1Y\",\"start_offset\":\"P0D\"}.",
|
|
5365
5638
|
"type": "object",
|
|
5639
|
+
"schema": {
|
|
5640
|
+
"type": "object",
|
|
5641
|
+
"additionalProperties": true,
|
|
5642
|
+
"required": ["duration"],
|
|
5643
|
+
"properties": {
|
|
5644
|
+
"duration": {
|
|
5645
|
+
"type": "string"
|
|
5646
|
+
},
|
|
5647
|
+
"start_offset": {
|
|
5648
|
+
"type": "string"
|
|
5649
|
+
},
|
|
5650
|
+
"trigger_type": {
|
|
5651
|
+
"type": "string",
|
|
5652
|
+
"enum": ["event_based", "time_based"]
|
|
5653
|
+
}
|
|
5654
|
+
}
|
|
5655
|
+
},
|
|
5366
5656
|
"required": true,
|
|
5367
5657
|
"position": "body"
|
|
5368
5658
|
},
|
|
@@ -5375,8 +5665,212 @@
|
|
|
5375
5665
|
},
|
|
5376
5666
|
{
|
|
5377
5667
|
"name": "phases",
|
|
5378
|
-
"description": "Array of plan phases (REQUIRED — must be non-empty). Each phase: {name: string (required), schedule: {duration, start_offset?, trigger_type?} (required), order: int (required, 0-indexed), description?: string, features?: CreateProductPricingRequestSchema (one-off phase-level pricing/features), pricings?: [{schedule, pricing_id?, product_id?, pricing?: CreateProductPricingRequestSchema, product?: CreateProductRequestSchema}] (per-product pricings)}. Each phase must have features OR a non-empty pricings array. Minimal example: [{\"name\":\"Phase 1\",\"schedule\":{\"duration\":\"P1Y\"},\"order\":0,\"features\":{\"pricing_data\":{\"pricing_type\":\"features\"}}}].",
|
|
5668
|
+
"description": "Array of plan phases (REQUIRED — must be non-empty). Each phase: {name: string (required), schedule: {duration, start_offset?, trigger_type?} (required), order: int (required, 0-indexed), description?: string, features?: CreateProductPricingRequestSchema (one-off phase-level pricing/features), pricings?: [{schedule, pricing_id?, product_id?, pricing?: CreateProductPricingRequestSchema, product?: CreateProductRequestSchema}] (per-product pricings)}. Each phase must have features OR a non-empty pricings array. Minimal example: [{\"name\":\"Phase 1\",\"schedule\":{\"duration\":\"P1Y\"},\"order\":0,\"features\":{\"pricing_data\":{\"pricing_type\":\"features\",\"currency\":\"USD\"}}}].",
|
|
5379
5669
|
"type": "array",
|
|
5670
|
+
"schema": {
|
|
5671
|
+
"type": "array",
|
|
5672
|
+
"minItems": 1,
|
|
5673
|
+
"items": {
|
|
5674
|
+
"anyOf": [
|
|
5675
|
+
{
|
|
5676
|
+
"type": "object",
|
|
5677
|
+
"additionalProperties": true,
|
|
5678
|
+
"required": ["name", "schedule", "order", "features"],
|
|
5679
|
+
"properties": {
|
|
5680
|
+
"name": { "type": "string" },
|
|
5681
|
+
"schedule": {
|
|
5682
|
+
"type": "object",
|
|
5683
|
+
"additionalProperties": true,
|
|
5684
|
+
"required": ["duration"],
|
|
5685
|
+
"properties": {
|
|
5686
|
+
"duration": { "type": "string" },
|
|
5687
|
+
"start_offset": { "type": "string" },
|
|
5688
|
+
"trigger_type": {
|
|
5689
|
+
"type": "string",
|
|
5690
|
+
"enum": ["event_based", "time_based"]
|
|
5691
|
+
}
|
|
5692
|
+
}
|
|
5693
|
+
},
|
|
5694
|
+
"order": { "type": "integer" },
|
|
5695
|
+
"features": {
|
|
5696
|
+
"type": "object",
|
|
5697
|
+
"additionalProperties": true,
|
|
5698
|
+
"required": ["pricing_data"],
|
|
5699
|
+
"properties": {
|
|
5700
|
+
"pricing_data": {
|
|
5701
|
+
"type": "object",
|
|
5702
|
+
"additionalProperties": true,
|
|
5703
|
+
"required": ["pricing_type", "currency"],
|
|
5704
|
+
"properties": {
|
|
5705
|
+
"pricing_type": { "type": "string" },
|
|
5706
|
+
"currency": { "type": "string" }
|
|
5707
|
+
}
|
|
5708
|
+
}
|
|
5709
|
+
}
|
|
5710
|
+
}
|
|
5711
|
+
}
|
|
5712
|
+
},
|
|
5713
|
+
{
|
|
5714
|
+
"type": "object",
|
|
5715
|
+
"additionalProperties": true,
|
|
5716
|
+
"required": ["name", "schedule", "order", "pricings"],
|
|
5717
|
+
"properties": {
|
|
5718
|
+
"name": { "type": "string" },
|
|
5719
|
+
"schedule": {
|
|
5720
|
+
"type": "object",
|
|
5721
|
+
"additionalProperties": true,
|
|
5722
|
+
"required": ["duration"],
|
|
5723
|
+
"properties": {
|
|
5724
|
+
"duration": { "type": "string" },
|
|
5725
|
+
"start_offset": { "type": "string" },
|
|
5726
|
+
"trigger_type": {
|
|
5727
|
+
"type": "string",
|
|
5728
|
+
"enum": ["event_based", "time_based"]
|
|
5729
|
+
}
|
|
5730
|
+
}
|
|
5731
|
+
},
|
|
5732
|
+
"order": { "type": "integer" },
|
|
5733
|
+
"pricings": {
|
|
5734
|
+
"type": "array",
|
|
5735
|
+
"minItems": 1,
|
|
5736
|
+
"items": {
|
|
5737
|
+
"oneOf": [
|
|
5738
|
+
{
|
|
5739
|
+
"type": "object",
|
|
5740
|
+
"additionalProperties": true,
|
|
5741
|
+
"required": [
|
|
5742
|
+
"schedule",
|
|
5743
|
+
"pricing_id",
|
|
5744
|
+
"product_id"
|
|
5745
|
+
],
|
|
5746
|
+
"properties": {
|
|
5747
|
+
"schedule": {
|
|
5748
|
+
"type": "object",
|
|
5749
|
+
"additionalProperties": true,
|
|
5750
|
+
"required": ["duration"],
|
|
5751
|
+
"properties": {
|
|
5752
|
+
"duration": { "type": "string" },
|
|
5753
|
+
"start_offset": { "type": "string" },
|
|
5754
|
+
"trigger_type": {
|
|
5755
|
+
"type": "string",
|
|
5756
|
+
"enum": ["event_based", "time_based"]
|
|
5757
|
+
}
|
|
5758
|
+
}
|
|
5759
|
+
},
|
|
5760
|
+
"pricing_id": { "type": "string" },
|
|
5761
|
+
"product_id": { "type": "string" }
|
|
5762
|
+
}
|
|
5763
|
+
},
|
|
5764
|
+
{
|
|
5765
|
+
"type": "object",
|
|
5766
|
+
"additionalProperties": true,
|
|
5767
|
+
"required": ["schedule", "pricing_id", "product"],
|
|
5768
|
+
"properties": {
|
|
5769
|
+
"schedule": {
|
|
5770
|
+
"type": "object",
|
|
5771
|
+
"additionalProperties": true,
|
|
5772
|
+
"required": ["duration"],
|
|
5773
|
+
"properties": {
|
|
5774
|
+
"duration": { "type": "string" },
|
|
5775
|
+
"start_offset": { "type": "string" },
|
|
5776
|
+
"trigger_type": {
|
|
5777
|
+
"type": "string",
|
|
5778
|
+
"enum": ["event_based", "time_based"]
|
|
5779
|
+
}
|
|
5780
|
+
}
|
|
5781
|
+
},
|
|
5782
|
+
"pricing_id": { "type": "string" },
|
|
5783
|
+
"product": {
|
|
5784
|
+
"type": "object",
|
|
5785
|
+
"additionalProperties": true
|
|
5786
|
+
}
|
|
5787
|
+
}
|
|
5788
|
+
},
|
|
5789
|
+
{
|
|
5790
|
+
"type": "object",
|
|
5791
|
+
"additionalProperties": true,
|
|
5792
|
+
"required": ["schedule", "pricing", "product_id"],
|
|
5793
|
+
"properties": {
|
|
5794
|
+
"schedule": {
|
|
5795
|
+
"type": "object",
|
|
5796
|
+
"additionalProperties": true,
|
|
5797
|
+
"required": ["duration"],
|
|
5798
|
+
"properties": {
|
|
5799
|
+
"duration": { "type": "string" },
|
|
5800
|
+
"start_offset": { "type": "string" },
|
|
5801
|
+
"trigger_type": {
|
|
5802
|
+
"type": "string",
|
|
5803
|
+
"enum": ["event_based", "time_based"]
|
|
5804
|
+
}
|
|
5805
|
+
}
|
|
5806
|
+
},
|
|
5807
|
+
"pricing": {
|
|
5808
|
+
"type": "object",
|
|
5809
|
+
"additionalProperties": true,
|
|
5810
|
+
"required": ["pricing_data"],
|
|
5811
|
+
"properties": {
|
|
5812
|
+
"pricing_data": {
|
|
5813
|
+
"type": "object",
|
|
5814
|
+
"additionalProperties": true,
|
|
5815
|
+
"required": ["pricing_type", "currency"],
|
|
5816
|
+
"properties": {
|
|
5817
|
+
"pricing_type": { "type": "string" },
|
|
5818
|
+
"currency": { "type": "string" }
|
|
5819
|
+
}
|
|
5820
|
+
}
|
|
5821
|
+
}
|
|
5822
|
+
},
|
|
5823
|
+
"product_id": { "type": "string" }
|
|
5824
|
+
}
|
|
5825
|
+
},
|
|
5826
|
+
{
|
|
5827
|
+
"type": "object",
|
|
5828
|
+
"additionalProperties": true,
|
|
5829
|
+
"required": ["schedule", "pricing", "product"],
|
|
5830
|
+
"properties": {
|
|
5831
|
+
"schedule": {
|
|
5832
|
+
"type": "object",
|
|
5833
|
+
"additionalProperties": true,
|
|
5834
|
+
"required": ["duration"],
|
|
5835
|
+
"properties": {
|
|
5836
|
+
"duration": { "type": "string" },
|
|
5837
|
+
"start_offset": { "type": "string" },
|
|
5838
|
+
"trigger_type": {
|
|
5839
|
+
"type": "string",
|
|
5840
|
+
"enum": ["event_based", "time_based"]
|
|
5841
|
+
}
|
|
5842
|
+
}
|
|
5843
|
+
},
|
|
5844
|
+
"pricing": {
|
|
5845
|
+
"type": "object",
|
|
5846
|
+
"additionalProperties": true,
|
|
5847
|
+
"required": ["pricing_data"],
|
|
5848
|
+
"properties": {
|
|
5849
|
+
"pricing_data": {
|
|
5850
|
+
"type": "object",
|
|
5851
|
+
"additionalProperties": true,
|
|
5852
|
+
"required": ["pricing_type", "currency"],
|
|
5853
|
+
"properties": {
|
|
5854
|
+
"pricing_type": { "type": "string" },
|
|
5855
|
+
"currency": { "type": "string" }
|
|
5856
|
+
}
|
|
5857
|
+
}
|
|
5858
|
+
}
|
|
5859
|
+
},
|
|
5860
|
+
"product": {
|
|
5861
|
+
"type": "object",
|
|
5862
|
+
"additionalProperties": true
|
|
5863
|
+
}
|
|
5864
|
+
}
|
|
5865
|
+
}
|
|
5866
|
+
]
|
|
5867
|
+
}
|
|
5868
|
+
}
|
|
5869
|
+
}
|
|
5870
|
+
}
|
|
5871
|
+
]
|
|
5872
|
+
}
|
|
5873
|
+
},
|
|
5380
5874
|
"required": true,
|
|
5381
5875
|
"position": "body"
|
|
5382
5876
|
}
|
package/dist/server.mjs
CHANGED
|
@@ -75,9 +75,9 @@ 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),Tm(t)}clear(){this._buffer=void 0}};function Tm(e){return hl.parse(JSON.parse(e))}function Em(e){return JSON.stringify(e)+`
|
|
76
76
|
`}var Dm=class{constructor(e=c.stdin,t=c.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new wm,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=Em(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};const Om=[];for(let e=0;e<256;++e)Om.push((e+256).toString(16).slice(1));function km(e,t=0){return(Om[e[t+0]]+Om[e[t+1]]+Om[e[t+2]]+Om[e[t+3]]+`-`+Om[e[t+4]]+Om[e[t+5]]+`-`+Om[e[t+6]]+Om[e[t+7]]+`-`+Om[e[t+8]]+Om[e[t+9]]+`-`+Om[e[t+10]]+Om[e[t+11]]+Om[e[t+12]]+Om[e[t+13]]+Om[e[t+14]]+Om[e[t+15]]).toLowerCase()}const Am=new Uint8Array(16);function jm(){return crypto.getRandomValues(Am)}function Mm(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():Nm(e,t,n)}function Nm(e,t,n){e||={};let r=e.random??e.rng?.()??jm();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 km(r)}var Pm=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 Fm(e){if(!e||typeof e!=`object`||Array.isArray(e))return rc();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 _c(t)}let t,n=Array.isArray(e.type)?e.type[0]:e.type;if(n===`integer`||n===`number`)t=n===`integer`?R().int():R(),typeof e.minimum==`number`&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&(t=t.max(e.maximum));else if(n===`boolean`)t=$s();else if(n===`array`)t=B(Fm(e.items));else if(n===`object`){let n=new Set(Array.isArray(e.required)?e.required:[]),r=e.properties||{},i={};Object.entries(r).forEach(([e,t])=>{let r=Fm(t);n.has(e)||(r=r.optional()),i[e]=r}),t=e.additionalProperties===!1?V(i):V(i).passthrough()}else t=I();return e.description&&(t=t.describe(e.description)),t}function Im(e){let t={};return e.forEach(e=>{let n;n=e.schema?Fm(e.schema):e.type===`integer`||e.type===`number`?R():e.type===`boolean`?$s():e.type===`object`?U(rc()):e.type===`array`?B(rc()):e.type===`datetime`?H([I(),R()]):I(),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=V({userId:I().optional(),authorization:I().optional(),organization:I().optional(),apiKey:I().optional(),headers:V({}).optional(),approval:V({approved:$s(),token:I().optional(),modifiedArguments:U(rc()).optional(),originalArguments:U(rc()).optional(),toolName:I().optional()}).optional()}).optional().describe(`Internal user context for multi-tenant authentication and approval workflow`),t}function Lm(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 Rm=new Set([`getInvoiceSummary`,`getCustomerBalance`,`getPaymentStatus`]),zm={listCustomers:{shape:`customer-table`,noun:`customer`,toPayload:Hm,threshold:0},listInvoices:{shape:`invoice-table`,noun:`invoice`,toPayload:Um,threshold:0},getInvoiceLineItems:{shape:`invoice-line-items`,noun:`line item`,toPayload:Gm,threshold:0},listAllPayments:{shape:`payment-table`,noun:`payment`,toPayload:Xm,threshold:0},listCreditNotes:{shape:`credit-note-table`,noun:`credit note`,toPayload:Qm,threshold:0},listContracts:{shape:`contract-table`,noun:`contract`,toPayload:eh,threshold:0},getCustomerById:{shape:`customer-detail`,noun:`customer`,toPayload:nh,threshold:0},getInvoiceById:{shape:`invoice-detail`,noun:`invoice`,toPayload:rh,threshold:0},getContractById:{shape:`contract-detail`,noun:`contract`,toPayload:ih,threshold:0},getCreditNoteById:{shape:`credit-note-detail`,noun:`credit note`,toPayload:lh,threshold:0},listProducts:{shape:`product-table`,noun:`product`,toPayload:uh,threshold:0},listPlans:{shape:`plan-table`,noun:`plan`,toPayload:fh,threshold:0},listJournalEntries:{shape:`journal-table`,noun:`journal entry`,toPayload:mh,threshold:0},listJobs:{shape:`job-table`,noun:`job`,toPayload:gh,threshold:0},listContacts:{shape:`contact-table`,noun:`contact`,toPayload:vh,threshold:0},listRawMetrics:{shape:`raw-metric-table`,noun:`raw metric`,toPayload:bh,threshold:0},listAggregates:{shape:`aggregate-table`,noun:`aggregate`,toPayload:Sh,threshold:0},listCustomerAddresses:{shape:`address-list`,noun:`address`,toPayload:wh,threshold:0},listPaymentMethods:{shape:`payment-method-list`,noun:`payment method`,toPayload:Eh,threshold:0},listBusinessEntities:{shape:`entity-table`,noun:`business entity`,toPayload:Oh,threshold:0},listEntitlements:{shape:`entitlement-table`,noun:`entitlement`,toPayload:Ah,threshold:0},getInvoicePreviewHtml:{shape:`invoice-preview`,noun:`invoice preview`,toPayload:Ih,threshold:0}},Bm=Object.freeze([`app`]);function Vm(e){return`ui://zenskar/app.html`}function Hm(e,t){let n=Q(e),r=Mh(n,[`customers`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(Ym),total:i,cursor:{next:o,prev:s},scope:c}}function Q(e){return e&&typeof e==`object`&&e.api_response&&typeof e.api_response==`object`?e.api_response:e||{}}function Um(e,t){let n=Q(e),r=Mh(n,[`invoices`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(n,[`cursor`,`pagination`])||{},o=a.next??n.next??null,s=a.prev??n.previous??null;return{invoices:r.map(Wm),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 Wm(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:Fh(e.net_invoice_total??e.invoice_total),amount_due:Fh(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 Gm(e,t){let n=Q(e),r=Array.isArray(n.lines)?n.lines:Array.isArray(n)?n:[],i=Fh(n.total),a=Km(r)||`USD`;return{invoice_id:t&&t.invoiceId?String(t.invoiceId):void 0,total:i,currency:a,lines:r.map(qm)}}function Km(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 qm(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:Jm(e.subtotal),quantity:Jm(e.quantity),price:e.price?Jm(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 Jm(e){return e?{value:Fh(e.value),unit:e.unit??null,display:e.display??null}:{value:null,unit:null,display:null}}function Ym(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 Xm(e,t){let n=Q(e),r=Mh(n,[`payments`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(Zm),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0,default_currency:`USD`}}function Zm(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:Fh(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 Qm(e,t){let n=Q(e),r=Mh(n,[`credit_notes`,`creditNotes`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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($m),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0,default_currency:`USD`}}function $m(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:Fh(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 eh(e,t){let n=Q(e),r=Mh(n,[`contracts`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(th),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0}}function th(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 nh(e){let t=Q(e),n=t.customer??t,r=Ym(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 rh(e){let t=Q(e),n=t.invoice??t,r=Wm(n),i=n.customer,a=n.contract;return{invoice:{...r,paid_amount:Fh(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 ih(e){let t=Q(e),n=t.contract??t,r=th(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(ah)}}function ah(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||Fh(e.product_count),pricings:n.map(sh)}}function oh(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 sh(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:oh(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:ch(t)}}function ch(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?Lm(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?Lm(e.trigger_event):``,r=e.expires_at?`, expires ${Lm(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?Lm(e.trigger_event):``;t.push({type:`Consumption`,label:e.label??null,summary:`${n} (${Lm(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 lh(e){let t=Q(e),n=t.credit_note??t.creditNote??t,r=$m(n),i=n.customer,a=n.invoice;return{credit_note:{...r,line_items_url:n.line_items_url??null,credits_returned:Fh(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 uh(e,t){let n=Q(e),r=Mh(n,[`products`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(dh),total:i,cursor:{next:o,prev:s},scope:c}}function dh(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 fh(e,t){let n=Q(e),r=Mh(n,[`plans`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(ph),total:i,cursor:{next:o,prev:s},scope:c}}function ph(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:Fh(e.plan_version),created_at:e.created_at??null}}function mh(e,t){let n=Q(e),r=Mh(n,[`entries`,`journal_entries`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(hh),total:i,cursor:{next:o,prev:s},scope:c,default_currency:`USD`}}function hh(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 gh(e,t){let n=Q(e),r=Mh(n,[`jobs`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(_h),total:i,cursor:{next:o,prev:s},scope:c,status_counts:l}}function _h(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 vh(e,t){let n=Q(e),r=Mh(n,[`contacts`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(yh),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0}}function yh(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 bh(e,t){let n=Q(e),r=Mh(n,[`raw_metrics`,`rawmetrics`,`rawMetrics`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(xh),total:i,cursor:{next:o,prev:s},scope:c}}function xh(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 Sh(e,t){let n=Q(e),r=Mh(n,[`aggregates`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(Ch),total:i,cursor:{next:o,prev:s},scope:c}}function Ch(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 wh(e,t){let n=Mh(Q(e),[`addresses`,`data`,`results`]);return{customer_id:t&&t.customerId?String(t.customerId):void 0,addresses:n.map(Th),total:n.length}}function Th(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 Eh(e,t){let n=Mh(Q(e),[`payment_methods`,`paymentMethods`,`data`,`results`]);return{customer_id:t&&t.customerId?String(t.customerId):void 0,payment_methods:n.map(Dh),total:n.length}}function Dh(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:Fh(t.exp_month??e.exp_month),exp_year:Fh(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 Oh(e,t){let n=Q(e),r=Mh(n,[`business_entities`,`businessEntities`,`entities`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(kh),total:i,cursor:{next:o,prev:s}}}function kh(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 Ah(e,t){let n=Q(e),r=Mh(n,[`entitlements`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(jh),total:i,cursor:{next:o,prev:s},scope:c}}function jh(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 Mh(e,t){if(Array.isArray(e))return e;for(let n of t)if(e&&Array.isArray(e[n]))return e[n];return[]}function Nh(e,t){for(let n of t)if(e&&e[n]&&typeof e[n]==`object`)return e[n];return null}function Ph(e,t){for(let n of t)if(e&&Number.isFinite(e[n]))return e[n];return null}function Fh(e){return Number.isFinite(e)?e:null}function Ih(e,t){let n=Q(e);return{html:n.html??(typeof n==`string`?n:``),invoice_id:t&&t.invoiceId?String(t.invoiceId):void 0}}function Lh(e){if(Rm.has(e))return{mode:`text-only`};let t=zm[e];return t?{mode:`ui`,...t}:{mode:`unmapped`}}const Rh=a(s(import.meta.url)),zh=[o(Rh,`..`,`..`,`..`,`dist`,`ui`),o(Rh,`ui`)];function Bh(e){for(let t of zh){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 Vh(){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 Hh(){let e={prefersBorder:!0},t=Vh();return t.length>0&&(e.csp={connectDomains:t,resourceDomains:t}),e}function Uh(e){for(let t of Bm){let n=Vm(t);e.registerResource(`zenskar-app`,n,{},async()=>({contents:[{uri:n,mimeType:`text/html;profile=mcp-app`,text:Bh(t),_meta:{"openai/widgetPrefersBorder":!0,ui:Hh()}}]}))}}const Wh=[`claude-code`,`cline`,`roo-code`,`continue`,`codex`,`windsurf`,`zed`,`aider`,`copilot`,`gemini-cli`],Gh=[`claude-desktop`,`claude-ai`,`chatgpt`,`mcp-inspector`,`toon`,`cursor`];let Kh=null,qh=null;function Jh(e){Kh=e?String(e).toLowerCase().trim():null}function Yh(e){qh=e}function Xh(){if(Kh==null&&qh){let e=qh();e&&Jh(e)}return Kh}function Zh(e){let t=(e??Kh??``).toLowerCase().trim();return t?Wh.some(e=>t.includes(e))?`coding-agent`:Gh.some(e=>t.includes(e))?`widget-host`:`default`:`default`}const Qh={comma:`,`,tab:` `,pipe:`|`}.comma;function $h(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}function eg(e){return e===`true`||e===`false`||e===`null`}function tg(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 tg(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(tg);if(e instanceof Set)return Array.from(e).map(tg);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),tg(t)]));if(og(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&(t[n]=tg(e[n]));return t}return null}function ng(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function rg(e){return Array.isArray(e)}function ig(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ag(e){return Object.keys(e).length===0}function og(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function sg(e){return e.length===0||e.every(e=>ng(e))}function cg(e){return e.length===0||e.every(e=>rg(e))}function lg(e){return e.length===0||e.every(e=>ig(e))}const ug=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,dg=/^0\d+$/;function fg(e){return/^[A-Z_][\w.]*$/i.test(e)}function pg(e){return/^[A-Z_]\w*$/i.test(e)}function mg(e,t=Qh){return!(!e||e!==e.trim()||eg(e)||hg(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\n\r\t]/.test(e)||e.includes(t)||e.startsWith(`-`))}function hg(e){return ug.test(e)||dg.test(e)}function gg(e,t,n,r,i,a,o){if(r.keyFolding!==`safe`||!ig(t))return;let{segments:s,tail:c,leafValue:l}=_g(e,t,o??r.flattenDepth);if(s.length<2||!s.every(e=>pg(e)))return;let u=vg(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 _g(e,t,n){let r=[e],i=t;for(;r.length<n&&ig(i);){let e=Object.keys(i);if(e.length!==1)break;let t=e[0],n=i[t];r.push(t),i=n}return!ig(i)||ag(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function vg(e){return e.join(`.`)}function yg(e,t){return e===null?`null`:typeof e==`boolean`||typeof e==`number`?String(e):bg(e,t)}function bg(e,t=Qh){return mg(e,t)?e:`"${$h(e)}"`}function xg(e){return fg(e)?e:`"${$h(e)}"`}function Sg(e,t=Qh){return e.map(e=>yg(e,t)).join(t)}function Cg(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;if(n!=null&&(a+=xg(n)),a+=`[${e}${i===Qh?``:i}]`,r){let e=r.map(e=>xg(e));a+=`{${e.join(i)}}`}return a+=`:`,a}function*wg(e,t,n){if(ng(e)){let n=yg(e,t.delimiter);n!==``&&(yield n);return}rg(e)?yield*Dg(void 0,e,n,t):ig(e)&&(yield*Tg(e,n,t))}function*Tg(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*Eg(a,c,t,n,o,r,i,s)}function*Eg(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=gg(e,t,i,r,a,o,l);if(s){let{foldedKey:e,remainder:t,leafValue:i,segmentCount:c}=s,u=xg(e);if(t===void 0){if(ng(i)){yield Lg(n,`${u}: ${yg(i,r.delimiter)}`,r.indent);return}else if(rg(i)){yield*Dg(e,i,n,r);return}else if(ig(i)&&ag(i)){yield Lg(n,`${u}:`,r.indent);return}}if(ig(t)){yield Lg(n,`${u}:`,r.indent);let i=l-c,s=o?`${o}.${e}`:e;yield*Tg(t,n+1,r,a,s,i);return}}}let u=xg(e);ng(t)?yield Lg(n,`${u}: ${yg(t,r.delimiter)}`,r.indent):rg(t)?yield*Dg(e,t,n,r):ig(t)&&(yield Lg(n,`${u}:`,r.indent),ag(t)||(yield*Tg(t,n+1,r,a,c,l)))}function*Dg(e,t,n,r){if(t.length===0){yield Lg(n,Cg(0,{key:e,delimiter:r.delimiter}),r.indent);return}if(sg(t)){yield Lg(n,kg(t,r.delimiter,e),r.indent);return}if(cg(t)&&t.every(e=>sg(e))){yield*Og(e,t,n,r);return}if(lg(t)){let i=jg(t);i?yield*Ag(e,t,i,n,r):yield*Pg(e,t,n,r);return}yield*Pg(e,t,n,r)}function*Og(e,t,n,r){yield Lg(n,Cg(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)if(sg(e)){let t=kg(e,r.delimiter);yield Rg(n+1,t,r.indent)}}function kg(e,t,n){let r=Cg(e.length,{key:n,delimiter:t}),i=Sg(e,t);return e.length===0?r:`${r} ${i}`}function*Ag(e,t,n,r,i){yield Lg(r,Cg(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*Ng(t,n,r+1,i)}function jg(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&Mg(e,n))return n}function Mg(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)||!ng(n[e]))return!1}return!0}function*Ng(e,t,n,r){for(let i of e)yield Lg(n,Sg(t.map(e=>i[e]),r.delimiter),r.indent)}function*Pg(e,t,n,r){yield Lg(n,Cg(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)yield*Ig(e,n+1,r)}function*Fg(e,t,n){if(ag(e)){yield Lg(t,`-`,n.indent);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(rg(a)&&lg(a)){let e=jg(a);if(e){yield Rg(t,Cg(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indent),yield*Ng(a,e,t+2,n),o.length>0&&(yield*Tg(Object.fromEntries(o),t+1,n));return}}let s=xg(i);if(ng(a))yield Rg(t,`${s}: ${yg(a,n.delimiter)}`,n.indent);else if(rg(a))if(a.length===0)yield Rg(t,`${s}${Cg(0,{delimiter:n.delimiter})}`,n.indent);else if(sg(a))yield Rg(t,`${s}${kg(a,n.delimiter)}`,n.indent);else{yield Rg(t,`${s}${Cg(a.length,{delimiter:n.delimiter})}`,n.indent);for(let e of a)yield*Ig(e,t+2,n)}else ig(a)&&(yield Rg(t,`${s}:`,n.indent),ag(a)||(yield*Tg(a,t+2,n)));o.length>0&&(yield*Tg(Object.fromEntries(o),t+1,n))}function*Ig(e,t,n){if(ng(e))yield Rg(t,yg(e,n.delimiter),n.indent);else if(rg(e))if(sg(e))yield Rg(t,kg(e,n.delimiter),n.indent);else{yield Rg(t,Cg(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*Ig(r,t+1,n)}else ig(e)&&(yield*Fg(e,t,n))}function Lg(e,t,n){return` `.repeat(n*e)+t}function Rg(e,t,n){return Lg(e,`- `+t,n)}function zg(e,t){let n=t(``,e,[]);return Bg(n===void 0?e:tg(n),t,[])}function Bg(e,t,n){return ig(e)?Vg(e,t,n):rg(e)?Hg(e,t,n):e}function Vg(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]=Bg(tg(o),t,e))}return r}function Hg(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=tg(s);r.push(Bg(c,t,o))}return r}function Ug(e,t){return Array.from(Wg(e,t)).join(`
|
|
78
|
+
[Response truncated due to length]`),t}catch(e){return console.error(`Response processing error:`,e),`Error processing response`}}};function Fm(e){if(!e||typeof e!=`object`||Array.isArray(e))return rc();let t=e.oneOf||e.anyOf;if(Array.isArray(t)&&t.length>0){let e=t.map(Fm);return e.length===1?e[0]:H(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 _c(t)}let n,r=Array.isArray(e.type)?e.type[0]:e.type;if(r===`integer`||r===`number`)n=r===`integer`?R().int():R(),typeof e.minimum==`number`&&(n=n.min(e.minimum)),typeof e.maximum==`number`&&(n=n.max(e.maximum));else if(r===`boolean`)n=$s();else if(r===`array`)n=B(Fm(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=Fm(n);t.has(e)||(r=r.optional()),i[e]=r}),n=e.additionalProperties===!1?V(i):V(i).passthrough()}else n=I();return e.description&&(n=n.describe(e.description)),n}function Im(e){let t={};return e.forEach(e=>{let n;n=e.schema?Fm(e.schema):e.type===`integer`||e.type===`number`?R():e.type===`boolean`?$s():e.type===`object`?U(rc()):e.type===`array`?B(rc()):e.type===`datetime`?H([I(),R()]):I(),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=V({userId:I().optional(),authorization:I().optional(),organization:I().optional(),apiKey:I().optional(),headers:V({}).optional(),approval:V({approved:$s(),token:I().optional(),modifiedArguments:U(rc()).optional(),originalArguments:U(rc()).optional(),toolName:I().optional()}).optional()}).optional().describe(`Internal user context for multi-tenant authentication and approval workflow`),t}function Lm(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 Rm=new Set([`getInvoiceSummary`,`getCustomerBalance`,`getPaymentStatus`]),zm={listCustomers:{shape:`customer-table`,noun:`customer`,toPayload:Hm,threshold:0},listInvoices:{shape:`invoice-table`,noun:`invoice`,toPayload:Um,threshold:0},getInvoiceLineItems:{shape:`invoice-line-items`,noun:`line item`,toPayload:Gm,threshold:0},listAllPayments:{shape:`payment-table`,noun:`payment`,toPayload:Xm,threshold:0},listCreditNotes:{shape:`credit-note-table`,noun:`credit note`,toPayload:Qm,threshold:0},listContracts:{shape:`contract-table`,noun:`contract`,toPayload:eh,threshold:0},getCustomerById:{shape:`customer-detail`,noun:`customer`,toPayload:nh,threshold:0},getInvoiceById:{shape:`invoice-detail`,noun:`invoice`,toPayload:rh,threshold:0},getContractById:{shape:`contract-detail`,noun:`contract`,toPayload:ih,threshold:0},getCreditNoteById:{shape:`credit-note-detail`,noun:`credit note`,toPayload:lh,threshold:0},listProducts:{shape:`product-table`,noun:`product`,toPayload:uh,threshold:0},listPlans:{shape:`plan-table`,noun:`plan`,toPayload:fh,threshold:0},listJournalEntries:{shape:`journal-table`,noun:`journal entry`,toPayload:mh,threshold:0},listJobs:{shape:`job-table`,noun:`job`,toPayload:gh,threshold:0},listContacts:{shape:`contact-table`,noun:`contact`,toPayload:vh,threshold:0},listRawMetrics:{shape:`raw-metric-table`,noun:`raw metric`,toPayload:bh,threshold:0},listAggregates:{shape:`aggregate-table`,noun:`aggregate`,toPayload:Sh,threshold:0},listCustomerAddresses:{shape:`address-list`,noun:`address`,toPayload:wh,threshold:0},listPaymentMethods:{shape:`payment-method-list`,noun:`payment method`,toPayload:Eh,threshold:0},listBusinessEntities:{shape:`entity-table`,noun:`business entity`,toPayload:Oh,threshold:0},listEntitlements:{shape:`entitlement-table`,noun:`entitlement`,toPayload:Ah,threshold:0},getInvoicePreviewHtml:{shape:`invoice-preview`,noun:`invoice preview`,toPayload:Ih,threshold:0}},Bm=Object.freeze([`app`]);function Vm(e){return`ui://zenskar/app.html`}function Hm(e,t){let n=Q(e),r=Mh(n,[`customers`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(Ym),total:i,cursor:{next:o,prev:s},scope:c}}function Q(e){return e&&typeof e==`object`&&e.api_response&&typeof e.api_response==`object`?e.api_response:e||{}}function Um(e,t){let n=Q(e),r=Mh(n,[`invoices`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(n,[`cursor`,`pagination`])||{},o=a.next??n.next??null,s=a.prev??n.previous??null;return{invoices:r.map(Wm),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 Wm(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:Fh(e.net_invoice_total??e.invoice_total),amount_due:Fh(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 Gm(e,t){let n=Q(e),r=Array.isArray(n.lines)?n.lines:Array.isArray(n)?n:[],i=Fh(n.total),a=Km(r)||`USD`;return{invoice_id:t&&t.invoiceId?String(t.invoiceId):void 0,total:i,currency:a,lines:r.map(qm)}}function Km(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 qm(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:Jm(e.subtotal),quantity:Jm(e.quantity),price:e.price?Jm(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 Jm(e){return e?{value:Fh(e.value),unit:e.unit??null,display:e.display??null}:{value:null,unit:null,display:null}}function Ym(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 Xm(e,t){let n=Q(e),r=Mh(n,[`payments`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(Zm),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0,default_currency:`USD`}}function Zm(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:Fh(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 Qm(e,t){let n=Q(e),r=Mh(n,[`credit_notes`,`creditNotes`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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($m),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0,default_currency:`USD`}}function $m(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:Fh(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 eh(e,t){let n=Q(e),r=Mh(n,[`contracts`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(th),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0}}function th(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 nh(e){let t=Q(e),n=t.customer??t,r=Ym(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 rh(e){let t=Q(e),n=t.invoice??t,r=Wm(n),i=n.customer,a=n.contract;return{invoice:{...r,paid_amount:Fh(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 ih(e){let t=Q(e),n=t.contract??t,r=th(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(ah)}}function ah(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||Fh(e.product_count),pricings:n.map(sh)}}function oh(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 sh(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:oh(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:ch(t)}}function ch(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?Lm(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?Lm(e.trigger_event):``,r=e.expires_at?`, expires ${Lm(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?Lm(e.trigger_event):``;t.push({type:`Consumption`,label:e.label??null,summary:`${n} (${Lm(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 lh(e){let t=Q(e),n=t.credit_note??t.creditNote??t,r=$m(n),i=n.customer,a=n.invoice;return{credit_note:{...r,line_items_url:n.line_items_url??null,credits_returned:Fh(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 uh(e,t){let n=Q(e),r=Mh(n,[`products`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(dh),total:i,cursor:{next:o,prev:s},scope:c}}function dh(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 fh(e,t){let n=Q(e),r=Mh(n,[`plans`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(ph),total:i,cursor:{next:o,prev:s},scope:c}}function ph(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:Fh(e.plan_version),created_at:e.created_at??null}}function mh(e,t){let n=Q(e),r=Mh(n,[`entries`,`journal_entries`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(hh),total:i,cursor:{next:o,prev:s},scope:c,default_currency:`USD`}}function hh(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 gh(e,t){let n=Q(e),r=Mh(n,[`jobs`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(_h),total:i,cursor:{next:o,prev:s},scope:c,status_counts:l}}function _h(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 vh(e,t){let n=Q(e),r=Mh(n,[`contacts`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(yh),total:i,cursor:{next:o,prev:s},scope:c?String(c):void 0}}function yh(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 bh(e,t){let n=Q(e),r=Mh(n,[`raw_metrics`,`rawmetrics`,`rawMetrics`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(xh),total:i,cursor:{next:o,prev:s},scope:c}}function xh(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 Sh(e,t){let n=Q(e),r=Mh(n,[`aggregates`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(Ch),total:i,cursor:{next:o,prev:s},scope:c}}function Ch(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 wh(e,t){let n=Mh(Q(e),[`addresses`,`data`,`results`]);return{customer_id:t&&t.customerId?String(t.customerId):void 0,addresses:n.map(Th),total:n.length}}function Th(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 Eh(e,t){let n=Mh(Q(e),[`payment_methods`,`paymentMethods`,`data`,`results`]);return{customer_id:t&&t.customerId?String(t.customerId):void 0,payment_methods:n.map(Dh),total:n.length}}function Dh(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:Fh(t.exp_month??e.exp_month),exp_year:Fh(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 Oh(e,t){let n=Q(e),r=Mh(n,[`business_entities`,`businessEntities`,`entities`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(kh),total:i,cursor:{next:o,prev:s}}}function kh(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 Ah(e,t){let n=Q(e),r=Mh(n,[`entitlements`,`data`,`results`]),i=Ph(n,[`total`,`count`,`total_count`])??r.length,a=Nh(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(jh),total:i,cursor:{next:o,prev:s},scope:c}}function jh(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 Mh(e,t){if(Array.isArray(e))return e;for(let n of t)if(e&&Array.isArray(e[n]))return e[n];return[]}function Nh(e,t){for(let n of t)if(e&&e[n]&&typeof e[n]==`object`)return e[n];return null}function Ph(e,t){for(let n of t)if(e&&Number.isFinite(e[n]))return e[n];return null}function Fh(e){return Number.isFinite(e)?e:null}function Ih(e,t){let n=Q(e);return{html:n.html??(typeof n==`string`?n:``),invoice_id:t&&t.invoiceId?String(t.invoiceId):void 0}}function Lh(e){if(Rm.has(e))return{mode:`text-only`};let t=zm[e];return t?{mode:`ui`,...t}:{mode:`unmapped`}}const Rh=a(s(import.meta.url)),zh=[o(Rh,`..`,`..`,`..`,`dist`,`ui`),o(Rh,`ui`)];function Bh(e){for(let t of zh){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 Vh(){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 Hh(){let e={prefersBorder:!0},t=Vh();return t.length>0&&(e.csp={connectDomains:t,resourceDomains:t}),e}function Uh(e){for(let t of Bm){let n=Vm(t);e.registerResource(`zenskar-app`,n,{},async()=>({contents:[{uri:n,mimeType:`text/html;profile=mcp-app`,text:Bh(t),_meta:{"openai/widgetPrefersBorder":!0,ui:Hh()}}]}))}}const Wh=[`claude-code`,`cline`,`roo-code`,`continue`,`codex`,`windsurf`,`zed`,`aider`,`copilot`,`gemini-cli`],Gh=[`claude-desktop`,`claude-ai`,`chatgpt`,`mcp-inspector`,`toon`,`cursor`];let Kh=null,qh=null;function Jh(e){Kh=e?String(e).toLowerCase().trim():null}function Yh(e){qh=e}function Xh(){if(Kh==null&&qh){let e=qh();e&&Jh(e)}return Kh}function Zh(e){let t=(e??Kh??``).toLowerCase().trim();return t?Wh.some(e=>t.includes(e))?`coding-agent`:Gh.some(e=>t.includes(e))?`widget-host`:`default`:`default`}const Qh={comma:`,`,tab:` `,pipe:`|`}.comma;function $h(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}function eg(e){return e===`true`||e===`false`||e===`null`}function tg(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 tg(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(tg);if(e instanceof Set)return Array.from(e).map(tg);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),tg(t)]));if(og(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&(t[n]=tg(e[n]));return t}return null}function ng(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function rg(e){return Array.isArray(e)}function ig(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ag(e){return Object.keys(e).length===0}function og(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function sg(e){return e.length===0||e.every(e=>ng(e))}function cg(e){return e.length===0||e.every(e=>rg(e))}function lg(e){return e.length===0||e.every(e=>ig(e))}const ug=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,dg=/^0\d+$/;function fg(e){return/^[A-Z_][\w.]*$/i.test(e)}function pg(e){return/^[A-Z_]\w*$/i.test(e)}function mg(e,t=Qh){return!(!e||e!==e.trim()||eg(e)||hg(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\n\r\t]/.test(e)||e.includes(t)||e.startsWith(`-`))}function hg(e){return ug.test(e)||dg.test(e)}function gg(e,t,n,r,i,a,o){if(r.keyFolding!==`safe`||!ig(t))return;let{segments:s,tail:c,leafValue:l}=_g(e,t,o??r.flattenDepth);if(s.length<2||!s.every(e=>pg(e)))return;let u=vg(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 _g(e,t,n){let r=[e],i=t;for(;r.length<n&&ig(i);){let e=Object.keys(i);if(e.length!==1)break;let t=e[0],n=i[t];r.push(t),i=n}return!ig(i)||ag(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function vg(e){return e.join(`.`)}function yg(e,t){return e===null?`null`:typeof e==`boolean`||typeof e==`number`?String(e):bg(e,t)}function bg(e,t=Qh){return mg(e,t)?e:`"${$h(e)}"`}function xg(e){return fg(e)?e:`"${$h(e)}"`}function Sg(e,t=Qh){return e.map(e=>yg(e,t)).join(t)}function Cg(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;if(n!=null&&(a+=xg(n)),a+=`[${e}${i===Qh?``:i}]`,r){let e=r.map(e=>xg(e));a+=`{${e.join(i)}}`}return a+=`:`,a}function*wg(e,t,n){if(ng(e)){let n=yg(e,t.delimiter);n!==``&&(yield n);return}rg(e)?yield*Dg(void 0,e,n,t):ig(e)&&(yield*Tg(e,n,t))}function*Tg(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*Eg(a,c,t,n,o,r,i,s)}function*Eg(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=gg(e,t,i,r,a,o,l);if(s){let{foldedKey:e,remainder:t,leafValue:i,segmentCount:c}=s,u=xg(e);if(t===void 0){if(ng(i)){yield Lg(n,`${u}: ${yg(i,r.delimiter)}`,r.indent);return}else if(rg(i)){yield*Dg(e,i,n,r);return}else if(ig(i)&&ag(i)){yield Lg(n,`${u}:`,r.indent);return}}if(ig(t)){yield Lg(n,`${u}:`,r.indent);let i=l-c,s=o?`${o}.${e}`:e;yield*Tg(t,n+1,r,a,s,i);return}}}let u=xg(e);ng(t)?yield Lg(n,`${u}: ${yg(t,r.delimiter)}`,r.indent):rg(t)?yield*Dg(e,t,n,r):ig(t)&&(yield Lg(n,`${u}:`,r.indent),ag(t)||(yield*Tg(t,n+1,r,a,c,l)))}function*Dg(e,t,n,r){if(t.length===0){yield Lg(n,Cg(0,{key:e,delimiter:r.delimiter}),r.indent);return}if(sg(t)){yield Lg(n,kg(t,r.delimiter,e),r.indent);return}if(cg(t)&&t.every(e=>sg(e))){yield*Og(e,t,n,r);return}if(lg(t)){let i=jg(t);i?yield*Ag(e,t,i,n,r):yield*Pg(e,t,n,r);return}yield*Pg(e,t,n,r)}function*Og(e,t,n,r){yield Lg(n,Cg(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)if(sg(e)){let t=kg(e,r.delimiter);yield Rg(n+1,t,r.indent)}}function kg(e,t,n){let r=Cg(e.length,{key:n,delimiter:t}),i=Sg(e,t);return e.length===0?r:`${r} ${i}`}function*Ag(e,t,n,r,i){yield Lg(r,Cg(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*Ng(t,n,r+1,i)}function jg(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&Mg(e,n))return n}function Mg(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)||!ng(n[e]))return!1}return!0}function*Ng(e,t,n,r){for(let i of e)yield Lg(n,Sg(t.map(e=>i[e]),r.delimiter),r.indent)}function*Pg(e,t,n,r){yield Lg(n,Cg(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)yield*Ig(e,n+1,r)}function*Fg(e,t,n){if(ag(e)){yield Lg(t,`-`,n.indent);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(rg(a)&&lg(a)){let e=jg(a);if(e){yield Rg(t,Cg(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indent),yield*Ng(a,e,t+2,n),o.length>0&&(yield*Tg(Object.fromEntries(o),t+1,n));return}}let s=xg(i);if(ng(a))yield Rg(t,`${s}: ${yg(a,n.delimiter)}`,n.indent);else if(rg(a))if(a.length===0)yield Rg(t,`${s}${Cg(0,{delimiter:n.delimiter})}`,n.indent);else if(sg(a))yield Rg(t,`${s}${kg(a,n.delimiter)}`,n.indent);else{yield Rg(t,`${s}${Cg(a.length,{delimiter:n.delimiter})}`,n.indent);for(let e of a)yield*Ig(e,t+2,n)}else ig(a)&&(yield Rg(t,`${s}:`,n.indent),ag(a)||(yield*Tg(a,t+2,n)));o.length>0&&(yield*Tg(Object.fromEntries(o),t+1,n))}function*Ig(e,t,n){if(ng(e))yield Rg(t,yg(e,n.delimiter),n.indent);else if(rg(e))if(sg(e))yield Rg(t,kg(e,n.delimiter),n.indent);else{yield Rg(t,Cg(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*Ig(r,t+1,n)}else ig(e)&&(yield*Fg(e,t,n))}function Lg(e,t,n){return` `.repeat(n*e)+t}function Rg(e,t,n){return Lg(e,`- `+t,n)}function zg(e,t){let n=t(``,e,[]);return Bg(n===void 0?e:tg(n),t,[])}function Bg(e,t,n){return ig(e)?Vg(e,t,n):rg(e)?Hg(e,t,n):e}function Vg(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]=Bg(tg(o),t,e))}return r}function Hg(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=tg(s);r.push(Bg(c,t,o))}return r}function Ug(e,t){return Array.from(Wg(e,t)).join(`
|
|
79
79
|
`)}function Wg(e,t){let n=tg(e),r=Gg(t);return wg(r.replacer?zg(n,r.replacer):n,r,0)}function Gg(e){return{indent:e?.indent??2,delimiter:e?.delimiter??Qh,keyFolding:e?.keyFolding??`off`,flattenDepth:e?.flattenDepth??1/0,replacer:e?.replacer}}function Kg(e){return typeof e==`string`?e:Ug(e)}function qg(){let e=process.env.ZENSKAR_MCP_UI_ENABLED;return e==null||e===``?!0:!/^(0|false|no|off)$/i.test(String(e).trim())}function Jg(){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 Yg=process.env.ZENSKAR_MCP_UI_DEBUG===`true`||process.env.MCP_DEBUG===`true`;function Xg(...e){Yg&&console.error(`[ui-wrap]`,...e)}function Zg(e,t,n,r){if(!qg())return Xg(e,`skipped: ZENSKAR_MCP_UI_ENABLED explicitly disabled`),$g(n);let i=Lh(e);if(i.mode!==`ui`)return Xg(e,`skipped: not in registry, mode=`,i.mode),$g(n);if(Jg().has(e))return Xg(e,`skipped: in ZENSKAR_MCP_UI_DISABLED_TOOLS`),$g(n);let a;try{a=i.toPayload(t,r)}catch(t){return Xg(e,`toPayload threw:`,t.message),$g(n)}let o=Qg(a);if(o<(i.threshold??0))return Xg(e,`below threshold:`,o,`<`,i.threshold),$g(n);let s=Zh(Xh());return Xg(e,`OK shape=`,i.shape,`items=`,o,`client=`,s),s===`coding-agent`?$g(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
|
-
`+Kg(a)}],structuredContent:a}:$g(n)}function Qg(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 $g(e){return{content:[{type:`text`,text:e}]}}const e_=s(import.meta.url),t_=i.dirname(e_),n_={logUsage:async()=>{}},r_=(e,t)=>({valid:!0,adjustedArgs:t,warnings:[],errors:[]}),i_=()=>({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):``)}},a_=i.join(t_,`mcp-config.json`);let o_;try{o_=JSON.parse(t.readFileSync(a_,`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 s_=new mm({name:o_.server?.name||`zenskar-api-server`,version:`1.0.0`});Yh(()=>{let e=s_.server.getClientVersion();return e&&e.name?e.name:null});const c_=new Pm;function l_(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t={...e};return typeof t.timestamp==`string`&&(t.timestamp=u_(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]=u_(t.data[e]))})),t}function u_(e){return typeof e==`string`?e.replace(`T`,` `).replace(`t`,` `).replace(/Z$/i,``).trim():e}function d_(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 f_(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t={...e};if(t.customer_id&&=d_(t.customer_id),t.timestamp&&=d_(t.timestamp),t.data&&typeof t.data==`object`&&!Array.isArray(t.data)){let e={};Object.entries(t.data).forEach(([t,n])=>{e[t]=d_(n)}),t.data=e}return t}function p_(e){return e?Array.isArray(e)?e:Array.isArray(e.results)?e.results:e.api_response===void 0?[]:p_(e.api_response):[]}function m_(e){return!e||typeof e!=`string`?`Uncategorized`:e.trim()||`Uncategorized`}function h_(e){let t=Number(e);return Number.isFinite(t)?t/100:null}function g_(e,t){let n=m_(t);return e===`getBalanceSheet`&&n===`Liabilities`?`Liabilities & Equity`:n}function __(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 v_(e){return`${e?.interval_start||`unknown_start`}__${e?.interval_end||`unknown_end`}`}function y_(e){return Object.values(e).sort((e,t)=>String(e.interval_start).localeCompare(String(t.interval_start)))}function b_(e,t,n){let r=new Map,i=new Map;t.forEach(t=>{let a=g_(e,t.account_category),o=v_(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:h_(t.balance??0),debits:t.debits??0,display_debits:h_(t.debits??0),credits:t.credits??0,display_credits:h_(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=h_(f.balance),f.display_debits=h_(f.debits),f.display_credits=h_(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=__(e,t.category)-__(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:y_(e.periods)})),totals_by_period:y_(e.totals_by_period),total_balance:e.total_balance,display_total_balance:h_(e.total_balance),total_debits:e.total_debits,display_total_debits:h_(e.total_debits),total_credits:e.total_credits,display_total_credits:h_(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 x_(e){if(!e)return``;let t=e.account_category||``;return t===`Liabilities`?`Liabilities & Equity`:t}function S_(e){let t=[...e].map(e=>({...e,account_category:x_(e)})).sort((e,t)=>{let n=x_(e).localeCompare(x_(t));return n===0?String(e.name||``).localeCompare(String(t.name||``)):n}),n=new Map;t.forEach(e=>{let t=x_(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 C_(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 w_(e){if(!e||!Array.isArray(e.results))return e;let t=[...e.results].sort((e,t)=>{let n=m_(e.account_category),r=m_(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=m_(t.account_category);return e[n]=e[n]||[],e[n].push(t),e},{});return{...e,results:t,grouped_view:n}}async function T_(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 E_(e,t,n){let r=e.rawMetricId,i=await T_(`${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 D_(e,t,n,r){if(!t||!Array.isArray(t.results))return t;try{let i=p_(await T_(`${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:g_(e,n.account_category),account_parent_path:n.parent_path||null,balance_normality:n.balance_normality||null,display_balance:h_(t.balance??0),display_debits:h_(t.debits??0),display_credits:h_(t.credits??0)}}),s=b_(e,o,a);if(e===`getBalanceSheet`){let e=new URLSearchParams;n.apiversion&&e.set(`apiversion`,n.apiversion);let t=await T_(`${r}/accounting_new/income_statement/v2`,n),i=Array.isArray(t?.results)?t.results:[],a={};i.forEach(e=>{let t=v_(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=y_(Object.fromEntries(Object.entries(a).map(([e,t])=>[e,{...t,display_balance:h_(t.balance),display_debits:h_(t.debits),display_credits:h_(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:h_(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:h_(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:h_(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 O_(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=l_(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&&=f_(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 E_(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 D_(e.name,s,u,t)}return e.name===`listJobs`&&(s=C_(s)),e.name===`listAccounts`&&(s=w_(s)),e.name===`getChartOfAccounts`&&Array.isArray(s)&&(s={raw_accounts:s,chart_view:S_(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}`)}}const k_=300*1e3,A_=process.env.APPROVAL_HMAC_SECRET,j_=!!A_,M_=new Map,N_=new Map;function P_(e){if(e==null)return e;if(typeof structuredClone==`function`)try{return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}function F_(e){let t=e?P_(e):{};return delete t.__userContext,t}function I_(t){return e.createHmac(`sha256`,A_).update(t).digest(`base64url`)}function L_(t,n){let r=Date.now(),i=r+k_,a=F_(n);if(j_){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}.${I_(o)}`}let o=Mm();return M_.set(o,{toolName:t,issuedAt:r,expiresAt:i,args:a}),o}function R_(t,n){if(!t||typeof t!=`string`)return null;if(j_){let r=t.split(`.`);if(r.length!==3)return null;let[i,a,o]=r;if(i!==`v1`)return null;let s=I_(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()||N_.has(t)?null:(N_.set(t,u.expiresAt),u)}let r=M_.get(t);return!r||(M_.delete(t),r.toolName!==n)||r.expiresAt<Date.now()?null:r}setInterval(()=>{let e=Date.now();for(let[t,n]of M_)n.expiresAt<e&&M_.delete(t);for(let[t,n]of N_)n<e&&N_.delete(t)},6e4).unref();function z_(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 B_(e,t){let n=e.__userContext;Object.keys(e).forEach(t=>{t!==`__userContext`&&delete e[t]}),Object.assign(e,t),e.__userContext=n}function V_(e,t){if(!e.needsApproval)return!1;let n=t.__userContext,r=n&&n.approval;if(r&&r.approved===!0){let n=R_(r.token,e.name);if(n){let{args:i,source:a}=z_(r,n);return $.info(`[${e.name}] Approval token verified; arg source=${a}`),B_(t,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 H_(e,t){t.__userContext;let n={...t};delete n.__userContext;let r=L_(e.name,t);return{type:`approval_required`,toolName:e.name,toolDescription:e.description,arguments:n,approvalToken:r,approvalTokenExpiresInSeconds:Math.floor(k_/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:W_(t.type),required:t.required||!1,value:n[t.name],sensitive:e.approvalConfig?.sensitiveFields?.includes(t.name)||!1}))}}function U_(e,t){let n=[];if(e===`createProductPricing`){let e=t.pricing_data;!e||typeof e!=`object`?n.push(`'pricing_data' is required and must be an object containing 'pricing_type' and 'currency'.`):(e.pricing_type||n.push(`'pricing_data.pricing_type' is required (e.g. 'per_unit', 'flat_fee', 'tiered', 'volume', 'percent', 'package').`),e.currency||n.push(`'pricing_data.currency' is required (ISO 4217, e.g. 'USD').`));let r=t.quantity;!r||typeof r!=`object`?n.push(`'quantity' is required and must be an object: {type:'fixed'|'metered', quantity?, unit?, aggregate_id?}. Without it the UI shows 0 for billing_metric.`):(r.type!==`fixed`&&r.type!==`metered`&&n.push(`'quantity.type' must be exactly 'fixed' or 'metered'.`),r.type===`fixed`&&(r.quantity==null||!r.unit)&&n.push(`'quantity.type'='fixed' requires both 'quantity' (number) and 'unit' (label string).`),r.type===`metered`&&!r.aggregate_id&&n.push(`'quantity.type'='metered' requires 'aggregate_id' (UUID of the billable metric).`));let i=t.billing_period;!i||typeof i!=`object`?n.push(`'billing_period' is required and must be an object: {cadence:'P1M'|'P3M'|'P1Y'|..., offset:'P0D'|...}. Without it the UI renders 'Undefined- Every Undefined Undefined'.`):(i.cadence||n.push(`'billing_period.cadence' is required (ISO-8601 duration: 'P1M'=monthly, 'P3M'=quarterly, 'P1Y'=yearly).`),i.offset||n.push(`'billing_period.offset' is required (ISO-8601 duration, 'P0D' for no offset).`))}if(e===`createPlan`){(!t.schedule||typeof t.schedule!=`object`||!t.schedule.duration)&&n.push(`'schedule' is required and must include 'duration' (ISO-8601, e.g. 'P1Y').`),t.status||n.push(`'status' is required: 'draft' | 'active' | 'archived'.`);let e=t.phases;!Array.isArray(e)||e.length===0?n.push(`'phases' must be a non-empty array. A plan with no phases is unusable in PlansV2 — include at least one phase with name, schedule, order, and either features or pricings.`):e.forEach((e,t)=>{if(!e||typeof e!=`object`){n.push(`'phases[${t}]' must be an object.`);return}e.name||n.push(`'phases[${t}].name' is required.`),(!e.schedule||!e.schedule.duration)&&n.push(`'phases[${t}].schedule.duration' is required (ISO-8601).`),typeof e.order!=`number`&&n.push(`'phases[${t}].order' is required (integer, 0-indexed).`),!e.features&&(!Array.isArray(e.pricings)||e.pricings.length===0)&&n.push(`'phases[${t}]' has neither 'features' nor non-empty 'pricings' — phase will be empty in the UI.`)})}if(e===`generateInvoice`){let e=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=e(t.from_date),i=e(t.to_date);r===null&&n.push(`'from_date' must be either an integer UNIX timestamp (seconds) or an ISO-8601 datetime string. Copy from getContractBillingCycles.start_date.`),i===null&&n.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&&n.push(`'to_date' must be strictly greater than 'from_date'.`),e(t.bill_for_date)===null&&n.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(t.billing_cycle_start_day)||t.billing_cycle_start_day<1||t.billing_cycle_start_day>31)&&n.push(`'billing_cycle_start_day' is REQUIRED and must be an integer 1-31. Copy from getContractBillingCycles.billing_cycle_start_day.`)}return e===`pauseContract`&&(t.start_date||n.push(`'start_date' is required (ISO 8601).`),t.unpause_extension_policy||n.push(`'unpause_extension_policy' is required: 'extend' or 'overlap'.`)),{valid:n.length===0,errors:n}}function W_(e){switch(e){case`string`:return`text`;case`integer`:case`number`:return`number`;case`boolean`:return`checkbox`;default:return`text`}}Uh(s_),o_.tools&&o_.tools.length>0&&o_.tools.forEach(e=>{$.info(`Registering tool: ${e.name}`);let t=Im(e.args||[]),n=Lh(e.name),r=n.mode===`ui`?(()=>{let e=Vm(n.shape);return{"openai/outputTemplate":e,"ui/resourceUri":e,ui:{resourceUri:e}}})():void 0;s_.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=U_(e.name,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(`
|
|
80
|
+
`+Kg(a)}],structuredContent:a}:$g(n)}function Qg(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 $g(e){return{content:[{type:`text`,text:e}]}}const e_=s(import.meta.url),t_=i.dirname(e_),n_={logUsage:async()=>{}},r_=(e,t)=>({valid:!0,adjustedArgs:t,warnings:[],errors:[]}),i_=()=>({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):``)}},a_=i.join(t_,`mcp-config.json`);let o_;try{o_=JSON.parse(t.readFileSync(a_,`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 s_=new mm({name:o_.server?.name||`zenskar-api-server`,version:`1.0.0`});Yh(()=>{let e=s_.server.getClientVersion();return e&&e.name?e.name:null});const c_=new Pm;function l_(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t={...e};return typeof t.timestamp==`string`&&(t.timestamp=u_(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]=u_(t.data[e]))})),t}function u_(e){return typeof e==`string`?e.replace(`T`,` `).replace(`t`,` `).replace(/Z$/i,``).trim():e}function d_(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 f_(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t={...e};if(t.customer_id&&=d_(t.customer_id),t.timestamp&&=d_(t.timestamp),t.data&&typeof t.data==`object`&&!Array.isArray(t.data)){let e={};Object.entries(t.data).forEach(([t,n])=>{e[t]=d_(n)}),t.data=e}return t}function p_(e){return e?Array.isArray(e)?e:Array.isArray(e.results)?e.results:e.api_response===void 0?[]:p_(e.api_response):[]}function m_(e){return!e||typeof e!=`string`?`Uncategorized`:e.trim()||`Uncategorized`}function h_(e){let t=Number(e);return Number.isFinite(t)?t/100:null}function g_(e,t){let n=m_(t);return e===`getBalanceSheet`&&n===`Liabilities`?`Liabilities & Equity`:n}function __(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 v_(e){return`${e?.interval_start||`unknown_start`}__${e?.interval_end||`unknown_end`}`}function y_(e){return Object.values(e).sort((e,t)=>String(e.interval_start).localeCompare(String(t.interval_start)))}function b_(e,t,n){let r=new Map,i=new Map;t.forEach(t=>{let a=g_(e,t.account_category),o=v_(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:h_(t.balance??0),debits:t.debits??0,display_debits:h_(t.debits??0),credits:t.credits??0,display_credits:h_(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=h_(f.balance),f.display_debits=h_(f.debits),f.display_credits=h_(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=__(e,t.category)-__(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:y_(e.periods)})),totals_by_period:y_(e.totals_by_period),total_balance:e.total_balance,display_total_balance:h_(e.total_balance),total_debits:e.total_debits,display_total_debits:h_(e.total_debits),total_credits:e.total_credits,display_total_credits:h_(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 x_(e){if(!e)return``;let t=e.account_category||``;return t===`Liabilities`?`Liabilities & Equity`:t}function S_(e){let t=[...e].map(e=>({...e,account_category:x_(e)})).sort((e,t)=>{let n=x_(e).localeCompare(x_(t));return n===0?String(e.name||``).localeCompare(String(t.name||``)):n}),n=new Map;t.forEach(e=>{let t=x_(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 C_(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 w_(e){if(!e||!Array.isArray(e.results))return e;let t=[...e.results].sort((e,t)=>{let n=m_(e.account_category),r=m_(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=m_(t.account_category);return e[n]=e[n]||[],e[n].push(t),e},{});return{...e,results:t,grouped_view:n}}async function T_(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 E_(e,t,n){let r=e.rawMetricId,i=await T_(`${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 D_(e,t,n,r){if(!t||!Array.isArray(t.results))return t;try{let i=p_(await T_(`${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:g_(e,n.account_category),account_parent_path:n.parent_path||null,balance_normality:n.balance_normality||null,display_balance:h_(t.balance??0),display_debits:h_(t.debits??0),display_credits:h_(t.credits??0)}}),s=b_(e,o,a);if(e===`getBalanceSheet`){let e=new URLSearchParams;n.apiversion&&e.set(`apiversion`,n.apiversion);let t=await T_(`${r}/accounting_new/income_statement/v2`,n),i=Array.isArray(t?.results)?t.results:[],a={};i.forEach(e=>{let t=v_(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=y_(Object.fromEntries(Object.entries(a).map(([e,t])=>[e,{...t,display_balance:h_(t.balance),display_debits:h_(t.debits),display_credits:h_(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:h_(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:h_(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:h_(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 O_(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=l_(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&&=f_(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 E_(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 D_(e.name,s,u,t)}return e.name===`listJobs`&&(s=C_(s)),e.name===`listAccounts`&&(s=w_(s)),e.name===`getChartOfAccounts`&&Array.isArray(s)&&(s={raw_accounts:s,chart_view:S_(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}`)}}const k_=300*1e3,A_=process.env.APPROVAL_HMAC_SECRET,j_=!!A_,M_=new Map,N_=new Map;function P_(e){if(e==null)return e;if(typeof structuredClone==`function`)try{return structuredClone(e)}catch{}return JSON.parse(JSON.stringify(e))}function F_(e){let t=e?P_(e):{};return delete t.__userContext,t}function I_(t){return e.createHmac(`sha256`,A_).update(t).digest(`base64url`)}function L_(t,n){let r=Date.now(),i=r+k_,a=F_(n);if(j_){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}.${I_(o)}`}let o=Mm();return M_.set(o,{toolName:t,issuedAt:r,expiresAt:i,args:a}),o}function R_(t,n){if(!t||typeof t!=`string`)return null;if(j_){let r=t.split(`.`);if(r.length!==3)return null;let[i,a,o]=r;if(i!==`v1`)return null;let s=I_(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()||N_.has(t)?null:(N_.set(t,u.expiresAt),u)}let r=M_.get(t);return!r||(M_.delete(t),r.toolName!==n)||r.expiresAt<Date.now()?null:r}setInterval(()=>{let e=Date.now();for(let[t,n]of M_)n.expiresAt<e&&M_.delete(t);for(let[t,n]of N_)n<e&&N_.delete(t)},6e4).unref();function z_(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 B_(e,t){let n=e.__userContext;Object.keys(e).forEach(t=>{t!==`__userContext`&&delete e[t]}),Object.assign(e,t),e.__userContext=n}function V_(e,t){if(!e.needsApproval)return!1;let n=t.__userContext,r=n&&n.approval;if(r&&r.approved===!0){let n=R_(r.token,e.name);if(n){let{args:i,source:a}=z_(r,n);return $.info(`[${e.name}] Approval token verified; arg source=${a}`),B_(t,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 H_(e,t){t.__userContext;let n={...t};delete n.__userContext;let r=L_(e.name,t);return{type:`approval_required`,toolName:e.name,toolDescription:e.description,arguments:n,approvalToken:r,approvalTokenExpiresInSeconds:Math.floor(k_/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:W_(t.type),required:t.required||!1,value:n[t.name],sensitive:e.approvalConfig?.sensitiveFields?.includes(t.name)||!1}))}}function U_(e,t){let n=[];if(e===`generateInvoice`){let e=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=e(t.from_date),i=e(t.to_date);r===null&&n.push(`'from_date' must be either an integer UNIX timestamp (seconds) or an ISO-8601 datetime string. Copy from getContractBillingCycles.start_date.`),i===null&&n.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&&n.push(`'to_date' must be strictly greater than 'from_date'.`),e(t.bill_for_date)===null&&n.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(t.billing_cycle_start_day)||t.billing_cycle_start_day<1||t.billing_cycle_start_day>31)&&n.push(`'billing_cycle_start_day' is REQUIRED and must be an integer 1-31. Copy from getContractBillingCycles.billing_cycle_start_day.`)}return e===`pauseContract`&&(t.start_date||n.push(`'start_date' is required (ISO 8601).`),t.unpause_extension_policy||n.push(`'unpause_extension_policy' is required: 'extend' or 'overlap'.`)),{valid:n.length===0,errors:n}}function W_(e){switch(e){case`string`:return`text`;case`integer`:case`number`:return`number`;case`boolean`:return`checkbox`;default:return`text`}}Uh(s_),o_.tools&&o_.tools.length>0&&o_.tools.forEach(e=>{$.info(`Registering tool: ${e.name}`);let t=Im(e.args||[]),n=Lh(e.name),r=n.mode===`ui`?(()=>{let e=Vm(n.shape);return{"openai/outputTemplate":e,"ui/resourceUri":e,ui:{resourceUri:e}}})():void 0;s_.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=U_(e.name,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
83
|
Fix the arguments and call again. Do NOT report success to the user.`}],isError:!0}}let u=V_(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=H_(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(k_/1e3)}s. Do NOT fabricate the token. Do NOT report success to the user; surface the dialog instead.`}],isApprovalRequired:!0,approvalRequest:n}}let f=U_(e.name,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
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mcp-zenskar",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.4",
|
|
4
4
|
"description": "Model Context Protocol (MCP) server for Zenskar API - customer management, invoicing, and billing operations",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/server.mjs",
|
|
@@ -59,8 +59,9 @@
|
|
|
59
59
|
"build:ui": "node src/ui/server/build.js",
|
|
60
60
|
"prebuild": "pnpm run build:ui",
|
|
61
61
|
"build": "tsdown",
|
|
62
|
+
"test:mcp-schema": "node --test src/test/mcp-list-tools.test.js",
|
|
62
63
|
"test:tool-schema": "node --test src/test/tool-schema.test.js",
|
|
63
64
|
"smoke": "tsx src/ui/test/smoke.ts",
|
|
64
|
-
"test": "pnpm run test:tool-schema && pnpm run smoke"
|
|
65
|
+
"test": "pnpm run test:tool-schema && pnpm run test:mcp-schema && pnpm run smoke"
|
|
65
66
|
}
|
|
66
67
|
}
|