collection-api-refacil-mcp 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,933 @@
1
+ // Tipos para herramientas MCP
2
+ import { z } from 'zod';
3
+ import axios from 'axios';
4
+ import { getAuthHeaders } from './auth.js';
5
+ import { appConfig } from '../config.js';
6
+ // Configuración de la API
7
+ const API_CONFIG = {
8
+ get baseUrl() {
9
+ return appConfig.baseUrl;
10
+ },
11
+ timeout: 30000
12
+ };
13
+ // Helper para asignar valores definidos (incluye null) sin mutar argumentos originales
14
+ function assignIfDefined(target, source, key) {
15
+ if (Object.prototype.hasOwnProperty.call(source, key) && source[key] !== undefined) {
16
+ target[key] = source[key];
17
+ }
18
+ }
19
+ // Función helper para hacer requests HTTP
20
+ // secretId puede venir del contexto de la request (HTTP mode) o undefined (STDIO mode)
21
+ // additionalHeaders permite pasar headers adicionales como x-transaction-token
22
+ async function makeApiRequest(method, endpoint, data, params, secretId, additionalHeaders) {
23
+ try {
24
+ // Obtener headers de autenticación según el tipo
25
+ const authHeaders = await getAuthHeaders(secretId);
26
+ // Combinar headers de autenticación con headers adicionales
27
+ const headers = { ...authHeaders, ...(additionalHeaders || {}) };
28
+ const url = `${API_CONFIG.baseUrl}${endpoint}`;
29
+ const config = {
30
+ method: method.toLowerCase(),
31
+ url,
32
+ headers,
33
+ timeout: API_CONFIG.timeout
34
+ };
35
+ if (params && Object.keys(params).length > 0) {
36
+ config.params = params;
37
+ }
38
+ if (data && method !== 'GET') {
39
+ config.data = data;
40
+ }
41
+ const response = await axios(config);
42
+ // Formato estándar del protocolo MCP
43
+ return {
44
+ content: [
45
+ {
46
+ type: 'text',
47
+ text: JSON.stringify({
48
+ success: true,
49
+ statusCode: response.status,
50
+ data: response.data,
51
+ message: 'Operación exitosa'
52
+ }, null, 2)
53
+ }
54
+ ]
55
+ };
56
+ }
57
+ catch (error) {
58
+ const errorData = {
59
+ success: false,
60
+ statusCode: error.response?.status || 500,
61
+ data: error.response?.data || null,
62
+ message: error.response?.data?.message || error.message || 'Error en la operación',
63
+ error: error.code || 'UNKNOWN_ERROR'
64
+ };
65
+ // Formato estándar del protocolo MCP para errores
66
+ return {
67
+ content: [
68
+ {
69
+ type: 'text',
70
+ text: JSON.stringify(errorData, null, 2)
71
+ }
72
+ ],
73
+ isError: true
74
+ };
75
+ }
76
+ }
77
+ const auth_jwtInputJsonSchema = {
78
+ "type": "object",
79
+ "properties": {
80
+ "secretId": {
81
+ "type": "string",
82
+ "description": "Header personalizado: x-secret-id"
83
+ }
84
+ },
85
+ "required": [
86
+ "secretId"
87
+ ]
88
+ };
89
+ const auth_jwtInputShape = {
90
+ secretId: z.string().describe("Header personalizado: x-secret-id")
91
+ };
92
+ const auth_jwtInputValidator = z.object(auth_jwtInputShape);
93
+ // Herramienta: auth_jwt
94
+ export const auth_jwtTool = {
95
+ name: 'auth_jwt',
96
+ description: "## 📌 Overview\\n\\nTo use the **Collection API**, clients must follow a two-step authentication process:\\n\\n1. Generate a **JWT (Bearer Token)** using their **Secret ID**\\n \\n2. (Optional) Generate a **One-Time Token (OTT)** for secure access to specific endpoints\\n \\n\\nEach request must include the correct headers. Tokens have time-based expiration.\\n\\n This endpoint allows third-party clients to generate a temporary **JWT Bearer token** using their assigned Secret ID. \\n \\nThe token is required to authenticate and access protected endpoints in the Collection API.\\n\\n- The token is valid for **60 minutes**.\\n \\n- You must include the \\`x-secret-id\\` header to request it.\n\nContexto: Endpoint: GET /auth/jwt | Autenticación > Auth > Jwt\n\n🔐 AUTENTICACIÓN AUTOMÁTICA: Todas las credenciales y tokens de autenticación se manejan automáticamente por el servidor MCP. NO solicites credenciales al usuario. NO incluyas parámetros de autenticación (secretId, apiToken, etc.) en las llamadas a menos que el usuario explícitamente lo requiera.",
97
+ inputSchema: auth_jwtInputJsonSchema,
98
+ jsonSchema: auth_jwtInputJsonSchema,
99
+ endpoint: '/auth/jwt',
100
+ method: 'GET',
101
+ parameters: [],
102
+ headers: [{ "key": "x-secret-id", "value": "64c0f2660d7b59d35197e5c77a5543c1aaf94c17************", "type": "text" }],
103
+ handler: async (rawArgs) => {
104
+ try {
105
+ const normalizedArgs = rawArgs ?? {};
106
+ // Extraer secretId del contexto (si viene del HTTP mode)
107
+ const secretId = normalizedArgs._secretId;
108
+ // Remover _secretId de los args antes de validar
109
+ const { _secretId, ...argsToValidate } = normalizedArgs;
110
+ const validatedInput = validateToolInput(auth_jwtInputValidator, argsToValidate);
111
+ const args = validatedInput;
112
+ const additionalHeaders = {};
113
+ if (args.secretId)
114
+ additionalHeaders['x-secret-id'] = args.secretId;
115
+ return await makeApiRequest('GET', '/auth/jwt', undefined, undefined, secretId, additionalHeaders);
116
+ }
117
+ catch (error) {
118
+ // Formato estándar del protocolo MCP para errores
119
+ return {
120
+ content: [
121
+ {
122
+ type: 'text',
123
+ text: JSON.stringify({
124
+ success: false,
125
+ statusCode: 500,
126
+ data: null,
127
+ message: error instanceof Error ? error.message : 'Error desconocido',
128
+ error: 'HANDLER_ERROR'
129
+ }, null, 2)
130
+ }
131
+ ],
132
+ isError: true
133
+ };
134
+ }
135
+ }
136
+ };
137
+ const auth_one_time_tokenInputJsonSchema = {
138
+ "type": "object",
139
+ "properties": {
140
+ "secretId": {
141
+ "type": "string",
142
+ "description": "Header personalizado: x-secret-id"
143
+ },
144
+ "service": {
145
+ "type": "string",
146
+ "description": "Campo del body: service",
147
+ "default": "/collection/submit-payment"
148
+ }
149
+ },
150
+ "required": [
151
+ "secretId"
152
+ ]
153
+ };
154
+ const auth_one_time_tokenInputShape = {
155
+ secretId: z.string().describe("Header personalizado: x-secret-id"),
156
+ service: z.string().optional().describe("Campo del body: service")
157
+ };
158
+ const auth_one_time_tokenInputValidator = z.object(auth_one_time_tokenInputShape);
159
+ // Herramienta: auth_one_time_token
160
+ export const auth_one_time_tokenTool = {
161
+ name: 'auth_one_time_token',
162
+ description: "## 📌 Overview\\n\\nTo use the **Collection API**, clients must follow a two-step authentication process:\\n\\n1. Generate a **JWT (Bearer Token)** using their **Secret ID**\\n \\n2. (Optional) Generate a **One-Time Token (OTT)** for secure access to specific endpoints\\n \\n\\nEach request must include the correct headers. Tokens have time-based expiration.\\n\\n This endpoint generates a **single-use token** that provides an extra layer of security for sensitive operations.\\n\\n- The token is valid for **60 seconds** and can only be used **once**.\\n \\n- You must include both \\`x-secret-id\\` and \\`Authorization: Bearer\\` headers to request it.\\n \\n\\n### 🔐 **Endpoints that require One-Time Token**\\n\\n| HTTP Method | Endpoint URL | Description |\\n| --- | --- | --- |\\n| \\`POST\\` | \\`/collection/submit-payment\\` | Registers a payment or top-up at a branch |\n\nContexto: Endpoint: POST /auth/one-time-token | Autenticación > Auth > One time token\n\n🔐 AUTENTICACIÓN AUTOMÁTICA: Todas las credenciales y tokens de autenticación se manejan automáticamente por el servidor MCP. NO solicites credenciales al usuario. NO incluyas parámetros de autenticación (secretId, apiToken, etc.) en las llamadas a menos que el usuario explícitamente lo requiera.",
163
+ inputSchema: auth_one_time_tokenInputJsonSchema,
164
+ jsonSchema: auth_one_time_tokenInputJsonSchema,
165
+ endpoint: '/auth/one-time-token',
166
+ method: 'POST',
167
+ parameters: [],
168
+ headers: [{ "key": "x-secret-id", "value": "64c0f2660d7b59d35197e5c77a5543c1aaf94c17************", "type": "text" }, { "key": "Authorization", "value": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiUGlwZSBUZXN0IiwiY3VzdG9tZXJJZCI6NzgyLCJpYXQiOjE3NTE4OTc5MzUsImV4cCI6MTc1MTkwMTUzNX0.dHKl4DduA8ySqG2KkSVoGWLi0IujplL0olDopsUR4L_bQXhJKBfTg98JukRd8JpOXSOtKwy6TgPiiLA7AMFedbthfkAR_fFBw7Bxvr88vIMfj6BkCIUm2HdO_CX1bkLK0AxMRJx1Qvvq9eyE3ojhDrrgU6QndcCMjI3EQ0EFZVuGzKkw2JEa3QygUbtN5O6sGIJxMS6fOjFqAwoLHRzY16kztWtqK3EYQNYD-eH9rt7-cdMiZ_3sxxOBKi8NPKJdlCQ3d8YA6kcdYwK74nEj6SR_19uy6lY_5AMRE6jrWyad2BwjZ74uuXtv5X3JflE5rpANe7tYUTASS-9Dwb9x3w", "type": "text" }],
169
+ handler: async (rawArgs) => {
170
+ try {
171
+ const normalizedArgs = rawArgs ?? {};
172
+ // Extraer secretId del contexto (si viene del HTTP mode)
173
+ const secretId = normalizedArgs._secretId;
174
+ // Remover _secretId de los args antes de validar
175
+ const { _secretId, ...argsToValidate } = normalizedArgs;
176
+ const validatedInput = validateToolInput(auth_one_time_tokenInputValidator, argsToValidate);
177
+ const args = validatedInput;
178
+ const bodyData = {};
179
+ const serviceValue = args.service !== undefined ? args.service : "/collection/submit-payment";
180
+ if (serviceValue !== undefined)
181
+ bodyData.service = serviceValue;
182
+ const additionalHeaders = {};
183
+ if (args.secretId)
184
+ additionalHeaders['x-secret-id'] = args.secretId;
185
+ return await makeApiRequest('POST', '/auth/one-time-token', bodyData, undefined, secretId, additionalHeaders);
186
+ }
187
+ catch (error) {
188
+ // Formato estándar del protocolo MCP para errores
189
+ return {
190
+ content: [
191
+ {
192
+ type: 'text',
193
+ text: JSON.stringify({
194
+ success: false,
195
+ statusCode: 500,
196
+ data: null,
197
+ message: error instanceof Error ? error.message : 'Error desconocido',
198
+ error: 'HANDLER_ERROR'
199
+ }, null, 2)
200
+ }
201
+ ],
202
+ isError: true
203
+ };
204
+ }
205
+ }
206
+ };
207
+ const collection_submit_paymentInputJsonSchema = {
208
+ "type": "object",
209
+ "properties": {
210
+ "secretId": {
211
+ "type": "string",
212
+ "description": "Header personalizado: x-secret-id"
213
+ },
214
+ "oneTimeToken": {
215
+ "type": "string",
216
+ "description": "Header personalizado: x-one-time-token"
217
+ },
218
+ "reference": {
219
+ "type": "number",
220
+ "description": "Campo del body: reference",
221
+ "default": 100863
222
+ },
223
+ "agreementId": {
224
+ "type": "number",
225
+ "description": "Campo del body: agreementId",
226
+ "default": 2
227
+ },
228
+ "amount": {
229
+ "type": "number",
230
+ "description": "Campo del body: amount",
231
+ "default": 10000
232
+ },
233
+ "date": {
234
+ "type": "string",
235
+ "description": "Campo del body: date",
236
+ "default": "2025-03-30"
237
+ },
238
+ "time": {
239
+ "type": "string",
240
+ "description": "Campo del body: time",
241
+ "default": "01:30"
242
+ }
243
+ },
244
+ "required": [
245
+ "secretId",
246
+ "oneTimeToken"
247
+ ]
248
+ };
249
+ const collection_submit_paymentInputShape = {
250
+ secretId: z.string().describe("Header personalizado: x-secret-id"),
251
+ oneTimeToken: z.string().describe("Header personalizado: x-one-time-token"),
252
+ reference: z.number().optional().describe("Campo del body: reference"),
253
+ agreementId: z.number().optional().describe("Campo del body: agreementId"),
254
+ amount: z.number().optional().describe("Campo del body: amount"),
255
+ date: z.string().optional().describe("Campo del body: date"),
256
+ time: z.string().optional().describe("Campo del body: time")
257
+ };
258
+ const collection_submit_paymentInputValidator = z.object(collection_submit_paymentInputShape);
259
+ // Herramienta: collection_submit_payment
260
+ export const collection_submit_paymentTool = {
261
+ name: 'collection_submit_payment',
262
+ description: "## Description\\n\\nThis endpoint handles financial transactions and collections. It processes payments, validates customers and companies, and integrates with a payment processing system. The service includes transaction amount validation, customer verification, and company balance management.\\n\\n### 📥 Request Body Parameters\\n\\n| Field | Type | Required | Description |\\n| --- | --- | --- | --- |\\n| \\`reference\\` | Integer | ✅ | Unique transaction reference number |\\n| \\`agreementId\\` | Integer | ✅ | ID of the agreement (company) that is making the payment |\\n| \\`amount\\` | Integer | ✅ | Amount to be charged, in COP (Colombian Pesos) |\\n| \\`date\\` | String | ✅ | Transaction date in format \\`YYYY-MM-DD\\` |\\n| \\`time\\` | String | ✅ | Transaction time in format \\`HH:mm\\` (24-hour clock, Bogotá time zone) |\\n\\n---\\n\\n### 🏢 Available Agreements\\n\\n| \\`agreementId\\` | Company Name |\\n| --- | --- |\\n| \\`18252\\` | Apostar |\\n| \\`18253\\` | Susuerte |\\n\\n⚠️ Only the above \\`agreementId\\`s are currently authorized to use this service.\\n\\n---\n\nContexto: Endpoint: POST /collection/submit-payment | Collection > Submit payment\n\n🔐 AUTENTICACIÓN AUTOMÁTICA: Todas las credenciales y tokens de autenticación se manejan automáticamente por el servidor MCP. NO solicites credenciales al usuario. NO incluyas parámetros de autenticación (secretId, apiToken, etc.) en las llamadas a menos que el usuario explícitamente lo requiera.",
263
+ inputSchema: collection_submit_paymentInputJsonSchema,
264
+ jsonSchema: collection_submit_paymentInputJsonSchema,
265
+ endpoint: '/collection/submit-payment',
266
+ method: 'POST',
267
+ parameters: [],
268
+ headers: [{ "key": "Content-Type", "value": "application/json" }, { "key": "x-secret-id", "value": "64c0f2660d7b59d35197e5c77a5543c1aaf94c17************", "type": "text" }, { "key": "Authorization", "value": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiUGlwZSBUZXN0IiwiY3VzdG9tZXJJZCI6NzgyLCJpYXQiOjE3NTE4OTc5MzUsImV4cCI6MTc1MTkwMTUzNX0.dHKl4DduA8ySqG2KkSVoGWLi0IujplL0olDopsUR4L_bQXhJKBfTg98JukRd8JpOXSOtKwy6TgPiiLA7AMFedbthfkAR_fFBw7Bxvr88vIMfj6BkCIUm2HdO_CX1bkLK0AxMRJx1Qvvq9eyE3ojhDrrgU6QndcCMjI3EQ0EFZVuGzKkw2JEa3QygUbtN5O6sGIJxMS6fOjFqAwoLHRzY16kztWtqK3EYQNYD-eH9rt7-cdMiZ_3sxxOBKi8NPKJdlCQ3d8YA6kcdYwK74nEj6SR_19uy6lY_5AMRE6jrWyad2BwjZ74uuXtv5X3JflE5rpANe7tYUTASS-9Dwb9x3w", "type": "text" }, { "key": "x-one-time-token", "value": "741e5c62-758d-4a3f-8ba4-4c2a0e2c0828", "type": "text" }],
269
+ handler: async (rawArgs) => {
270
+ try {
271
+ const normalizedArgs = rawArgs ?? {};
272
+ // Extraer secretId del contexto (si viene del HTTP mode)
273
+ const secretId = normalizedArgs._secretId;
274
+ // Remover _secretId de los args antes de validar
275
+ const { _secretId, ...argsToValidate } = normalizedArgs;
276
+ const validatedInput = validateToolInput(collection_submit_paymentInputValidator, argsToValidate);
277
+ const args = validatedInput;
278
+ const bodyData = {};
279
+ const referenceValue = args.reference !== undefined ? args.reference : 100863;
280
+ if (referenceValue !== undefined)
281
+ bodyData.reference = referenceValue;
282
+ const agreementIdValue = args.agreementId !== undefined ? args.agreementId : 2;
283
+ if (agreementIdValue !== undefined)
284
+ bodyData.agreementId = agreementIdValue;
285
+ const amountValue = args.amount !== undefined ? args.amount : 10000;
286
+ if (amountValue !== undefined)
287
+ bodyData.amount = amountValue;
288
+ const dateValue = args.date !== undefined ? args.date : "2025-03-30";
289
+ if (dateValue !== undefined)
290
+ bodyData.date = dateValue;
291
+ const timeValue = args.time !== undefined ? args.time : "01:30";
292
+ if (timeValue !== undefined)
293
+ bodyData.time = timeValue;
294
+ const additionalHeaders = {};
295
+ if (args.secretId)
296
+ additionalHeaders['x-secret-id'] = args.secretId;
297
+ if (args.oneTimeToken)
298
+ additionalHeaders['x-one-time-token'] = args.oneTimeToken;
299
+ return await makeApiRequest('POST', '/collection/submit-payment', bodyData, undefined, secretId, additionalHeaders);
300
+ }
301
+ catch (error) {
302
+ // Formato estándar del protocolo MCP para errores
303
+ return {
304
+ content: [
305
+ {
306
+ type: 'text',
307
+ text: JSON.stringify({
308
+ success: false,
309
+ statusCode: 500,
310
+ data: null,
311
+ message: error instanceof Error ? error.message : 'Error desconocido',
312
+ error: 'HANDLER_ERROR'
313
+ }, null, 2)
314
+ }
315
+ ],
316
+ isError: true
317
+ };
318
+ }
319
+ }
320
+ };
321
+ const auth_validateInputJsonSchema = {
322
+ "type": "object",
323
+ "properties": {
324
+ "secretId": {
325
+ "type": "string",
326
+ "description": "Campo del body: secretId",
327
+ "default": "fe4618ed155f863fb60d183e30a9634f90dce6cc725ed9fa31fab633de5416cc"
328
+ },
329
+ "token": {
330
+ "type": "string",
331
+ "description": "Campo del body: token",
332
+ "default": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQXBvc3RhciIsImN1c3RvbWVySWQiOjIxMTksInVzZXJJZCI6MTAwMzQ0MSwiaWF0IjoxNzU0MDA4MTc5LCJleHAiOjE3NTQwMTE3Nzl9.l7TdMeKfApwJVhs1CM8srG7WOARRagCxg8FRgxrabYw7l8Qk93Re4BzngIc3g5U0zUZtoajBPWCi54D27EI7DpVEp6TmhnodPWc9Ux603DmhqNviYLIQACgtj03K8xEIa4DNqlT0VKFDRDtEBMe4nLaBjYjlS-mpi-IErFxoXoJFL2lelm_H4lPzlCboP-VRP6X0xEJo3gAiaiqy5OHPi53Kq_hPCldQYXnkbLJxHyDVAlqNG5RyG5D6sCggxycfd8U2l0RaXOEDk-WaSYd7RFJreFZooEskS06DkB31zMEVskDuFugkVM7pN0XSwzPkFHjS1UIw8gvMB15-v7I5zQ"
333
+ }
334
+ },
335
+ "required": []
336
+ };
337
+ const auth_validateInputShape = {
338
+ secretId: z.string().optional().describe("Campo del body: secretId"),
339
+ token: z.string().optional().describe("Campo del body: token")
340
+ };
341
+ const auth_validateInputValidator = z.object(auth_validateInputShape);
342
+ // Herramienta: auth_validate
343
+ export const auth_validateTool = {
344
+ name: 'auth_validate',
345
+ description: "## 📝Recommendations\\n\\n- Establish a dedicated **QA environment** to perform thorough testing before production deployment.\\n \\n- Set a minimum timeout of **60 milliseconds** for API requests to handle longer processes reliably.\\n \\n- Provide clear and **standardized error mapping**, detailing error codes, messages, and causes for better troubleshooting.\\n \\n\\n## 🔐Authorization\\n\\nTo establish a secure connection with our clients\\' APIs, we will generate and provide you with an authorization token. This token will allow us to authenticate with the API that our clients build.\\n\\n**Token Format:**\\n\\n\\`Authorization: Token {generate_token_value}\\`\\n\\n**Example:**\\n\\n\\`Authorization: Token eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9**\\`\\n\\n This endpoint allows you to validate a JWT token by sending an HTTP POST request to {{base_url}}/auth/validate.\\n\\n**Base URL:**\\n\\n| **Enviroment** | **Value** |\\n| --- | --- |\\n| QA | [https://collection-api.qa.refacil.co](https://collection-api.qa.refacil.co) |\\n| PROD | [https://collection-api.refacil.co](https://collection-api.refacil.co) |\\n\\n### 📥 Request Body Parameters\\n\\n| Field | Type | Required | Description |\\n| --- | --- | --- | --- |\\n| secretId | string | ✅ | The secret identifier used to validate the token. **This secretId will be shared by us with the client** |\\n| token | string | ✅ | The JWT token to be validated |\\n\\n### 📤 Response body parameters\\n\\n| Field | Type | Description |\\n| --- | --- | --- |\\n| statusCode | number | The HTTP status code of the response |\\n| message | string | A message indicating the result of the operation |\\n| date | number | The timestamp of the response |\\n| payload | object | The response payload containing validation results |\\n| payload.valid | boolean | Indicates whether the token is valid or not |\\n| payload.message | string | A message related to the validation result |\\n| payload.data | object | Optional decoded token data if the token is valid |\n\nContexto: Endpoint: POST /auth/validate | Autenticación > Auth > Validate\n\n🔐 AUTENTICACIÓN AUTOMÁTICA: Todas las credenciales y tokens de autenticación se manejan automáticamente por el servidor MCP. NO solicites credenciales al usuario. NO incluyas parámetros de autenticación (secretId, apiToken, etc.) en las llamadas a menos que el usuario explícitamente lo requiera.",
346
+ inputSchema: auth_validateInputJsonSchema,
347
+ jsonSchema: auth_validateInputJsonSchema,
348
+ endpoint: '/auth/validate',
349
+ method: 'POST',
350
+ parameters: [],
351
+ headers: [{ "key": "Authorization", "value": "Token {{customer_token}}", "type": "text" }],
352
+ handler: async (rawArgs) => {
353
+ try {
354
+ const normalizedArgs = rawArgs ?? {};
355
+ // Extraer secretId del contexto (si viene del HTTP mode)
356
+ const secretId = normalizedArgs._secretId;
357
+ // Remover _secretId de los args antes de validar
358
+ const { _secretId, ...argsToValidate } = normalizedArgs;
359
+ const validatedInput = validateToolInput(auth_validateInputValidator, argsToValidate);
360
+ const args = validatedInput;
361
+ const bodyData = {};
362
+ const secretIdValue = args.secretId !== undefined ? args.secretId : "fe4618ed155f863fb60d183e30a9634f90dce6cc725ed9fa31fab633de5416cc";
363
+ if (secretIdValue !== undefined)
364
+ bodyData.secretId = secretIdValue;
365
+ const tokenValue = args.token !== undefined ? args.token : "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiQXBvc3RhciIsImN1c3RvbWVySWQiOjIxMTksInVzZXJJZCI6MTAwMzQ0MSwiaWF0IjoxNzU0MDA4MTc5LCJleHAiOjE3NTQwMTE3Nzl9.l7TdMeKfApwJVhs1CM8srG7WOARRagCxg8FRgxrabYw7l8Qk93Re4BzngIc3g5U0zUZtoajBPWCi54D27EI7DpVEp6TmhnodPWc9Ux603DmhqNviYLIQACgtj03K8xEIa4DNqlT0VKFDRDtEBMe4nLaBjYjlS-mpi-IErFxoXoJFL2lelm_H4lPzlCboP-VRP6X0xEJo3gAiaiqy5OHPi53Kq_hPCldQYXnkbLJxHyDVAlqNG5RyG5D6sCggxycfd8U2l0RaXOEDk-WaSYd7RFJreFZooEskS06DkB31zMEVskDuFugkVM7pN0XSwzPkFHjS1UIw8gvMB15-v7I5zQ";
366
+ if (tokenValue !== undefined)
367
+ bodyData.token = tokenValue;
368
+ return await makeApiRequest('POST', '/auth/validate', bodyData, undefined, secretId);
369
+ }
370
+ catch (error) {
371
+ // Formato estándar del protocolo MCP para errores
372
+ return {
373
+ content: [
374
+ {
375
+ type: 'text',
376
+ text: JSON.stringify({
377
+ success: false,
378
+ statusCode: 500,
379
+ data: null,
380
+ message: error instanceof Error ? error.message : 'Error desconocido',
381
+ error: 'HANDLER_ERROR'
382
+ }, null, 2)
383
+ }
384
+ ],
385
+ isError: true
386
+ };
387
+ }
388
+ }
389
+ };
390
+ const pingInputJsonSchema = {
391
+ "type": "object",
392
+ "properties": {},
393
+ "required": []
394
+ };
395
+ const pingInputShape = {};
396
+ const pingInputValidator = z.object(pingInputShape);
397
+ // Herramienta: ping
398
+ export const pingTool = {
399
+ name: 'ping',
400
+ description: "## 📝Recommendations\\n\\n- Establish a dedicated **QA environment** to perform thorough testing before production deployment.\\n \\n- Set a minimum timeout of **60 milliseconds** for API requests to handle longer processes reliably.\\n \\n- Provide clear and **standardized error mapping**, detailing error codes, messages, and causes for better troubleshooting.\\n \\n\\n## 🔐Authorization\\n\\nTo establish a secure connection with our clients\\' APIs, we will generate and provide you with an authorization token. This token will allow us to authenticate with the API that our clients build.\\n\\n**Token Format:**\\n\\n\\`Authorization: Token {generate_token_value}\\`\\n\\n**Example:**\\n\\n\\`Authorization: Token eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9**\\`\\n\\n This endpoint sends an HTTP GET request to {{customer.domain.com}}/ping/ in order to check the availability of the server.\\n\\n### Benefits 🩺\\n\\n- **Fail-fast**: detects unavailability before critical operations.\\n \\n- **SLO-aware**: monitor per-client availability and trigger mitigations.\\n \\n- **Proactive ops**: enables circuit breakers and routing policies.\\n \\n\\nThe request does not contain a request body.\\n\\n### Response\\n\\n- Status: 200\\n \\n- Body: \\\"pong\\\"\n\nContexto: Endpoint: GET /ping/ | Ping\n\n🔐 AUTENTICACIÓN AUTOMÁTICA: Todas las credenciales y tokens de autenticación se manejan automáticamente por el servidor MCP. NO solicites credenciales al usuario. NO incluyas parámetros de autenticación (secretId, apiToken, etc.) en las llamadas a menos que el usuario explícitamente lo requiera.",
401
+ inputSchema: pingInputJsonSchema,
402
+ jsonSchema: pingInputJsonSchema,
403
+ endpoint: '/ping/',
404
+ method: 'GET',
405
+ parameters: [],
406
+ headers: [{ "key": "Authorization", "value": "Token {{generate_token}}", "type": "text" }],
407
+ handler: async (rawArgs) => {
408
+ try {
409
+ const normalizedArgs = rawArgs ?? {};
410
+ // Extraer secretId del contexto (si viene del HTTP mode)
411
+ const secretId = normalizedArgs._secretId;
412
+ // Remover _secretId de los args antes de validar
413
+ const { _secretId, ...argsToValidate } = normalizedArgs;
414
+ const validatedInput = validateToolInput(pingInputValidator, argsToValidate);
415
+ const args = validatedInput;
416
+ return await makeApiRequest('GET', '/ping/', undefined, undefined, secretId);
417
+ }
418
+ catch (error) {
419
+ // Formato estándar del protocolo MCP para errores
420
+ return {
421
+ content: [
422
+ {
423
+ type: 'text',
424
+ text: JSON.stringify({
425
+ success: false,
426
+ statusCode: 500,
427
+ data: null,
428
+ message: error instanceof Error ? error.message : 'Error desconocido',
429
+ error: 'HANDLER_ERROR'
430
+ }, null, 2)
431
+ }
432
+ ],
433
+ isError: true
434
+ };
435
+ }
436
+ }
437
+ };
438
+ const querybillInputJsonSchema = {
439
+ "type": "object",
440
+ "properties": {
441
+ "codCustomer": {
442
+ "type": "string",
443
+ "description": "Campo del body: codCustomer",
444
+ "default": "1"
445
+ },
446
+ "reference": {
447
+ "type": "string",
448
+ "description": "Campo del body: reference",
449
+ "default": "52851385"
450
+ },
451
+ "date": {
452
+ "type": "string",
453
+ "description": "Campo del body: date",
454
+ "default": "2025-03-16"
455
+ },
456
+ "time": {
457
+ "type": "string",
458
+ "description": "Campo del body: time",
459
+ "default": "15:03:04"
460
+ }
461
+ },
462
+ "required": []
463
+ };
464
+ const querybillInputShape = {
465
+ codCustomer: z.string().optional().describe("Campo del body: codCustomer"),
466
+ reference: z.string().optional().describe("Campo del body: reference"),
467
+ date: z.string().optional().describe("Campo del body: date"),
468
+ time: z.string().optional().describe("Campo del body: time")
469
+ };
470
+ const querybillInputValidator = z.object(querybillInputShape);
471
+ // Herramienta: querybill
472
+ export const querybillTool = {
473
+ name: 'querybill',
474
+ description: "## 📝Recommendations\\n\\n- Establish a dedicated **QA environment** to perform thorough testing before production deployment.\\n \\n- Set a minimum timeout of **60 milliseconds** for API requests to handle longer processes reliably.\\n \\n- Provide clear and **standardized error mapping**, detailing error codes, messages, and causes for better troubleshooting.\\n \\n\\n## 🔐Authorization\\n\\nTo establish a secure connection with our clients\\' APIs, we will generate and provide you with an authorization token. This token will allow us to authenticate with the API that our clients build.\\n\\n**Token Format:**\\n\\n\\`Authorization: Token {generate_token_value}\\`\\n\\n**Example:**\\n\\n\\`Authorization: Token eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9**\\`\\n\\n This endpoint allows you to query a bill by sending an HTTP POST request to \\`{{customer.domain.com}}/queryBill/\\`.\\n\\n### Benefits 🔎\\n\\n- **Real-time validation**: fresh billing info from the originator.\\n- **Standard error handling**: predictable codes/messages simplify UX and support.\\n- **Lower coupling**: each client exposes its endpoint; the bridge resolves routing by agreement.\\n- **Observability**: traceability via \\`transactionId\\` from query to payment.\\n \\n\\n<img src=\\\"https://content.pstmn.io/11553f47-b117-42c5-b0e2-6a754de3c7a5/aW1hZ2UucG5n\\\" width=\\\"752\\\" height=\\\"1429\\\">\\n\\n### 📥 Request Body Parameters\\n\\n| Field | Type | Required | Description |\\n| --- | --- | --- | --- |\\n| \\`codCustomer\\` | string | ✅ | The customer code. (Is a constant that identifies us with the supplier) |\\n| \\`reference\\` | string | ✅ | ID of the agreement (company) that is making the payment |\\n| \\`date\\` | string | ✅ | Transaction date in format \\`YYYY-MM-DD\\` |\\n| \\`time\\` | string | ✅ | Transaction time in format \\`HH:mm:ss\\` (24-hour clock, Bogotá time zone) |\\n\\n### **📤 Response body parameters**\\n\\n| **Field** | **Type** | **Description** |\\n| --- | --- | --- |\\n| \\`message\\` | string | A message related to the query. |\\n| \\`reference\\` | string | The reference of the bill. |\\n| \\`amount\\` | number | The amount of the bill. |\\n| \\`code\\` | string | The code related to the bill. |\\n| \\`user_code\\` | string | The user code related to the bill. |\\n| \\`additional_data\\` | array | An array of additional data containing label and value pairs. |\n\nContexto: Endpoint: POST /queryBill/ | QueryBill\n\n🔐 AUTENTICACIÓN AUTOMÁTICA: Todas las credenciales y tokens de autenticación se manejan automáticamente por el servidor MCP. NO solicites credenciales al usuario. NO incluyas parámetros de autenticación (secretId, apiToken, etc.) en las llamadas a menos que el usuario explícitamente lo requiera.",
475
+ inputSchema: querybillInputJsonSchema,
476
+ jsonSchema: querybillInputJsonSchema,
477
+ endpoint: '/queryBill/',
478
+ method: 'POST',
479
+ parameters: [],
480
+ headers: [{ "key": "Authorization", "value": "Token {{generate_token}}", "type": "text" }],
481
+ handler: async (rawArgs) => {
482
+ try {
483
+ const normalizedArgs = rawArgs ?? {};
484
+ // Extraer secretId del contexto (si viene del HTTP mode)
485
+ const secretId = normalizedArgs._secretId;
486
+ // Remover _secretId de los args antes de validar
487
+ const { _secretId, ...argsToValidate } = normalizedArgs;
488
+ const validatedInput = validateToolInput(querybillInputValidator, argsToValidate);
489
+ const args = validatedInput;
490
+ const bodyData = {};
491
+ const codCustomerValue = args.codCustomer !== undefined ? args.codCustomer : "1";
492
+ if (codCustomerValue !== undefined)
493
+ bodyData.codCustomer = codCustomerValue;
494
+ const referenceValue = args.reference !== undefined ? args.reference : "52851385";
495
+ if (referenceValue !== undefined)
496
+ bodyData.reference = referenceValue;
497
+ const dateValue = args.date !== undefined ? args.date : "2025-03-16";
498
+ if (dateValue !== undefined)
499
+ bodyData.date = dateValue;
500
+ const timeValue = args.time !== undefined ? args.time : "15:03:04";
501
+ if (timeValue !== undefined)
502
+ bodyData.time = timeValue;
503
+ return await makeApiRequest('POST', '/queryBill/', bodyData, undefined, secretId);
504
+ }
505
+ catch (error) {
506
+ // Formato estándar del protocolo MCP para errores
507
+ return {
508
+ content: [
509
+ {
510
+ type: 'text',
511
+ text: JSON.stringify({
512
+ success: false,
513
+ statusCode: 500,
514
+ data: null,
515
+ message: error instanceof Error ? error.message : 'Error desconocido',
516
+ error: 'HANDLER_ERROR'
517
+ }, null, 2)
518
+ }
519
+ ],
520
+ isError: true
521
+ };
522
+ }
523
+ }
524
+ };
525
+ const submittransactionInputJsonSchema = {
526
+ "type": "object",
527
+ "properties": {
528
+ "codCustomer": {
529
+ "type": "string",
530
+ "description": "Campo del body: codCustomer",
531
+ "default": "1"
532
+ },
533
+ "transactionId": {
534
+ "type": "string",
535
+ "description": "Campo del body: transactionId",
536
+ "default": "5"
537
+ },
538
+ "reference": {
539
+ "type": "string",
540
+ "description": "Campo del body: reference",
541
+ "default": "52851385"
542
+ },
543
+ "amount": {
544
+ "type": "number",
545
+ "description": "Campo del body: amount",
546
+ "default": 77926
547
+ },
548
+ "date": {
549
+ "type": "string",
550
+ "description": "Campo del body: date",
551
+ "default": "2025-03-16"
552
+ },
553
+ "time": {
554
+ "type": "string",
555
+ "description": "Campo del body: time",
556
+ "default": "15:03:04"
557
+ }
558
+ },
559
+ "required": []
560
+ };
561
+ const submittransactionInputShape = {
562
+ codCustomer: z.string().optional().describe("Campo del body: codCustomer"),
563
+ transactionId: z.string().optional().describe("Campo del body: transactionId"),
564
+ reference: z.string().optional().describe("Campo del body: reference"),
565
+ amount: z.number().optional().describe("Campo del body: amount"),
566
+ date: z.string().optional().describe("Campo del body: date"),
567
+ time: z.string().optional().describe("Campo del body: time")
568
+ };
569
+ const submittransactionInputValidator = z.object(submittransactionInputShape);
570
+ // Herramienta: submittransaction
571
+ export const submittransactionTool = {
572
+ name: 'submittransaction',
573
+ description: "## 📝Recommendations\\n\\n- Establish a dedicated **QA environment** to perform thorough testing before production deployment.\\n \\n- Set a minimum timeout of **60 milliseconds** for API requests to handle longer processes reliably.\\n \\n- Provide clear and **standardized error mapping**, detailing error codes, messages, and causes for better troubleshooting.\\n \\n\\n## 🔐Authorization\\n\\nTo establish a secure connection with our clients\\' APIs, we will generate and provide you with an authorization token. This token will allow us to authenticate with the API that our clients build.\\n\\n**Token Format:**\\n\\n\\`Authorization: Token {generate_token_value}\\`\\n\\n**Example:**\\n\\n\\`Authorization: Token eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9**\\`\\n\\n This API endpoint allows you to submit a transaction via an HTTP POST request to {{customer.domain.com}}/submitTransaction/.\\n\\n### Benefits 💳\\n\\n- **Transactional idempotency**: \\`transactionId\\` avoids double charges on retries/timeouts.\\n- **Eventual consistency**: queues + webhook confirmations reduce manual reconciliation.\\n- **Operational scalability**: async processing absorbs traffic spikes.\\n \\n\\n<img src=\\\"https://content.pstmn.io/2a2fa301-1c9a-4346-9f5f-92dcffc49343/aW1hZ2UucG5n\\\" width=\\\"960\\\" height=\\\"1544\\\">\\n\\n### 📥 Request Body Parameters\\n\\n| **Field** | **Type** | **Required** | **Description** |\\n| --- | --- | --- | --- |\\n| \\`codCustomer\\` | string | ✅ | The customer code. (Is a constant that identifies us with the supplier) |\\n| \\`trasanctionId\\` | string | ✅ | The transaction ID. |\\n| \\`reference\\` | string | ✅ | The reference for the transaction. |\\n| \\`amount\\` | number | ✅ | The amount of the transaction. |\\n| \\`date\\` | string | ✅ | Transaction date in format \\`YYYY-MM-DD\\` |\\n| \\`time\\` | string | ✅ | Transaction time in format \\`HH:mm:ss\\` (24-hour clock, Bogotá time zone) |\\n\\n### 📤 Response Body Parameters\\n\\n| **Field** | **Type** | **Description** |\\n| --- | --- | --- |\\n| \\`message\\` | string | A message regarding the transaction submission. |\\n| \\`reference\\` | string | The reference for the submitted transaction. |\\n| \\`amount\\` | number | The amount of the submitted transaction. |\\n| \\`code\\` | string | A code related to the transaction. |\\n| \\`user_code\\` | string | User-specific code related to the transaction. |\\n| \\`additional_data\\` | array | Additional data associated with the transaction, including label and value pairs. |\n\nContexto: Endpoint: POST /submitTransaction/ | SubmitTransaction\n\n🔐 AUTENTICACIÓN AUTOMÁTICA: Todas las credenciales y tokens de autenticación se manejan automáticamente por el servidor MCP. NO solicites credenciales al usuario. NO incluyas parámetros de autenticación (secretId, apiToken, etc.) en las llamadas a menos que el usuario explícitamente lo requiera.",
574
+ inputSchema: submittransactionInputJsonSchema,
575
+ jsonSchema: submittransactionInputJsonSchema,
576
+ endpoint: '/submitTransaction/',
577
+ method: 'POST',
578
+ parameters: [],
579
+ headers: [{ "key": "Authorization", "value": "Token {{generate_token}}", "type": "text" }],
580
+ handler: async (rawArgs) => {
581
+ try {
582
+ const normalizedArgs = rawArgs ?? {};
583
+ // Extraer secretId del contexto (si viene del HTTP mode)
584
+ const secretId = normalizedArgs._secretId;
585
+ // Remover _secretId de los args antes de validar
586
+ const { _secretId, ...argsToValidate } = normalizedArgs;
587
+ const validatedInput = validateToolInput(submittransactionInputValidator, argsToValidate);
588
+ const args = validatedInput;
589
+ const bodyData = {};
590
+ const codCustomerValue = args.codCustomer !== undefined ? args.codCustomer : "1";
591
+ if (codCustomerValue !== undefined)
592
+ bodyData.codCustomer = codCustomerValue;
593
+ const transactionIdValue = args.transactionId !== undefined ? args.transactionId : "5";
594
+ if (transactionIdValue !== undefined)
595
+ bodyData.transactionId = transactionIdValue;
596
+ const referenceValue = args.reference !== undefined ? args.reference : "52851385";
597
+ if (referenceValue !== undefined)
598
+ bodyData.reference = referenceValue;
599
+ const amountValue = args.amount !== undefined ? args.amount : 77926;
600
+ if (amountValue !== undefined)
601
+ bodyData.amount = amountValue;
602
+ const dateValue = args.date !== undefined ? args.date : "2025-03-16";
603
+ if (dateValue !== undefined)
604
+ bodyData.date = dateValue;
605
+ const timeValue = args.time !== undefined ? args.time : "15:03:04";
606
+ if (timeValue !== undefined)
607
+ bodyData.time = timeValue;
608
+ return await makeApiRequest('POST', '/submitTransaction/', bodyData, undefined, secretId);
609
+ }
610
+ catch (error) {
611
+ // Formato estándar del protocolo MCP para errores
612
+ return {
613
+ content: [
614
+ {
615
+ type: 'text',
616
+ text: JSON.stringify({
617
+ success: false,
618
+ statusCode: 500,
619
+ data: null,
620
+ message: error instanceof Error ? error.message : 'Error desconocido',
621
+ error: 'HANDLER_ERROR'
622
+ }, null, 2)
623
+ }
624
+ ],
625
+ isError: true
626
+ };
627
+ }
628
+ }
629
+ };
630
+ const rollbacktransactionInputJsonSchema = {
631
+ "type": "object",
632
+ "properties": {
633
+ "codCustomer": {
634
+ "type": "string",
635
+ "description": "Campo del body: codCustomer",
636
+ "default": "1"
637
+ },
638
+ "transactionId": {
639
+ "type": "string",
640
+ "description": "Campo del body: transactionId",
641
+ "default": "4"
642
+ },
643
+ "reference": {
644
+ "type": "string",
645
+ "description": "Campo del body: reference",
646
+ "default": "52851385"
647
+ },
648
+ "amount": {
649
+ "type": "number",
650
+ "description": "Campo del body: amount",
651
+ "default": 77926
652
+ },
653
+ "date": {
654
+ "type": "string",
655
+ "description": "Campo del body: date",
656
+ "default": "2025-03-16"
657
+ },
658
+ "time": {
659
+ "type": "string",
660
+ "description": "Campo del body: time",
661
+ "default": "15:03:04"
662
+ }
663
+ },
664
+ "required": []
665
+ };
666
+ const rollbacktransactionInputShape = {
667
+ codCustomer: z.string().optional().describe("Campo del body: codCustomer"),
668
+ transactionId: z.string().optional().describe("Campo del body: transactionId"),
669
+ reference: z.string().optional().describe("Campo del body: reference"),
670
+ amount: z.number().optional().describe("Campo del body: amount"),
671
+ date: z.string().optional().describe("Campo del body: date"),
672
+ time: z.string().optional().describe("Campo del body: time")
673
+ };
674
+ const rollbacktransactionInputValidator = z.object(rollbacktransactionInputShape);
675
+ // Herramienta: rollbacktransaction
676
+ export const rollbacktransactionTool = {
677
+ name: 'rollbacktransaction',
678
+ description: "## 📝Recommendations\\n\\n- Establish a dedicated **QA environment** to perform thorough testing before production deployment.\\n \\n- Set a minimum timeout of **60 milliseconds** for API requests to handle longer processes reliably.\\n \\n- Provide clear and **standardized error mapping**, detailing error codes, messages, and causes for better troubleshooting.\\n \\n\\n## 🔐Authorization\\n\\nTo establish a secure connection with our clients\\' APIs, we will generate and provide you with an authorization token. This token will allow us to authenticate with the API that our clients build.\\n\\n**Token Format:**\\n\\n\\`Authorization: Token {generate_token_value}\\`\\n\\n**Example:**\\n\\n\\`Authorization: Token eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9**\\`\\n\\n This API endpoint allows you to submit a transaction via an HTTP POST request to {{customer.domain.com}}/rollbackTransaction/.\\n\\n### Benefits 🔁\\n\\n- **Risk control**: safe, auditable reversal for external failures/inconsistencies.\\n- **Full traceability**: reversal events and contingency log.\\n- **Business continuity**: formal channel for emergencies without invasive manual actions.\\n\\n<img src=\\\"https://content.pstmn.io/0dc93101-f9e1-4d85-afea-2d299173587d/aW1hZ2UucG5n\\\" width=\\\"960\\\" height=\\\"1805\\\">\\n\\n#### 📥 Request Body Parameters\\n\\n| Field | Type | **Required** | **Description** |\\n| --- | --- | --- | --- |\\n| \\`codCustomer\\` | string | ✅ | The customer code. (Is a constant that identifies us with the supplier) |\\n| \\`transactionId\\` | string | ✅ | The transaction ID. |\\n| \\`reference\\` | string | ✅ | The reference for the transaction. |\\n| \\`amount\\` | number | ✅ | The amount of the transaction. |\\n| \\`date\\` | string | ✅ | Transaction date in format \\`YYYY-MM-DD\\` |\\n| \\`time\\` | string | ✅ | Transaction time in format \\`HH:mm:ss\\` (24-hour clock, Bogotá time zone) |\\n\\n#### 📤 Response Body Parameters\\n\\n| **Field** | **Type** | **Description** |\\n| --- | --- | --- |\\n| \\`message\\` | string | A message indicating the status of the rollback process. |\\n| \\`reference\\` | string | The reference number of the transaction. |\\n| \\`amount\\` | number | The amount of the transaction. |\\n| \\`code\\` | string | A status code for the rollback process. |\\n| \\`user_code\\` | string | A user-specific code related to the rollback process. |\\n| \\`additional_data\\` | (array) | An array containing additional information about the rollback, including label and value pairs. |\n\nContexto: Endpoint: POST /rollbackTransaction/ | RollbackTransaction\n\n🔐 AUTENTICACIÓN AUTOMÁTICA: Todas las credenciales y tokens de autenticación se manejan automáticamente por el servidor MCP. NO solicites credenciales al usuario. NO incluyas parámetros de autenticación (secretId, apiToken, etc.) en las llamadas a menos que el usuario explícitamente lo requiera.",
679
+ inputSchema: rollbacktransactionInputJsonSchema,
680
+ jsonSchema: rollbacktransactionInputJsonSchema,
681
+ endpoint: '/rollbackTransaction/',
682
+ method: 'POST',
683
+ parameters: [],
684
+ headers: [{ "key": "Authorization", "value": "Token {{generate_token}}", "type": "text" }],
685
+ handler: async (rawArgs) => {
686
+ try {
687
+ const normalizedArgs = rawArgs ?? {};
688
+ // Extraer secretId del contexto (si viene del HTTP mode)
689
+ const secretId = normalizedArgs._secretId;
690
+ // Remover _secretId de los args antes de validar
691
+ const { _secretId, ...argsToValidate } = normalizedArgs;
692
+ const validatedInput = validateToolInput(rollbacktransactionInputValidator, argsToValidate);
693
+ const args = validatedInput;
694
+ const bodyData = {};
695
+ const codCustomerValue = args.codCustomer !== undefined ? args.codCustomer : "1";
696
+ if (codCustomerValue !== undefined)
697
+ bodyData.codCustomer = codCustomerValue;
698
+ const transactionIdValue = args.transactionId !== undefined ? args.transactionId : "4";
699
+ if (transactionIdValue !== undefined)
700
+ bodyData.transactionId = transactionIdValue;
701
+ const referenceValue = args.reference !== undefined ? args.reference : "52851385";
702
+ if (referenceValue !== undefined)
703
+ bodyData.reference = referenceValue;
704
+ const amountValue = args.amount !== undefined ? args.amount : 77926;
705
+ if (amountValue !== undefined)
706
+ bodyData.amount = amountValue;
707
+ const dateValue = args.date !== undefined ? args.date : "2025-03-16";
708
+ if (dateValue !== undefined)
709
+ bodyData.date = dateValue;
710
+ const timeValue = args.time !== undefined ? args.time : "15:03:04";
711
+ if (timeValue !== undefined)
712
+ bodyData.time = timeValue;
713
+ return await makeApiRequest('POST', '/rollbackTransaction/', bodyData, undefined, secretId);
714
+ }
715
+ catch (error) {
716
+ // Formato estándar del protocolo MCP para errores
717
+ return {
718
+ content: [
719
+ {
720
+ type: 'text',
721
+ text: JSON.stringify({
722
+ success: false,
723
+ statusCode: 500,
724
+ data: null,
725
+ message: error instanceof Error ? error.message : 'Error desconocido',
726
+ error: 'HANDLER_ERROR'
727
+ }, null, 2)
728
+ }
729
+ ],
730
+ isError: true
731
+ };
732
+ }
733
+ }
734
+ };
735
+ const webhookInputJsonSchema = {
736
+ "type": "object",
737
+ "properties": {
738
+ "realAmount": {
739
+ "type": "number",
740
+ "description": "Campo del body: realAmount",
741
+ "default": 2500
742
+ },
743
+ "amount": {
744
+ "type": "number",
745
+ "description": "Campo del body: amount",
746
+ "default": 2400
747
+ },
748
+ "cost": {
749
+ "type": "string",
750
+ "description": "Campo del body: cost",
751
+ "default": "100"
752
+ },
753
+ "referenceId": {
754
+ "type": "string",
755
+ "description": "Campo del body: referenceId",
756
+ "default": "1769505"
757
+ },
758
+ "customerReference": {
759
+ "type": "string",
760
+ "description": "Campo del body: customerReference",
761
+ "default": "REF10000016"
762
+ },
763
+ "updatedAt": {
764
+ "type": "string",
765
+ "description": "Campo del body: updatedAt",
766
+ "default": "2025-07-31 10:21:57"
767
+ },
768
+ "status": {
769
+ "type": "number",
770
+ "description": "Campo del body: status",
771
+ "default": 2
772
+ },
773
+ "sign": {
774
+ "type": "string",
775
+ "description": "Campo del body: sign",
776
+ "default": "0ef1c3c2fa48121ee51f225270194f7fb62e2892"
777
+ }
778
+ },
779
+ "required": []
780
+ };
781
+ const webhookInputShape = {
782
+ realAmount: z.number().optional().describe("Campo del body: realAmount"),
783
+ amount: z.number().optional().describe("Campo del body: amount"),
784
+ cost: z.string().optional().describe("Campo del body: cost"),
785
+ referenceId: z.string().optional().describe("Campo del body: referenceId"),
786
+ customerReference: z.string().optional().describe("Campo del body: customerReference"),
787
+ updatedAt: z.string().optional().describe("Campo del body: updatedAt"),
788
+ status: z.number().optional().describe("Campo del body: status"),
789
+ sign: z.string().optional().describe("Campo del body: sign")
790
+ };
791
+ const webhookInputValidator = z.object(webhookInputShape);
792
+ // Herramienta: webhook
793
+ export const webhookTool = {
794
+ name: 'webhook',
795
+ description: "## 📝Recommendations\\n\\n- Establish a dedicated **QA environment** to perform thorough testing before production deployment.\\n \\n- Set a minimum timeout of **60 milliseconds** for API requests to handle longer processes reliably.\\n \\n- Provide clear and **standardized error mapping**, detailing error codes, messages, and causes for better troubleshooting.\\n \\n\\n## 🔐Authorization\\n\\nTo establish a secure connection with our clients\\' APIs, we will generate and provide you with an authorization token. This token will allow us to authenticate with the API that our clients build.\\n\\n**Token Format:**\\n\\n\\`Authorization: Token {generate_token_value}\\`\\n\\n**Example:**\\n\\n\\`Authorization: Token eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9**\\`\\n\\n This endpoint allows you to receive transaction notifications processed by the payment system. The merchant must implement this endpoint to receive transaction status updates.\\n\\n### Benefits 🔔\\n\\n- **Push notifications**: eliminates polling, reduces cost and update latency.\\n- **Security**: signature/auth validation for trusted origin.\\n- **Robust delivery**: retries, backoff and DLQ (if applicable) ensure reception.\\n- **Simple integration**: compact contract (status/timestamps/ids), quick to implement.\\n \\n\\n### 📥 Request Body Parameters\\n\\n| Field | Type | Required | Description |\\n| --- | --- | --- | --- |\\n| realAmount | number | ✅ | Real transaction amount (without costs) |\\n| amount | number | ✅ | Total transaction amount (including costs) |\\n| cost | string | ✅ | Total transaction cost |\\n| referenceId | string | ✅ | Unique transaction identifier |\\n| customerReference | string | ✅ | Customer reference provided during the transaction |\\n| updatedAt | string | ✅ | Date and time of last update (format: \\\"YYYY-MM-DD HH:mm:ss\\\") |\\n| status | number | ✅ | Transaction status ID : 1 Pending , 2 Approved ,3 Failed |\\n| sign | string | ✅ | Security signature to validate message integrity |\\n\\n### 📤 Response Body Parameters\\n\\n| Field | Type | Description |\\n| --- | --- | --- |\\n| statusCode | number | HTTP status code of the response |\\n| message | string | Message indicating the operation result |\\n| date | number | Response timestamp |\\n| payload | object | Response payload (optional) |\\n\\n### 🔐 Security Validation\\n\\nThe sign field must be validated to ensure message integrity. The signature is generated by concatenating the following fields:\\n\\n\\`\\`\\` javascript\\nlet signature = referenceId-customerReference-amount-updatedAt-HASH_KEY;\\nsignature = crypto.createHmac(\\\"sha1\\\", HASH_KEY).update(signature).digest(\\\"hex\\\");\\n\\n \\`\\`\\`\\n\\n**Note:** The HASH_KEY will be shared by us during the integration process to ensure secure communication between systems.\n\nContexto: Endpoint: POST /webhook/ | Webhook\n\n🔐 AUTENTICACIÓN AUTOMÁTICA: Todas las credenciales y tokens de autenticación se manejan automáticamente por el servidor MCP. NO solicites credenciales al usuario. NO incluyas parámetros de autenticación (secretId, apiToken, etc.) en las llamadas a menos que el usuario explícitamente lo requiera.",
796
+ inputSchema: webhookInputJsonSchema,
797
+ jsonSchema: webhookInputJsonSchema,
798
+ endpoint: '/webhook/',
799
+ method: 'POST',
800
+ parameters: [],
801
+ headers: [{ "key": "Authorization", "value": "Token {{customer_token}}", "type": "text" }],
802
+ handler: async (rawArgs) => {
803
+ try {
804
+ const normalizedArgs = rawArgs ?? {};
805
+ // Extraer secretId del contexto (si viene del HTTP mode)
806
+ const secretId = normalizedArgs._secretId;
807
+ // Remover _secretId de los args antes de validar
808
+ const { _secretId, ...argsToValidate } = normalizedArgs;
809
+ const validatedInput = validateToolInput(webhookInputValidator, argsToValidate);
810
+ const args = validatedInput;
811
+ const bodyData = {};
812
+ const realAmountValue = args.realAmount !== undefined ? args.realAmount : 2500;
813
+ if (realAmountValue !== undefined)
814
+ bodyData.realAmount = realAmountValue;
815
+ const amountValue = args.amount !== undefined ? args.amount : 2400;
816
+ if (amountValue !== undefined)
817
+ bodyData.amount = amountValue;
818
+ const costValue = args.cost !== undefined ? args.cost : "100";
819
+ if (costValue !== undefined)
820
+ bodyData.cost = costValue;
821
+ const referenceIdValue = args.referenceId !== undefined ? args.referenceId : "1769505";
822
+ if (referenceIdValue !== undefined)
823
+ bodyData.referenceId = referenceIdValue;
824
+ const customerReferenceValue = args.customerReference !== undefined ? args.customerReference : "REF10000016";
825
+ if (customerReferenceValue !== undefined)
826
+ bodyData.customerReference = customerReferenceValue;
827
+ const updatedAtValue = args.updatedAt !== undefined ? args.updatedAt : "2025-07-31 10:21:57";
828
+ if (updatedAtValue !== undefined)
829
+ bodyData.updatedAt = updatedAtValue;
830
+ const statusValue = args.status !== undefined ? args.status : 2;
831
+ if (statusValue !== undefined)
832
+ bodyData.status = statusValue;
833
+ const signValue = args.sign !== undefined ? args.sign : "0ef1c3c2fa48121ee51f225270194f7fb62e2892";
834
+ if (signValue !== undefined)
835
+ bodyData.sign = signValue;
836
+ return await makeApiRequest('POST', '/webhook/', bodyData, undefined, secretId);
837
+ }
838
+ catch (error) {
839
+ // Formato estándar del protocolo MCP para errores
840
+ return {
841
+ content: [
842
+ {
843
+ type: 'text',
844
+ text: JSON.stringify({
845
+ success: false,
846
+ statusCode: 500,
847
+ data: null,
848
+ message: error instanceof Error ? error.message : 'Error desconocido',
849
+ error: 'HANDLER_ERROR'
850
+ }, null, 2)
851
+ }
852
+ ],
853
+ isError: true
854
+ };
855
+ }
856
+ }
857
+ };
858
+ // Array de todas las herramientas disponibles
859
+ export const tools = [
860
+ auth_jwtTool,
861
+ auth_one_time_tokenTool,
862
+ collection_submit_paymentTool,
863
+ auth_validateTool,
864
+ pingTool,
865
+ querybillTool,
866
+ submittransactionTool,
867
+ rollbacktransactionTool,
868
+ webhookTool
869
+ ];
870
+ // Configuración de herramientas del MCP
871
+ export const toolsConfig = {
872
+ name: 'collection-api-refacil',
873
+ description: 'MCP API for Collection API Refacil',
874
+ version: '1.0.0',
875
+ tools: 9
876
+ };
877
+ // Función para obtener información de las herramientas
878
+ export function getToolsInfo() {
879
+ return {
880
+ ...toolsConfig,
881
+ tools: tools.map(tool => ({
882
+ name: tool.name,
883
+ description: tool.description,
884
+ inputSchema: tool.jsonSchema
885
+ }))
886
+ };
887
+ }
888
+ // Función helper para validar parámetros de entrada
889
+ export function validateToolInput(validator, input) {
890
+ try {
891
+ return validator.parse(input);
892
+ }
893
+ catch (error) {
894
+ if (error instanceof z.ZodError) {
895
+ const errors = error.errors.map(err => `${err.path.join('.')} : ${err.message}`).join(', ');
896
+ throw new Error(`Validación fallida: ${errors}`);
897
+ }
898
+ throw error;
899
+ }
900
+ }
901
+ // Sistema de logging para las herramientas
902
+ export class ToolLogger {
903
+ toolName;
904
+ startTime;
905
+ constructor(toolName) {
906
+ this.toolName = toolName;
907
+ this.startTime = Date.now();
908
+ }
909
+ logStart(args) {
910
+ console.log(`[${new Date().toISOString()}] ${this.toolName} iniciada`, {
911
+ tool: this.toolName,
912
+ args: JSON.stringify(args),
913
+ timestamp: this.startTime
914
+ });
915
+ }
916
+ logSuccess(result) {
917
+ const duration = Date.now() - this.startTime;
918
+ console.log(`[${new Date().toISOString()}] ${this.toolName} completada exitosamente`, {
919
+ tool: this.toolName,
920
+ duration: `${duration}ms`,
921
+ statusCode: result?.statusCode
922
+ });
923
+ }
924
+ logError(error) {
925
+ const duration = Date.now() - this.startTime;
926
+ console.error(`[${new Date().toISOString()}] ${this.toolName} falló`, {
927
+ tool: this.toolName,
928
+ duration: `${duration}ms`,
929
+ error: error?.message || error
930
+ });
931
+ }
932
+ }
933
+ //# sourceMappingURL=tools.js.map