-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
678 lines (549 loc) Β· 27.8 KB
/
Copy pathserver.py
File metadata and controls
678 lines (549 loc) Β· 27.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
"""
Servidor MCP para Datafast (Dataweb / ACI Worldwide) v2.0.0
============================================================
Permite a un agente de IA procesar pagos con tarjeta de crΓ©dito/dΓ©bito
a travΓ©s del gateway Datafast Ecuador (motor ACI Worldwide / Oppwa).
β οΈ IMPORTANTE β Formato de peticiΓ³n:
Las peticiones POST y DELETE usan application/x-www-form-urlencoded,
NO JSON. Este servidor maneja ese detalle internamente.
MULTI-ACCOUNT SUPPORT (v2.0):
Cada tool acepta `entity_id` como parΓ‘metro explΓcito. El bearer token
se lee de la variable de entorno DATAFAST_BEARER_TOKEN. Esto permite al
agente operar en diferentes cuentas de comercio pasando entity_id por
llamada.
Flujo estΓ‘ndar:
1. crear_checkout β obtiene checkoutId
2. [Frontend renderiza el widget de tarjeta con el checkoutId]
3. verificar_pago_checkout β valida si fue aprobado
CΓ³digos de resultado comunes:
Β· 000.000.000 / 000.100.112 β Aprobado
Β· 800.100.152 / 800.100.162 β Rechazado (banco)
Β· 100.400.500 β Error de datos / sumatoria de impuestos
Fuente de verdad tΓ©cnica: docs/openapi.yaml
"""
import os
import json
import logging
from decimal import ROUND_HALF_UP, Decimal
from enum import Enum
from typing import Any
from dotenv import load_dotenv
import httpx
from mcp.server.fastmcp import FastMCP
from mcp_common.security import validate_safe_url, validate_amount
from mcp_common.logging_filter import install as install_logging_filter
load_dotenv()
# ---------------------------------------------------------------------------
# Motor fiscal determinista β IVA Ecuador (Datafast / Oppwa)
# ---------------------------------------------------------------------------
# El LLM NUNCA calcula impuestos. Solo pasa `monto` + `tipo_monto`.
# Datafast exige strings con 2 decimales y que:
# amount == subtotal_iva0 + subtotal_gravado + valor_iva + valor_ice
# El incumplimiento de esa suma causa el error 100.400.500.
# ---------------------------------------------------------------------------
class TipoMonto(str, Enum):
"""Indica si el monto dado por el usuario incluye IVA o es la base imponible."""
SUBTOTAL = "subtotal" # el usuario dio la base SIN IVA (default)
TOTAL_CON_IVA = "total_con_iva" # el usuario dio el total CON IVA incluido
_TWO = Decimal("0.01")
def _iva_rate() -> Decimal:
"""Lee IVA_EC_PERCENTAGE del entorno. Fallback: 0.15 (15%)."""
raw = os.environ.get("IVA_EC_PERCENTAGE", "0.15")
try:
rate = Decimal(raw)
if not (Decimal(0) < rate <= Decimal(1)):
raise ValueError()
return rate
except Exception:
raise ValueError(
f"IVA_EC_PERCENTAGE invΓ‘lido: {raw!r}. "
"Debe ser un decimal entre 0 y 1, ej. '0.15' para 15%."
)
def _r2(v: Decimal) -> Decimal:
"""Redondeo estricto a 2 decimales (ROUND_HALF_UP)."""
return v.quantize(_TWO, rounding=ROUND_HALF_UP)
def _calcular_strings_fiscales(
monto: float, tipo: TipoMonto
) -> tuple[str, str, str]:
"""Calcula (amount_str, subtotal_gravado_str, valor_iva_str) con 2 decimales.
Datafast/Oppwa exige strings tipo "12.50". Este mΓ©todo garantiza la
invariante fiscal que evita el error 100.400.500:
amount == subtotal_iva0 + subtotal_gravado + valor_iva + valor_ice
Args:
monto: El valor exacto dado por el usuario (en USD).
tipo: TipoMonto.SUBTOTAL β monto es la base sin IVA.
TipoMonto.TOTAL_CON_IVA β monto es el total ya con IVA.
Returns:
(amount_str, subtotal_gravado_str, valor_iva_str) β strings "0.00".
Ejemplos:
_calcular_strings_fiscales(30.0, SUBTOTAL)
β ("34.50", "30.00", "4.50")
_calcular_strings_fiscales(30.0, TOTAL_CON_IVA)
β ("30.00", "26.09", "3.91")
"""
if monto <= 0:
raise ValueError(f"monto debe ser > 0. Recibido: {monto}")
rate = _iva_rate()
d = Decimal(str(monto))
if tipo == TipoMonto.TOTAL_CON_IVA:
total = _r2(d)
subtotal = _r2(d / (1 + rate))
iva = _r2(total - subtotal)
else: # SUBTOTAL
subtotal = _r2(d)
iva = _r2(d * rate)
total = _r2(subtotal + iva)
return str(total), str(subtotal), str(iva)
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# ConfiguraciΓ³n
# ---------------------------------------------------------------------------
logging.basicConfig(
level=logging.INFO,
format='{"time":"%(asctime)s", "level":"%(levelname)s", "name":"%(name)s", "message":"%(message)s"}',
)
logger = logging.getLogger("datafast-mcp")
install_logging_filter()
# ProducciΓ³n: https://eu-prod.oppwa.com | Sandbox: https://eu-test.oppwa.com
DATAFAST_BASE_URL = os.environ.get("DATAFAST_BASE_URL", "https://eu-prod.oppwa.com")
HTTP_TIMEOUT = float(os.environ.get("DATAFAST_HTTP_TIMEOUT", "30"))
mcp = FastMCP(
"datafast",
host=os.getenv("MCP_HOST", "0.0.0.0"), # nosec B104 β configurable via MCP_HOST env
instructions=(
"MCP server for Datafast Ecuador payment gateway (ACI Worldwide / Oppwa engine). "
"Supports card payments via hosted checkout widget, recurring charges with tokenized "
"cards, reversals, refunds and payment status queries. "
"bearer_token is loaded from DATAFAST_BEARER_TOKEN env var. Pass `entity_id` per call. "
"DO NOT pass bearer_token as a function argument β it is not in the signature. "
"STANDARD FLOW: "
" 1. Call crear_checkout β get checkoutId. "
" 2. Frontend renders the Datafast widget using that checkoutId. "
" 3. Call verificar_pago_checkout β confirm the result. "
"MONETARY INPUT RULES (agent must follow strictly): "
" Β· Pass `monto` (float) with the EXACT number the user stated. "
" Β· Pass `tipo_monto`='subtotal' if the amount is WITHOUT IVA (default). "
" Β· Pass `tipo_monto`='total_con_iva' if the amount ALREADY INCLUDES IVA. "
" Β· NEVER calculate subtotals, IVA, or string-format amounts yourself. "
" Β· The server computes subtotal_gravado, valor_iva, and amount from monto+tipo_monto. "
" Β· Approved result codes: 000.000.000 or 000.100.112. "
" Β· paymentType: DB=Direct debit/purchase, PA=Pre-authorization, "
" RV=Reversal (same-day void), RF=Refund (post-day). "
" Β· Set DATAFAST_BASE_URL=https://eu-test.oppwa.com for sandbox testing. "
"The IVA rate is read from IVA_EC_PERCENTAGE env var (default 15%)."
))
# ---------------------------------------------------------------------------
# Cliente HTTP reutilizable
# ---------------------------------------------------------------------------
def _resolve_bearer() -> str:
"""Validate and return the Datafast Bearer token."""
resolved = os.environ.get("DATAFAST_BEARER_TOKEN", "")
if not resolved:
raise ValueError(
"DATAFAST_BEARER_TOKEN env var is required. Configure it in your .env file."
)
return resolved
def _auth_headers() -> dict[str, str]:
"""Build Authorization headers for a specific Datafast account."""
return {"Authorization": f"Bearer {_resolve_bearer()}"}
async def _get(
path: str,
*,
params: dict[str, Any] | None = None) -> dict | list | str:
"""Execute a GET request against the Datafast API."""
url = f"{DATAFAST_BASE_URL}{path}"
if params:
params = {k: v for k, v in params.items() if v is not None and v != ""}
logger.info("GET %s params=%s", url, params)
async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as client:
resp = await client.get(url, headers=_auth_headers(), params=params)
logger.info("Respuesta HTTP %s", resp.status_code)
return _parse_response(resp)
async def _post_form(
path: str,
data: dict[str, Any]) -> dict | list | str:
"""Execute a POST with application/x-www-form-urlencoded."""
url = f"{DATAFAST_BASE_URL}{path}"
clean_data = {k: str(v) for k, v in data.items() if v is not None and v != ""}
logger.info("POST (form) %s data_keys=%s", url, list(clean_data.keys()))
async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as client:
resp = await client.post(
url,
headers=_auth_headers(),
data=clean_data)
logger.info("Respuesta HTTP %s", resp.status_code)
return _parse_response(resp)
async def _delete_form(
path: str,
*,
params: dict[str, Any] | None = None) -> dict | list | str:
"""Execute a DELETE request against the Datafast API."""
url = f"{DATAFAST_BASE_URL}{path}"
if params:
params = {k: v for k, v in params.items() if v is not None and v != ""}
logger.info("DELETE %s params=%s", url, params)
async with httpx.AsyncClient(timeout=HTTP_TIMEOUT) as client:
resp = await client.delete(url, headers=_auth_headers(), params=params)
logger.info("Respuesta HTTP %s", resp.status_code)
return _parse_response(resp)
def _parse_response(resp: httpx.Response) -> dict | list | str:
"""Parse a Datafast HTTP response."""
if resp.status_code >= 400:
return {
"error": True,
"status_code": resp.status_code,
"detail": resp.text,
}
if not resp.text.strip():
return {"ok": True, "status_code": resp.status_code}
try:
return resp.json()
except Exception:
return resp.text
def _is_approved(result_code: str) -> bool:
"""Indicate whether a Datafast result code is a success."""
return result_code in ("000.000.000", "000.100.112")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# CHECKOUT Y VERIFICACIΓN DE PAGO
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@mcp.tool()
async def crear_checkout(
entity_id: str,
monto: float,
payment_type: str,
tipo_monto: TipoMonto = TipoMonto.SUBTOTAL,
subtotal_iva0: str = "0.00",
valor_ice: str = "0.00",
currency: str = "USD",
merchant_transaction_id: str | None = None,
customer_email: str | None = None,
customer_nombre: str | None = None,
customer_apellido: str | None = None,
customer_doc_tipo: str | None = None,
customer_doc_numero: str | None = None,
billing_calle: str | None = None,
tokenizar_tarjeta: bool = False) -> str:
"""β οΈ MUTATION β Create a Checkout session in Datafast to initiate a card payment β POST /v1/checkouts.
Use this tool as STEP 1 of the standard Datafast payment flow.
The returned checkoutId is passed to the frontend Datafast widget (card form).
After the customer submits the card form, call verificar_pago_checkout.
MONETARY INPUT (agent MUST follow this contract):
monto (float): The EXACT amount the user stated β pass it verbatim, no rounding.
tipo_monto (enum):
Β· "subtotal" β monto is the taxable base WITHOUT IVA (default).
Β· "total_con_iva" β monto is the final price ALREADY INCLUDING IVA.
β οΈ DO NOT calculate subtotal_gravado, valor_iva, or format amounts as strings yourself.
The server computes all fiscal values and guarantees the Oppwa tax invariant:
amount == subtotal_iva0 + subtotal_gravado + valor_iva + valor_ice
Violation causes Datafast error code 100.400.500.
REQUIRED PARAMETERS:
entity_id (str): Commerce entity ID issued by Datafast.
Note: Datafast may issue different entityIds for Visa/MC vs Diners/Discover.
monto (float): Amount exactly as stated by the user. Example: 30.0
payment_type (str): Payment operation type.
Valid values: "DB"=Direct debit/purchase, "PA"=Pre-authorization.
OPTIONAL PARAMETERS:
tipo_monto (str, default="subtotal"): "subtotal" | "total_con_iva".
subtotal_iva0 (str, default="0.00"): Zero-rated base (Base Cero). Only set this
if part of the transaction is VAT-exempt.
valor_ice (str, default="0.00"): ICE tax amount (SHOPPER_VAL_ICE).
currency (str, default="USD"): Currency code.
merchant_transaction_id (str): Your system's order number for reconciliation.
tokenizar_tarjeta (bool, default=False): Set True to save the card and receive
a registrationId for future charges.
customer_email, customer_nombre, customer_apellido (str): Customer info.
customer_doc_tipo (str): "IDCARD" | "PASSPORT"
customer_doc_numero (str): Customer cedula or passport number.
billing_calle (str): Billing street address.
RETURNS:
JSON with 'id' (checkoutId) and 'result.code' (success = "000.200.100").
EXAMPLE CALLS:
# User says "charge $30 + VAT"
crear_checkout(entity_id="8ac7...", monto=30.0, tipo_monto="subtotal",
payment_type="DB")
# User says "charge $34.50 with VAT included"
crear_checkout(entity_id="8ac7...", monto=34.50, tipo_monto="total_con_iva",
payment_type="DB")
"""
# ββ CΓ‘lculo determinista (servidor, no el LLM) ββββββββββββββββββββββββββ
amount_str, subtotal_gravado_str, valor_iva_str = _calcular_strings_fiscales(
monto, tipo_monto
)
logger.info(
"[crear_checkout] monto=%.2f tipo=%s β amount=%s subtotal_gravado=%s valor_iva=%s",
monto, tipo_monto.value, amount_str, subtotal_gravado_str, valor_iva_str,
)
data: dict[str, Any] = {
"entityId": entity_id,
"amount": amount_str,
"currency": currency,
"paymentType": payment_type,
"customParameters[SHOPPER_VAL_BASE0]": subtotal_iva0,
"customParameters[SHOPPER_VAL_BASEIMP]": subtotal_gravado_str,
"customParameters[SHOPPER_VAL_IVA]": valor_iva_str,
"customParameters[SHOPPER_VAL_ICE]": valor_ice,
}
if merchant_transaction_id is not None:
data["merchantTransactionId"] = merchant_transaction_id
if customer_email is not None:
data["customer.email"] = customer_email
if customer_nombre is not None:
data["customer.givenName"] = customer_nombre
if customer_apellido is not None:
data["customer.surname"] = customer_apellido
if customer_doc_tipo is not None:
data["customer.identificationDocType"] = customer_doc_tipo
if customer_doc_numero is not None:
data["customer.identificationDocId"] = customer_doc_numero
if billing_calle is not None:
data["billing.street1"] = billing_calle
if tokenizar_tarjeta:
data["createRegistration"] = "true"
result = await _post_form("/v1/checkouts", data)
return json.dumps(result, ensure_ascii=False, default=str)
@mcp.tool()
async def verificar_pago_checkout( entity_id: str,
checkout_id: str) -> str:
"""Verify the final status of a Datafast payment after the customer completes the card form β GET /v1/checkouts/{id}/payment.
Use this tool as STEP 3 of the standard Datafast payment flow, after the frontend
redirects back with the resourcePath or after receiving a webhook notification.
REQUIRED PARAMETERS:
entity_id (str): Commerce entity ID issued by Datafast.
checkout_id (str): The checkoutId generated by crear_checkout.
Example: "1ABC23DEF456GH78"
RETURNS:
JSON with transaction result. Key fields:
- result.code: "000.000.000" or "000.100.112" = Approved.
- id: Real payment ID (use this for reversals/refunds, NOT the checkoutId).
- registrationId: Card token (only present if tokenizar_tarjeta=True was set).
- resultDetails.AuthCode: Bank authorization code.
- resultDetails.ReferenceNbr: Bank reference number.
EXAMPLE CALL:
verificar_pago_checkout(entity_id="8ac7...",
checkout_id="1ABC23DEF456GH78")
"""
result = await _get(
f"/v1/checkouts/{checkout_id}/payment",
params={"entityId": entity_id})
return json.dumps(result, ensure_ascii=False, default=str)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# CONSULTA POR ID DEL COMERCIO
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@mcp.tool()
async def consultar_pago_por_orden( entity_id: str,
merchant_transaction_id: str) -> str:
"""Search for a transaction by your internal order number β GET /v1/query.
Use this tool when you do not have the checkoutId but know the order number
you sent as merchant_transaction_id in crear_checkout.
REQUIRED PARAMETERS:
entity_id (str): Commerce entity ID issued by Datafast.
merchant_transaction_id (str): Your system's order number sent during crear_checkout.
Example: "ORDER-2025-0042"
RETURNS:
List of transactions matching the order number, each with result.code,
amount, id, and payment details.
EXAMPLE CALL:
consultar_pago_por_orden(entity_id="8ac7...",
merchant_transaction_id="ORDER-2025-0042")
"""
result = await _get(
"/v1/query",
params={
"entityId": entity_id,
"merchantTransactionId": merchant_transaction_id,
})
return json.dumps(result, ensure_ascii=False, default=str)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# REVERSALES Y REEMBOLSOS
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@mcp.tool()
async def reversar_reembolsar_pago( entity_id: str,
payment_id: str,
amount: str,
payment_type: str,
currency: str = "USD") -> str:
"""β οΈ MUTATION β Reverse or refund a previously approved payment β POST /v1/payments/{id}.
Use this tool to cancel or return funds for an approved transaction.
β οΈ IMPORTANT:
- payment_id is the 'id' field from verificar_pago_checkout response.
It is NOT the checkoutId. It is the real transaction ID issued after approval.
REQUIRED PARAMETERS:
entity_id (str): Commerce entity ID issued by Datafast.
payment_id (str): Real payment ID from verificar_pago_checkout (not checkoutId).
Example: "8ac7a4a2123456789abc0123"
amount (str): Amount to reverse/refund with 2 decimal places.
For full reversals, use the original transaction amount. Example: "12.50"
payment_type (str): Operation type.
"RV" = Reversal (void) β same-day ONLY, full cancellation.
"RF" = Refund β for days after the transaction.
OPTIONAL PARAMETERS:
currency (str, default="USD"): Currency code.
RETURNS:
JSON with result.code and refund/reversal confirmation details.
EXAMPLE CALL:
reversar_reembolsar_pago(entity_id="8ac7...",
payment_id="8ac7a4a2123456789abc",
amount="12.50", payment_type="RF")
"""
try:
amount_float = float(amount)
validate_amount(amount_float, "amount")
except ValueError as exc:
raise ValueError(f"amount debe ser un string numΓ©rico vΓ‘lido: {exc}") from exc
data: dict[str, Any] = {
"entityId": entity_id,
"amount": amount,
"currency": currency,
"paymentType": payment_type,
}
result = await _post_form(f"/v1/payments/{payment_id}", data)
return json.dumps(result, ensure_ascii=False, default=str)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PAGOS RECURRENTES / ONECLICK (TARJETAS TOKENIZADAS)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@mcp.tool()
async def pago_recurrente_oneclick( entity_id: str,
registration_id: str,
amount: str,
currency: str = "USD",
payment_type: str = "DB",
shopper_result_url: str | None = None) -> str:
"""β οΈ MUTATION β Charge a tokenized (saved) card for recurring or OneClick payments β POST /v1/registrations/{id}/payments.
Use this tool to charge a card that was previously saved via tokenizar_tarjeta=True
in crear_checkout. The registrationId was returned in verificar_pago_checkout.
REQUIRED PARAMETERS:
entity_id (str): Commerce entity ID issued by Datafast.
registration_id (str): Card token (registrationId) from verificar_pago_checkout.
Example: "8ac7a4a2-abcd-1234-efgh-5678"
amount (str): Amount to charge with 2 decimal places. Example: "99.00"
OPTIONAL PARAMETERS:
currency (str, default="USD"): Currency code.
payment_type (str, default="DB"): Payment operation. "DB"=Direct purchase.
shopper_result_url (str): REQUIRED if the card triggers a 3D Secure challenge.
The customer will be redirected here after 3DS authentication.
RETURNS:
JSON with result.code ("000.000.000"=Approved), transaction id,
authorizationCode, and card details.
EXAMPLE CALL:
pago_recurrente_oneclick(entity_id="8ac7...",
registration_id="8ac7a4a2-abcd", amount="99.00")
"""
try:
amount_float = float(amount)
validate_amount(amount_float, "amount")
except ValueError as exc:
raise ValueError(f"amount debe ser un string numΓ©rico vΓ‘lido: {exc}") from exc
if shopper_result_url is not None:
# Anti-SSRF: bloquea metadata IPs, loopback, private ranges, http://
shopper_result_url = validate_safe_url(shopper_result_url, "shopper_result_url")
data: dict[str, Any] = {
"entityId": entity_id,
"amount": amount,
"currency": currency,
"paymentType": payment_type,
}
if shopper_result_url is not None:
data["shopperResultUrl"] = shopper_result_url
result = await _post_form(
f"/v1/registrations/{registration_id}/payments", data)
return json.dumps(result, ensure_ascii=False, default=str)
@mcp.tool()
async def eliminar_token_tarjeta( entity_id: str,
registration_id: str) -> str:
"""β οΈ IRREVERSIBLE MUTATION β Delete a saved card token from the Datafast vault β DELETE /v1/registrations/{id}.
Use this tool when a customer requests deletion of their saved card.
Once deleted, the registrationId cannot be used for future charges.
REQUIRED PARAMETERS:
entity_id (str): Commerce entity ID issued by Datafast.
registration_id (str): Card token (registrationId) to delete.
Example: "8ac7a4a2-abcd-1234-efgh-5678"
RETURNS:
JSON confirmation of the deletion.
EXAMPLE CALL:
eliminar_token_tarjeta(entity_id="8ac7...",
registration_id="8ac7a4a2-abcd-1234-efgh-5678")
"""
result = await _delete_form(
f"/v1/registrations/{registration_id}",
params={"entityId": entity_id})
return json.dumps(result, ensure_ascii=False, default=str)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# UTILIDADES
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@mcp.tool()
async def interpretar_codigo_resultado(code: str) -> str:
"""Interpret the meaning of a Datafast result code from a transaction response.
Use this tool to understand whether a result.code from any Datafast operation
means the transaction was approved, pending, or rejected.
This tool does NOT require credentials (local lookup only).
REQUIRED PARAMETERS:
code (str): Datafast result code to interpret.
Examples: "000.000.000" (approved), "800.100.152" (declined by bank),
"100.400.500" (tax validation error).
RETURNS:
{"code": str, "descripcion": str, "aprobada": bool, "pendiente": bool, "rechazada": bool}
EXAMPLE CALL:
interpretar_codigo_resultado(code="800.100.152")
"""
import re
approved_patterns = [
r"^000\.000\.",
r"^000\.100\.1",
r"^000\.300\.",
r"^000\.400\.0",
]
pending_patterns = [
r"^000\.200\.",
r"^800\.400\.5",
]
rejected_patterns = [
r"^800\.100\.",
r"^900\.100\.",
r"^800\.200\.",
r"^100\.400\.",
r"^200\.300\.",
]
is_approved = any(re.match(p, code) for p in approved_patterns)
is_pending = any(re.match(p, code) for p in pending_patterns)
is_rejected = any(re.match(p, code) for p in rejected_patterns)
known_codes: dict[str, str] = {
"000.000.000": "β
APROBADA β TransacciΓ³n exitosa.",
"000.100.112": "β
APROBADA β TransacciΓ³n aprobada (pendiente de confirmaciΓ³n batch).",
"800.100.152": "β RECHAZADA β Declinada por el banco (fondos insuficientes u otro motivo).",
"800.100.162": "β RECHAZADA β Declinada por el banco (restricciΓ³n de la cuenta).",
"100.400.500": "β οΈ ERROR β Datos invΓ‘lidos. Verificar que la suma de impuestos coincida con el amount total.",
}
if code in known_codes:
descripcion = known_codes[code]
elif is_approved:
descripcion = "β
APROBADA segΓΊn el patrΓ³n del cΓ³digo."
elif is_pending:
descripcion = "β³ PENDIENTE β La transacciΓ³n estΓ‘ en proceso."
elif is_rejected:
descripcion = "β RECHAZADA segΓΊn el patrΓ³n del cΓ³digo."
else:
descripcion = "β DESCONOCIDO β Consultar documentaciΓ³n de ACI Worldwide."
return json.dumps(
{
"code": code,
"descripcion": descripcion,
"aprobada": is_approved,
"pendiente": is_pending,
"rechazada": is_rejected,
},
ensure_ascii=False)
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
import uvicorn
port = int(os.getenv("MCP_PORT", 8000))
transport_mode = os.getenv("MCP_TRANSPORT_MODE", "sse").lower()
print(f"Starting Datafast MCP Server on http://0.0.0.0:{port}/mcp ({transport_mode})")
if transport_mode == "sse":
app = mcp.sse_app()
elif transport_mode == "http_stream":
app = mcp.streamable_http_app()
else:
raise ValueError(f"Unknown transport mode: {transport_mode}")
uvicorn.run(app, host=os.getenv("MCP_HOST", "0.0.0.0"), port=port) # nosec B104 β configurable via MCP_HOST env