@securelend/sdk 0.1.0-beta.5

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/index.js ADDED
@@ -0,0 +1,1004 @@
1
+ 'use strict';
2
+
3
+ var zod = require('zod');
4
+ var index_js = require('@modelcontextprotocol/sdk/client/index.js');
5
+ var streamableHttp_js = require('@modelcontextprotocol/sdk/client/streamableHttp.js');
6
+
7
+ // src/client.ts
8
+
9
+ // src/utils/errors.ts
10
+ var SecureLendError = class extends Error {
11
+ constructor(message, type, details) {
12
+ super(message);
13
+ this.name = "SecureLendError";
14
+ this.type = type;
15
+ this.details = details;
16
+ Error.captureStackTrace(this, this.constructor);
17
+ }
18
+ };
19
+ var AuthenticationError = class extends SecureLendError {
20
+ constructor(message) {
21
+ super(message, "authentication_error");
22
+ this.name = "AuthenticationError";
23
+ }
24
+ };
25
+ var RateLimitError = class extends SecureLendError {
26
+ constructor(message, retryAfter) {
27
+ super(message, "rate_limit_error");
28
+ this.name = "RateLimitError";
29
+ this.retryAfter = retryAfter;
30
+ }
31
+ };
32
+ var ValidationError = class extends SecureLendError {
33
+ constructor(message, errors) {
34
+ super(message, "validation_error", errors);
35
+ this.name = "ValidationError";
36
+ }
37
+ };
38
+ var NotFoundError = class extends SecureLendError {
39
+ constructor(message) {
40
+ super(message, "not_found");
41
+ this.name = "NotFoundError";
42
+ }
43
+ };
44
+ var NetworkError = class extends SecureLendError {
45
+ constructor(message) {
46
+ super(message, "network_error");
47
+ this.name = "NetworkError";
48
+ }
49
+ };
50
+ var ServerError = class extends SecureLendError {
51
+ constructor(message) {
52
+ super(message, "server_error");
53
+ this.name = "ServerError";
54
+ }
55
+ };
56
+
57
+ // src/utils/mcp.ts
58
+ var MCPClient = class {
59
+ constructor(config) {
60
+ this.debug = false;
61
+ this.isConnected = false;
62
+ this.config = config;
63
+ this.mcp = new index_js.Client({ name: "@securelend/sdk", version: "1.0.0" });
64
+ }
65
+ async connect() {
66
+ if (this.isConnected) return;
67
+ try {
68
+ if (this.debug) {
69
+ console.log(
70
+ `[SecureLend SDK] Connecting to MCP server at ${this.config.mcpURL}`
71
+ );
72
+ }
73
+ const transport = new streamableHttp_js.StreamableHTTPClientTransport(
74
+ new URL(this.config.mcpURL)
75
+ );
76
+ await this.mcp.connect(transport);
77
+ this.isConnected = true;
78
+ if (this.debug) {
79
+ console.log(`[SecureLend SDK] MCP client connected.`);
80
+ }
81
+ } catch (error) {
82
+ this.isConnected = false;
83
+ const errorMessage = error instanceof Error ? error.message : String(error);
84
+ if (errorMessage.includes("401")) {
85
+ throw new AuthenticationError(
86
+ "MCP connection failed: Invalid API key."
87
+ );
88
+ }
89
+ throw new NetworkError(`MCP connection failed: ${errorMessage}`);
90
+ }
91
+ }
92
+ async callTool(name, args) {
93
+ await this.connect();
94
+ if (this.debug) {
95
+ console.log(`[SecureLend SDK] Calling tool: ${name} with args:`, args);
96
+ }
97
+ try {
98
+ const result = await this.mcp.callTool({
99
+ name,
100
+ arguments: args
101
+ });
102
+ if (this.debug) {
103
+ console.log(`[SecureLend SDK] Tool result for ${name}:`, result);
104
+ }
105
+ return result;
106
+ } catch (error) {
107
+ if (error instanceof SecureLendError) throw error;
108
+ const errorMessage = error instanceof Error ? error.message : String(error);
109
+ if (errorMessage.includes("400")) {
110
+ throw new ValidationError("Invalid tool arguments", error);
111
+ }
112
+ throw new SecureLendError(
113
+ `Tool call failed: ${errorMessage}`,
114
+ "mcp_tool_error",
115
+ error
116
+ );
117
+ }
118
+ }
119
+ setApiKey(apiKey) {
120
+ this.config.apiKey = apiKey;
121
+ this.isConnected = false;
122
+ }
123
+ enableDebug() {
124
+ this.debug = true;
125
+ }
126
+ disableDebug() {
127
+ this.debug = false;
128
+ }
129
+ };
130
+ var anyObjectSchema = zod.z.object({}).passthrough();
131
+ var CreditTier = /* @__PURE__ */ ((CreditTier2) => {
132
+ CreditTier2["PRIME"] = "PRIME";
133
+ CreditTier2["NEAR_PRIME"] = "NEAR_PRIME";
134
+ CreditTier2["SUBPRIME"] = "SUBPRIME";
135
+ CreditTier2["DEEP_SUBPRIME"] = "DEEP_SUBPRIME";
136
+ CreditTier2["UNKNOWN"] = "UNKNOWN";
137
+ return CreditTier2;
138
+ })(CreditTier || {});
139
+ var ProductType = /* @__PURE__ */ ((ProductType2) => {
140
+ ProductType2["INSTALLMENT_LOAN"] = "INSTALLMENT_LOAN";
141
+ ProductType2["LINE_OF_CREDIT"] = "LINE_OF_CREDIT";
142
+ ProductType2["SHORT_TERM_CREDIT"] = "SHORT_TERM_CREDIT";
143
+ ProductType2["BNPL"] = "BNPL";
144
+ ProductType2["MORTGAGE"] = "MORTGAGE";
145
+ ProductType2["AUTO_LOAN"] = "AUTO_LOAN";
146
+ ProductType2["AUTO_REFINANCE"] = "AUTO_REFINANCE";
147
+ ProductType2["STUDENT_LOAN"] = "STUDENT_LOAN";
148
+ ProductType2["STUDENT_LOAN_REFINANCE"] = "STUDENT_LOAN_REFINANCE";
149
+ ProductType2["BUSINESS_LOAN"] = "BUSINESS_LOAN";
150
+ ProductType2["BUSINESS_BANKING"] = "BUSINESS_BANKING";
151
+ ProductType2["BUSINESS_CREDIT_CARD"] = "BUSINESS_CREDIT_CARD";
152
+ ProductType2["PERSONAL_BANKING"] = "PERSONAL_BANKING";
153
+ ProductType2["SAVINGS_ACCOUNT"] = "SAVINGS_ACCOUNT";
154
+ ProductType2["PERSONAL_CREDIT_CARD"] = "PERSONAL_CREDIT_CARD";
155
+ return ProductType2;
156
+ })(ProductType || {});
157
+ var moneySchema = zod.z.object({
158
+ amount: zod.z.number(),
159
+ currency: zod.z.string().length(3).optional()
160
+ });
161
+ var bankAccountOfferSchema = zod.z.object({
162
+ id: zod.z.string(),
163
+ providerName: zod.z.string(),
164
+ providerLogo: zod.z.string().optional(),
165
+ accountName: zod.z.string(),
166
+ monthlyFee: zod.z.number(),
167
+ minBalance: zod.z.number(),
168
+ interestRate: zod.z.number(),
169
+ features: zod.z.array(zod.z.string()),
170
+ isSecureLendTenant: zod.z.boolean().optional(),
171
+ applicationUrl: zod.z.string().url().optional()
172
+ });
173
+ var creditCardOfferSchema = zod.z.object({
174
+ id: zod.z.string(),
175
+ issuerName: zod.z.string(),
176
+ issuerLogo: zod.z.string().optional(),
177
+ cardName: zod.z.string(),
178
+ apr: zod.z.object({
179
+ min: zod.z.number(),
180
+ max: zod.z.number()
181
+ }),
182
+ annualFee: zod.z.number(),
183
+ rewards: zod.z.object({
184
+ type: zod.z.enum(["cash_back", "points", "miles"]),
185
+ summary: zod.z.string(),
186
+ signupBonus: zod.z.string().optional()
187
+ }),
188
+ isSecureLendTenant: zod.z.boolean().optional(),
189
+ applicationUrl: zod.z.string().url().optional()
190
+ });
191
+ var ApplicationType = /* @__PURE__ */ ((ApplicationType2) => {
192
+ ApplicationType2["PERSONAL"] = "PERSONAL";
193
+ ApplicationType2["BUSINESS"] = "BUSINESS";
194
+ return ApplicationType2;
195
+ })(ApplicationType || {});
196
+ var ApplicationStatus = /* @__PURE__ */ ((ApplicationStatus2) => {
197
+ ApplicationStatus2["DRAFT"] = "DRAFT";
198
+ ApplicationStatus2["SUBMITTED"] = "SUBMITTED";
199
+ ApplicationStatus2["IN_REVIEW"] = "IN_REVIEW";
200
+ ApplicationStatus2["ACTION_REQUIRED"] = "ACTION_REQUIRED";
201
+ ApplicationStatus2["APPROVED"] = "APPROVED";
202
+ ApplicationStatus2["DECLINED"] = "DECLINED";
203
+ ApplicationStatus2["CLOSED"] = "CLOSED";
204
+ return ApplicationStatus2;
205
+ })(ApplicationStatus || {});
206
+ var ProviderStatus = /* @__PURE__ */ ((ProviderStatus2) => {
207
+ ProviderStatus2["PENDING"] = "PENDING";
208
+ ProviderStatus2["SUBMITTED"] = "SUBMITTED";
209
+ ProviderStatus2["REFERRED"] = "REFERRED";
210
+ ProviderStatus2["ERROR"] = "ERROR";
211
+ ProviderStatus2["RECEIVED"] = "RECEIVED";
212
+ return ProviderStatus2;
213
+ })(ProviderStatus || {});
214
+ var personalApplicantSchema = zod.z.object({
215
+ firstName: zod.z.string().describe("The applicant's first name."),
216
+ lastName: zod.z.string().describe("The applicant's last name."),
217
+ email: zod.z.string().email().describe("The applicant's email address."),
218
+ phone: zod.z.string().optional().describe("The applicant's phone number.")
219
+ });
220
+ var lenderSchema = zod.z.object({
221
+ id: zod.z.string(),
222
+ name: zod.z.string(),
223
+ type: zod.z.string(),
224
+ logoUrl: zod.z.string().url().optional()
225
+ });
226
+ var productSchema = zod.z.object({
227
+ name: zod.z.string(),
228
+ type: zod.z.string(),
229
+ description: zod.z.string().optional()
230
+ });
231
+ var loanTermsSchema = zod.z.object({
232
+ amount: moneySchema,
233
+ interestRate: zod.z.object({
234
+ type: zod.z.enum(["fixed", "variable"]),
235
+ rate: zod.z.number().optional(),
236
+ // rate might not always be available if only APR is given
237
+ apr: zod.z.number()
238
+ }),
239
+ termMonths: zod.z.number().int(),
240
+ payment: zod.z.object({
241
+ frequency: zod.z.string().optional(),
242
+ amount: moneySchema
243
+ }),
244
+ totalCost: moneySchema.optional(),
245
+ repayment: zod.z.object({
246
+ totalRepaymentAmount: zod.z.number(),
247
+ costOfFinancing: zod.z.number()
248
+ }).optional()
249
+ });
250
+ var loanFeesSchema = zod.z.object({
251
+ origination: zod.z.object({
252
+ amount: moneySchema.optional(),
253
+ percentage: zod.z.number().optional()
254
+ }).optional()
255
+ }).optional();
256
+ var matchingSchema = zod.z.object({
257
+ approvalProbability: zod.z.number().min(0).max(1).optional(),
258
+ matchScore: zod.z.number().min(0).max(100).optional(),
259
+ matchReasons: zod.z.array(zod.z.string()).optional()
260
+ }).optional();
261
+ var processSchema = zod.z.object({
262
+ applicationMethod: zod.z.string(),
263
+ applicationUrl: zod.z.string().url().optional(),
264
+ fundingSpeed: zod.z.object({
265
+ description: zod.z.string()
266
+ }).optional()
267
+ });
268
+ var loanOfferSchema = zod.z.object({
269
+ offerId: zod.z.string(),
270
+ lender: lenderSchema,
271
+ product: productSchema,
272
+ terms: loanTermsSchema,
273
+ fees: loanFeesSchema,
274
+ matching: matchingSchema,
275
+ process: processSchema.optional(),
276
+ // Additional fields for UI that were in the old schema
277
+ lenderInfo: zod.z.string().optional(),
278
+ badges: zod.z.array(zod.z.string()).optional(),
279
+ isSecureLendTenant: zod.z.boolean().optional()
280
+ });
281
+ var personalLoanSearchSchema = zod.z.object({
282
+ loanAmount: zod.z.number().min(1e3).max(1e5).describe("The desired loan amount in USD (e.g., 25000)."),
283
+ purpose: zod.z.enum([
284
+ "debt_consolidation",
285
+ "home_improvement",
286
+ "major_purchase",
287
+ "medical",
288
+ "vacation",
289
+ "other"
290
+ ]).describe("The purpose of the loan."),
291
+ creditScore: zod.z.number().min(300).max(850).optional().describe("The applicant's estimated credit score (300-850)."),
292
+ monthlyIncome: zod.z.number().min(0).optional().describe("Applicant's gross monthly income in USD."),
293
+ employmentStatus: zod.z.enum(["employed", "self_employed", "retired", "unemployed"]).optional().describe("The applicant's employment status."),
294
+ state: zod.z.string().optional().describe("The applicant's state of residence (2-letter code).")
295
+ });
296
+ var businessLoanSearchSchema = zod.z.object({
297
+ loanAmount: zod.z.number().min(1e3).describe("The desired loan amount, e.g., 50000 for $50,000."),
298
+ purpose: zod.z.string().describe("The reason for the loan, e.g., 'working capital'."),
299
+ annualRevenue: zod.z.number().min(0).optional().describe("The business's gross annual revenue in USD."),
300
+ industry: zod.z.string().optional().describe("The industry the business operates in, e.g., 'technology'."),
301
+ state: zod.z.string().optional().describe("The state where the business is located (2-letter code).")
302
+ });
303
+ var mortgageSearchSchema = zod.z.object({
304
+ loanAmount: zod.z.number().min(5e4).max(2e6).describe("The desired mortgage loan amount in USD."),
305
+ homePrice: zod.z.number().min(5e4).max(5e6).optional().describe("The purchase price of the home in USD."),
306
+ downPayment: zod.z.number().min(0).optional().describe("The amount of the down payment in USD."),
307
+ creditScore: zod.z.number().min(500).max(850).optional().describe("The applicant's estimated credit score (500-850)."),
308
+ loanType: zod.z.enum(["conventional", "fha", "va", "jumbo", "refinance"]).describe("The type of mortgage loan."),
309
+ propertyType: zod.z.enum(["primary", "secondary", "investment"]).optional().describe("The intended use of the property."),
310
+ state: zod.z.string().optional().describe("The state where the property is located (2-letter code).")
311
+ });
312
+ var autoLoanSearchSchema = zod.z.object({
313
+ loanAmount: zod.z.number().min(1e3).max(1e5).describe("The desired auto loan amount in USD."),
314
+ creditScore: zod.z.number().min(300).max(850).optional().describe("The applicant's estimated credit score (300-850)."),
315
+ isNew: zod.z.boolean().describe("Specifies if the vehicle is new (true) or used (false)."),
316
+ state: zod.z.string().optional().describe("The applicant's state of residence (2-letter code).")
317
+ });
318
+ var studentLoanSearchSchema = zod.z.object({
319
+ loanAmount: zod.z.number().min(1e3).max(25e4).describe("The total amount needed for the student loan in USD."),
320
+ creditScore: zod.z.number().min(300).max(850).optional().describe("The student's estimated credit score (300-850)."),
321
+ coSignerCreditScore: zod.z.number().min(300).max(850).optional().describe(
322
+ "The co-signer's estimated credit score (300-850), if applicable."
323
+ ),
324
+ degreeType: zod.z.enum(["undergraduate", "graduate", "mba", "medical", "law"]).describe("The type of degree the loan is for."),
325
+ state: zod.z.string().optional().describe("The student's state of residence (2-letter code).")
326
+ });
327
+ var businessCreditCardSearchSchema = zod.z.object({
328
+ creditScore: zod.z.number().min(300).max(850).optional().describe("The applicant's estimated credit score (300-850)."),
329
+ annualRevenue: zod.z.number().min(0).optional().describe("The business's annual revenue in USD."),
330
+ businessAgeInYears: zod.z.number().min(0).optional().describe("The age of the business in years.")
331
+ });
332
+ var businessCreditCardOfferSchema = zod.z.object({
333
+ cardId: zod.z.string(),
334
+ name: zod.z.string(),
335
+ issuer: zod.z.string(),
336
+ imageUrl: zod.z.string(),
337
+ rating: zod.z.number().min(0).max(5),
338
+ creditScoreRange: zod.z.string(),
339
+ welcomeBonus: zod.z.string(),
340
+ terms: zod.z.object({
341
+ apr: zod.z.number(),
342
+ annualFee: zod.z.number(),
343
+ creditLimit: moneySchema
344
+ })
345
+ });
346
+ var businessCreditCardComparisonResponseSchema = zod.z.object({
347
+ offers: zod.z.array(businessCreditCardOfferSchema),
348
+ searchCriteria: businessCreditCardSearchSchema.optional(),
349
+ metadata: zod.z.object({
350
+ queryId: zod.z.string(),
351
+ timestamp: zod.z.string(),
352
+ sessionId: zod.z.string().optional()
353
+ }),
354
+ widget: zod.z.string().optional()
355
+ });
356
+ var businessBankingSearchSchema = zod.z.object({
357
+ industry: zod.z.string().optional().describe("The business's industry."),
358
+ monthlyTransactions: zod.z.number().optional().describe("Estimated number of monthly transactions.")
359
+ });
360
+ var businessBankingOfferSchema = zod.z.object({
361
+ accountId: zod.z.string(),
362
+ name: zod.z.string(),
363
+ issuer: zod.z.string(),
364
+ imageUrl: zod.z.string(),
365
+ rating: zod.z.number().min(0).max(5),
366
+ bestFor: zod.z.string(),
367
+ apy: zod.z.string(),
368
+ interestRate: zod.z.string().optional(),
369
+ monthlyFee: zod.z.string(),
370
+ bonus: zod.z.string()
371
+ });
372
+ var businessBankingComparisonResponseSchema = zod.z.object({
373
+ offers: zod.z.array(businessBankingOfferSchema),
374
+ searchCriteria: businessBankingSearchSchema.optional(),
375
+ metadata: zod.z.object({
376
+ queryId: zod.z.string(),
377
+ timestamp: zod.z.string(),
378
+ sessionId: zod.z.string().optional()
379
+ }),
380
+ widget: zod.z.string().optional()
381
+ });
382
+ var personalBankingSearchSchema = zod.z.object({
383
+ features: zod.z.array(zod.z.string()).optional().describe("Desired account features.")
384
+ });
385
+ var personalBankingOfferSchema = zod.z.object({
386
+ accountId: zod.z.string(),
387
+ name: zod.z.string(),
388
+ issuer: zod.z.string(),
389
+ imageUrl: zod.z.string(),
390
+ rating: zod.z.number().min(0).max(5),
391
+ bestFor: zod.z.string(),
392
+ apy: zod.z.string(),
393
+ interestRate: zod.z.string().optional(),
394
+ bonus: zod.z.string(),
395
+ monthlyFee: zod.z.string(),
396
+ overdraftRating: zod.z.number().min(0).max(5)
397
+ });
398
+ var personalBankingComparisonResponseSchema = zod.z.object({
399
+ offers: zod.z.array(personalBankingOfferSchema),
400
+ searchCriteria: personalBankingSearchSchema.optional(),
401
+ metadata: zod.z.object({
402
+ queryId: zod.z.string(),
403
+ timestamp: zod.z.string(),
404
+ sessionId: zod.z.string().optional()
405
+ }),
406
+ widget: zod.z.string().optional()
407
+ });
408
+ var savingsSearchSchema = zod.z.object({
409
+ initialDeposit: zod.z.number().optional().describe("The initial deposit amount in USD.")
410
+ });
411
+ var savingsOfferSchema = zod.z.object({
412
+ accountId: zod.z.string(),
413
+ name: zod.z.string(),
414
+ issuer: zod.z.string(),
415
+ imageUrl: zod.z.string(),
416
+ rating: zod.z.number().min(0).max(5),
417
+ apy: zod.z.string(),
418
+ interestRate: zod.z.string().optional(),
419
+ minBalanceForApy: zod.z.string(),
420
+ monthlyFee: zod.z.string()
421
+ });
422
+ var savingsComparisonResponseSchema = zod.z.object({
423
+ offers: zod.z.array(savingsOfferSchema),
424
+ searchCriteria: savingsSearchSchema.optional(),
425
+ metadata: zod.z.object({
426
+ queryId: zod.z.string(),
427
+ timestamp: zod.z.string(),
428
+ sessionId: zod.z.string().optional()
429
+ }),
430
+ widget: zod.z.string().optional()
431
+ });
432
+ var personalCreditCardSearchSchema = zod.z.object({
433
+ creditScore: zod.z.number().min(300).max(850).optional().describe("The applicant's estimated credit score (300-850)."),
434
+ rewardsType: zod.z.enum(["cash_back", "travel", "points"]).optional().describe("Preferred rewards type.")
435
+ });
436
+ var personalCreditCardOfferSchema = zod.z.object({
437
+ cardId: zod.z.string(),
438
+ name: zod.z.string(),
439
+ issuer: zod.z.string(),
440
+ imageUrl: zod.z.string(),
441
+ rating: zod.z.number().min(0).max(5),
442
+ bestFor: zod.z.string(),
443
+ rewardsRate: zod.z.string(),
444
+ introOffer: zod.z.string(),
445
+ recommendedCreditScore: zod.z.string(),
446
+ terms: zod.z.object({
447
+ apr: zod.z.object({
448
+ purchase: zod.z.number(),
449
+ balanceTransfer: zod.z.number(),
450
+ penalty: zod.z.number().optional()
451
+ }),
452
+ fees: zod.z.object({
453
+ annual: zod.z.number()
454
+ })
455
+ }),
456
+ applicationUrl: zod.z.string().url().optional()
457
+ });
458
+ var personalCreditCardComparisonResponseSchema = zod.z.object({
459
+ offers: zod.z.array(personalCreditCardOfferSchema),
460
+ searchCriteria: personalCreditCardSearchSchema.optional(),
461
+ metadata: zod.z.object({
462
+ queryId: zod.z.string(),
463
+ timestamp: zod.z.string(),
464
+ sessionId: zod.z.string().optional()
465
+ }),
466
+ widget: zod.z.string().optional()
467
+ });
468
+ var loanComparisonResponseSchema = zod.z.object({
469
+ offers: zod.z.array(loanOfferSchema),
470
+ summary: zod.z.object({
471
+ totalOffers: zod.z.number().int(),
472
+ bestRate: zod.z.number(),
473
+ bestApprovalProbability: zod.z.number().optional(),
474
+ fastestFunding: zod.z.string().optional()
475
+ }),
476
+ searchCriteria: zod.z.union([
477
+ personalLoanSearchSchema,
478
+ businessLoanSearchSchema,
479
+ mortgageSearchSchema,
480
+ autoLoanSearchSchema,
481
+ studentLoanSearchSchema
482
+ ]).optional(),
483
+ metadata: zod.z.object({
484
+ queryId: zod.z.string(),
485
+ timestamp: zod.z.string(),
486
+ sessionId: zod.z.string().optional()
487
+ }),
488
+ widget: zod.z.string().optional()
489
+ });
490
+ var applicationProviderSchema = zod.z.object({
491
+ providerId: zod.z.string(),
492
+ providerName: zod.z.string(),
493
+ status: zod.z.nativeEnum(ProviderStatus),
494
+ submittedAt: zod.z.string().optional(),
495
+ providerApplicationId: zod.z.string().optional(),
496
+ referralUrl: zod.z.string().url().optional(),
497
+ error: zod.z.string().optional()
498
+ });
499
+ var personalApplicationSchema = zod.z.object({
500
+ id: zod.z.string(),
501
+ createdAt: zod.z.string(),
502
+ updatedAt: zod.z.string(),
503
+ applicationType: zod.z.nativeEnum(ApplicationType),
504
+ productType: zod.z.union([zod.z.nativeEnum(ProductType), zod.z.string()]),
505
+ status: zod.z.nativeEnum(ApplicationStatus),
506
+ applicant: personalApplicantSchema,
507
+ applicationData: anyObjectSchema,
508
+ providers: zod.z.array(applicationProviderSchema),
509
+ email: zod.z.string().email(),
510
+ widget: zod.z.string().optional()
511
+ });
512
+ var createPersonalApplicationSchema = zod.z.object({
513
+ productType: zod.z.nativeEnum(ProductType),
514
+ applicant: personalApplicantSchema,
515
+ applicationData: anyObjectSchema,
516
+ providers: zod.z.array(zod.z.object({ providerId: zod.z.string(), providerName: zod.z.string() })).optional()
517
+ });
518
+ var displayOfferFormSchema = zod.z.object({
519
+ sessionId: zod.z.string().optional().describe("The session ID from a previous search to retrieve all offers."),
520
+ offerId: zod.z.string().optional().describe("The specific offer ID to pre-select in the form.")
521
+ });
522
+ var anyOfferSchema = zod.z.union([
523
+ loanOfferSchema,
524
+ businessCreditCardOfferSchema,
525
+ businessBankingOfferSchema,
526
+ personalBankingOfferSchema,
527
+ savingsOfferSchema,
528
+ personalCreditCardOfferSchema
529
+ ]);
530
+ var displayOfferFormResponseSchema = zod.z.object({
531
+ offer: anyOfferSchema,
532
+ allOffers: zod.z.array(anyOfferSchema),
533
+ applicationData: anyObjectSchema,
534
+ productType: zod.z.string(),
535
+ widget: zod.z.string().optional()
536
+ });
537
+ var getOfferSchema = zod.z.object({
538
+ productType: zod.z.nativeEnum(ProductType).describe("The type of financial product being applied for."),
539
+ applicant: personalApplicantSchema.describe(
540
+ "Personal details of the applicant."
541
+ ),
542
+ applicationData: anyObjectSchema.describe(
543
+ "The original search parameters or form data for the application."
544
+ ),
545
+ provider: zod.z.object({
546
+ providerId: zod.z.string().describe("The ID of the selected provider."),
547
+ providerName: zod.z.string().describe("The name of the selected provider.")
548
+ }).describe("The selected provider to submit the application to.")
549
+ });
550
+ var getMultipleOffersSchema = zod.z.object({
551
+ productType: zod.z.nativeEnum(ProductType).describe("The type of financial product being applied for."),
552
+ applicant: personalApplicantSchema.describe(
553
+ "Personal details of the applicant."
554
+ ),
555
+ applicationData: anyObjectSchema.describe(
556
+ "The original search parameters or form data for the application."
557
+ ),
558
+ providers: zod.z.array(
559
+ zod.z.object({
560
+ providerId: zod.z.string().describe("The ID of the selected provider."),
561
+ providerName: zod.z.string().describe("The name of the selected provider.")
562
+ })
563
+ ).min(1).describe("The list of selected providers to submit the application to.")
564
+ });
565
+ var trackOfferStatusSchema = zod.z.object({
566
+ applicationId: zod.z.string().optional().describe("The unique ID of the application to track."),
567
+ email: zod.z.string().email().optional().describe("The email address of the applicant to find applications for.")
568
+ }).refine((data) => data.applicationId || data.email, {
569
+ message: "Either applicationId or email must be provided."
570
+ });
571
+ var trackOfferStatusResponseSchema = zod.z.object({
572
+ applications: zod.z.array(personalApplicationSchema),
573
+ widget: zod.z.string().optional()
574
+ });
575
+ var businessApplicantSchema = zod.z.object({
576
+ businessName: zod.z.string(),
577
+ ein: zod.z.string().optional(),
578
+ contact: personalApplicantSchema
579
+ });
580
+ var createBusinessApplicationSchema = zod.z.object({
581
+ productType: zod.z.nativeEnum(ProductType),
582
+ applicant: businessApplicantSchema,
583
+ applicationData: anyObjectSchema,
584
+ providers: zod.z.array(zod.z.object({ providerId: zod.z.string(), providerName: zod.z.string() })).optional()
585
+ });
586
+ var documentTypeEnum = zod.z.enum([
587
+ "articles-of-incorporation",
588
+ "balance-sheet",
589
+ "bank-statement",
590
+ "business-license",
591
+ "business-plan",
592
+ "contract",
593
+ "drivers-license",
594
+ "financial-statement",
595
+ "identity-document",
596
+ "invoice",
597
+ "lease-agreement",
598
+ "other-business-document",
599
+ "other-personal-document",
600
+ "passport",
601
+ "profit-and-loss-statement",
602
+ "proof-of-address",
603
+ "proof-of-income",
604
+ "property-document",
605
+ "purchase-order",
606
+ "tax-return",
607
+ "utility-bill",
608
+ "vehicle-document",
609
+ "voided-check"
610
+ ]);
611
+ var displayUploadDocumentsFormSchema = zod.z.object({
612
+ applicationId: zod.z.string().optional().describe("Pre-fill the application ID for the document upload form.")
613
+ });
614
+ var submitDocumentsSchema = zod.z.object({
615
+ applicationId: zod.z.string().describe("The ID of the application to associate the document with."),
616
+ fileName: zod.z.string().describe("The original name of the file."),
617
+ documentType: documentTypeEnum.describe("The category of the document."),
618
+ _openai_meta: zod.z.object({}).passthrough().optional().describe("Internal metadata from OpenAI (automatically injected)")
619
+ });
620
+ var submitDocumentsResponseSchema = zod.z.object({
621
+ success: zod.z.boolean(),
622
+ message: zod.z.string(),
623
+ uploadUrl: zod.z.string().url().optional(),
624
+ uploadFields: zod.z.record(zod.z.string(), zod.z.string()).optional(),
625
+ documentId: zod.z.string().optional(),
626
+ widget: zod.z.string().optional()
627
+ });
628
+ var displayUploadDocumentsFormResponseSchema = zod.z.object({
629
+ widget: zod.z.string().optional()
630
+ });
631
+ var loanPaymentSchema = zod.z.object({
632
+ loanAmount: zod.z.number().describe("The total amount of the loan in USD.").positive("Loan amount must be positive."),
633
+ interestRate: zod.z.number().describe("The annual interest rate (e.g., 5 for 5%).").min(0, "Interest rate cannot be negative."),
634
+ loanTermInMonths: zod.z.number().describe("The duration of the loan in months.").positive("Loan term must be positive.").int()
635
+ });
636
+ var loanPaymentResponseSchema = zod.z.object({
637
+ monthlyPayment: zod.z.number().describe("The calculated monthly payment amount."),
638
+ totalPayment: zod.z.number().describe("The total amount to be paid over the life of the loan."),
639
+ totalInterest: zod.z.number().describe("The total interest paid over the life of the loan."),
640
+ widget: zod.z.string().optional()
641
+ });
642
+ var mortgagePaymentSchema = zod.z.object({
643
+ propertyValue: zod.z.number().describe("The total value of the property in USD.").positive("Property value must be positive."),
644
+ downPayment: zod.z.number().describe("The amount paid upfront in USD.").min(0, "Down payment cannot be negative."),
645
+ interestRate: zod.z.number().describe("The annual interest rate (e.g., 3.5 for 3.5%).").min(0, "Interest rate cannot be negative."),
646
+ loanTermInYears: zod.z.number().describe("The duration of the loan in years.").positive("Loan term must be positive.").int(),
647
+ propertyTaxRate: zod.z.number().describe(
648
+ "The annual property tax rate as a percentage (e.g., 1.2 for 1.2%)."
649
+ ).min(0, "Property tax rate cannot be negative."),
650
+ homeInsurance: zod.z.number().describe("The annual home insurance cost in USD.").min(0, "Home insurance cannot be negative.")
651
+ });
652
+ var mortgagePaymentResponseSchema = zod.z.object({
653
+ loanAmount: zod.z.number().describe("The total loan amount after down payment."),
654
+ principalAndInterest: zod.z.number().describe("The monthly payment for principal and interest."),
655
+ monthlyPropertyTax: zod.z.number().describe("The estimated monthly property tax payment."),
656
+ monthlyHomeInsurance: zod.z.number().describe("The estimated monthly home insurance payment."),
657
+ totalMonthlyPayment: zod.z.number().describe("The total estimated monthly payment (PITI)."),
658
+ widget: zod.z.string().optional()
659
+ });
660
+ var leaseVsPurchaseSchema = zod.z.object({
661
+ // Purchase details
662
+ purchasePrice: zod.z.number().positive("Purchase price must be positive.").describe("Total price of the vehicle for purchase in USD."),
663
+ downPayment: zod.z.number().min(0, "Down payment cannot be negative.").describe("Upfront payment amount for purchase in USD."),
664
+ loanTermInMonths: zod.z.number().positive().int().describe("Loan duration in months for purchase."),
665
+ interestRate: zod.z.number().min(0, "Interest rate cannot be negative.").describe("Annual interest rate for purchase loan (e.g., 5 for 5%)."),
666
+ salesTaxRate: zod.z.number().min(0, "Sales tax rate cannot be negative.").describe("Sales tax rate as a percentage (e.g., 7.5 for 7.5%)."),
667
+ // Lease details
668
+ leaseTermInMonths: zod.z.number().positive().int().describe("Lease duration in months."),
669
+ monthlyLeasePayment: zod.z.number().positive().describe("Monthly payment for the lease in USD."),
670
+ moneyFactor: zod.z.number().positive("Money factor must be positive.").describe("The money factor for the lease (similar to interest rate)."),
671
+ acquisitionFee: zod.z.number().min(0).default(0).describe("Fee charged by the lessor to initiate the lease in USD."),
672
+ securityDeposit: zod.z.number().min(0).default(0).describe("Refundable deposit paid at the start of the lease in USD."),
673
+ // Common details
674
+ residualValuePercentage: zod.z.number().min(0).max(100, "Residual value percentage cannot exceed 100.").describe(
675
+ "Estimated value of the vehicle at the end of the lease, as a percentage of MSRP."
676
+ ),
677
+ expectedOwnershipInMonths: zod.z.number().positive().int().describe("How long you plan to keep the vehicle, in months.")
678
+ });
679
+ var leaseVsPurchaseResponseSchema = zod.z.object({
680
+ purchaseAnalysis: zod.z.object({
681
+ totalLoanPayment: zod.z.number(),
682
+ totalInterestPaid: zod.z.number(),
683
+ totalSalesTax: zod.z.number(),
684
+ equityAfterOwnership: zod.z.number(),
685
+ totalCostOfOwnership: zod.z.number(),
686
+ monthlyPayment: zod.z.number()
687
+ }),
688
+ leaseAnalysis: zod.z.object({
689
+ totalLeasePayments: zod.z.number(),
690
+ totalUpfrontCosts: zod.z.number(),
691
+ totalCostOfLeasing: zod.z.number()
692
+ }),
693
+ comparison: zod.z.object({
694
+ purchaseCostIsLowerBy: zod.z.number(),
695
+ leaseCostIsLowerBy: zod.z.number(),
696
+ recommendation: zod.z.string()
697
+ }),
698
+ widget: zod.z.string().optional()
699
+ });
700
+
701
+ // src/client.ts
702
+ var SecureLend = class {
703
+ /**
704
+ * Create a new SecureLend client
705
+ *
706
+ * @param config - Optional configuration
707
+ */
708
+ constructor(config) {
709
+ let mcpURL = config?.serverUrl || "https://mcp.securelend.ai/mcp";
710
+ if (typeof window !== "undefined" && mcpURL.startsWith("/")) {
711
+ mcpURL = window.location.origin + mcpURL;
712
+ }
713
+ this.mcpClient = new MCPClient({ apiKey: config?.apiKey || "", mcpURL });
714
+ this.mcp = this.mcpClient.mcp;
715
+ }
716
+ // --- Loan Comparison ---
717
+ async comparePersonalLoans(request) {
718
+ return this.callTool(
719
+ "compare_personal_loans",
720
+ request,
721
+ loanComparisonResponseSchema
722
+ );
723
+ }
724
+ async compareBusinessLoans(request) {
725
+ return this.callTool(
726
+ "compare_business_loans",
727
+ request,
728
+ loanComparisonResponseSchema
729
+ );
730
+ }
731
+ async comparePersonalMortgages(request) {
732
+ return this.callTool(
733
+ "compare_personal_mortgages",
734
+ request,
735
+ loanComparisonResponseSchema
736
+ );
737
+ }
738
+ async compareBusinessMortgages(request) {
739
+ return this.callTool(
740
+ "compare_business_mortgages",
741
+ request,
742
+ loanComparisonResponseSchema
743
+ );
744
+ }
745
+ async compareCarLoans(request) {
746
+ return this.callTool(
747
+ "compare_car_loans",
748
+ request,
749
+ loanComparisonResponseSchema
750
+ );
751
+ }
752
+ async compareStudentLoans(request) {
753
+ return this.callTool(
754
+ "compare_student_loans",
755
+ request,
756
+ loanComparisonResponseSchema
757
+ );
758
+ }
759
+ // --- Banking & Credit Cards ---
760
+ async compareBusinessBanking(request) {
761
+ return this.callTool(
762
+ "compare_business_banking",
763
+ request,
764
+ businessBankingComparisonResponseSchema
765
+ );
766
+ }
767
+ async comparePersonalBanking(request) {
768
+ return this.callTool(
769
+ "compare_personal_banking",
770
+ request,
771
+ personalBankingComparisonResponseSchema
772
+ );
773
+ }
774
+ async compareSavingsAccounts(request) {
775
+ return this.callTool(
776
+ "compare_savings_accounts",
777
+ request,
778
+ savingsComparisonResponseSchema
779
+ );
780
+ }
781
+ async compareBusinessCreditCards(request) {
782
+ return this.callTool(
783
+ "compare_business_credit_cards",
784
+ request,
785
+ businessCreditCardComparisonResponseSchema
786
+ );
787
+ }
788
+ async comparePersonalCreditCards(request) {
789
+ return this.callTool(
790
+ "compare_personal_credit_cards",
791
+ request,
792
+ personalCreditCardComparisonResponseSchema
793
+ );
794
+ }
795
+ // --- Financial Calculators ---
796
+ async calculateLoanPayment(request) {
797
+ return this.callTool(
798
+ "calculate_loan_payment",
799
+ request,
800
+ loanPaymentResponseSchema
801
+ );
802
+ }
803
+ async calculateMortgagePayment(request) {
804
+ return this.callTool(
805
+ "calculate_mortgage_payment",
806
+ request,
807
+ mortgagePaymentResponseSchema
808
+ );
809
+ }
810
+ async compareLeaseVsPurchase(request) {
811
+ return this.callTool(
812
+ "compare_lease_vs_purchase",
813
+ request,
814
+ leaseVsPurchaseResponseSchema
815
+ );
816
+ }
817
+ // --- Application Management ---
818
+ async getOffer(request) {
819
+ return this.callTool("get_offer", request, personalApplicationSchema);
820
+ }
821
+ async getMultipleOffers(request) {
822
+ return this.callTool(
823
+ "get_multiple_offers",
824
+ request,
825
+ personalApplicationSchema
826
+ );
827
+ }
828
+ async displayOfferForm(request) {
829
+ return this.callTool(
830
+ "display_offer_form",
831
+ request,
832
+ displayOfferFormResponseSchema
833
+ );
834
+ }
835
+ async trackOfferStatus(request) {
836
+ return this.callTool(
837
+ "track_offer_status",
838
+ request,
839
+ trackOfferStatusResponseSchema
840
+ );
841
+ }
842
+ async displayUploadDocumentsForm(request) {
843
+ return this.callTool(
844
+ "display_upload_documents_form",
845
+ request,
846
+ displayUploadDocumentsFormResponseSchema
847
+ );
848
+ }
849
+ async submitDocuments(request) {
850
+ return this.callTool(
851
+ "submit_documents",
852
+ request,
853
+ submitDocumentsResponseSchema
854
+ );
855
+ }
856
+ // --- Core Methods ---
857
+ /**
858
+ * Manually connect to the MCP server.
859
+ * Connection is otherwise established on the first tool call.
860
+ */
861
+ async connect() {
862
+ await this.mcpClient.connect();
863
+ }
864
+ /**
865
+ * Enable debug logging
866
+ */
867
+ enableDebug() {
868
+ this.mcpClient.enableDebug();
869
+ }
870
+ /**
871
+ * Disable debug logging
872
+ */
873
+ disableDebug() {
874
+ this.mcpClient.disableDebug();
875
+ }
876
+ /**
877
+ * Set the API key for subsequent requests.
878
+ * @param apiKey - The new API key
879
+ */
880
+ setApiKey(apiKey) {
881
+ this.mcpClient.setApiKey(apiKey);
882
+ }
883
+ // --- Private Helpers ---
884
+ async callTool(toolName, request, schema) {
885
+ const toolResult = await this.mcpClient.callTool(
886
+ toolName,
887
+ request
888
+ );
889
+ const data = this.parseJsonResponse(toolResult, schema);
890
+ return { ...data, widget: this.getWidget(toolResult) };
891
+ }
892
+ parseJsonResponse(toolResult, schema) {
893
+ try {
894
+ let jsonData;
895
+ if (toolResult.structuredContent) {
896
+ jsonData = toolResult.structuredContent;
897
+ } else {
898
+ const jsonContent = toolResult.content.find(
899
+ (c) => c.type === "resource" && c.resource && c.resource.mimeType === "application/json" || c.type === "text"
900
+ );
901
+ if (!jsonContent) {
902
+ throw new SecureLendError(
903
+ "Invalid response from MCP server: missing JSON content",
904
+ "mcp_error",
905
+ toolResult
906
+ );
907
+ }
908
+ if (jsonContent.type === "text" && jsonContent.text) {
909
+ jsonData = JSON.parse(jsonContent.text);
910
+ } else if (jsonContent.type === "resource" && jsonContent.resource) {
911
+ jsonData = JSON.parse(jsonContent.resource.text);
912
+ } else {
913
+ throw new Error("Invalid content structure");
914
+ }
915
+ }
916
+ return schema.parse(jsonData);
917
+ } catch (e) {
918
+ if (e instanceof zod.z.ZodError) {
919
+ throw new ValidationError(
920
+ "Invalid response from MCP server: failed to validate JSON content",
921
+ { validationErrors: e.issues, serverResponse: toolResult }
922
+ );
923
+ }
924
+ throw new SecureLendError(
925
+ "Invalid response from MCP server: failed to parse JSON content",
926
+ "mcp_error",
927
+ { originalError: e, serverResponse: toolResult }
928
+ );
929
+ }
930
+ }
931
+ getWidget(toolResult) {
932
+ const widgetContent = toolResult.content.find(
933
+ (c) => c.type === "resource" && c.resource?.mimeType === "text/html"
934
+ );
935
+ if (widgetContent?.type === "resource" && widgetContent.resource) {
936
+ return widgetContent.resource.text;
937
+ }
938
+ return void 0;
939
+ }
940
+ };
941
+
942
+ exports.ApplicationStatus = ApplicationStatus;
943
+ exports.ApplicationType = ApplicationType;
944
+ exports.AuthenticationError = AuthenticationError;
945
+ exports.CreditTier = CreditTier;
946
+ exports.NetworkError = NetworkError;
947
+ exports.NotFoundError = NotFoundError;
948
+ exports.ProductType = ProductType;
949
+ exports.ProviderStatus = ProviderStatus;
950
+ exports.RateLimitError = RateLimitError;
951
+ exports.SecureLend = SecureLend;
952
+ exports.SecureLendError = SecureLendError;
953
+ exports.ServerError = ServerError;
954
+ exports.ValidationError = ValidationError;
955
+ exports.anyOfferSchema = anyOfferSchema;
956
+ exports.applicationProviderSchema = applicationProviderSchema;
957
+ exports.autoLoanSearchSchema = autoLoanSearchSchema;
958
+ exports.bankAccountOfferSchema = bankAccountOfferSchema;
959
+ exports.businessApplicantSchema = businessApplicantSchema;
960
+ exports.businessBankingComparisonResponseSchema = businessBankingComparisonResponseSchema;
961
+ exports.businessBankingOfferSchema = businessBankingOfferSchema;
962
+ exports.businessBankingSearchSchema = businessBankingSearchSchema;
963
+ exports.businessCreditCardComparisonResponseSchema = businessCreditCardComparisonResponseSchema;
964
+ exports.businessCreditCardOfferSchema = businessCreditCardOfferSchema;
965
+ exports.businessCreditCardSearchSchema = businessCreditCardSearchSchema;
966
+ exports.businessLoanSearchSchema = businessLoanSearchSchema;
967
+ exports.createBusinessApplicationSchema = createBusinessApplicationSchema;
968
+ exports.createPersonalApplicationSchema = createPersonalApplicationSchema;
969
+ exports.creditCardOfferSchema = creditCardOfferSchema;
970
+ exports.displayOfferFormResponseSchema = displayOfferFormResponseSchema;
971
+ exports.displayOfferFormSchema = displayOfferFormSchema;
972
+ exports.displayUploadDocumentsFormResponseSchema = displayUploadDocumentsFormResponseSchema;
973
+ exports.displayUploadDocumentsFormSchema = displayUploadDocumentsFormSchema;
974
+ exports.documentTypeEnum = documentTypeEnum;
975
+ exports.getMultipleOffersSchema = getMultipleOffersSchema;
976
+ exports.getOfferSchema = getOfferSchema;
977
+ exports.leaseVsPurchaseResponseSchema = leaseVsPurchaseResponseSchema;
978
+ exports.leaseVsPurchaseSchema = leaseVsPurchaseSchema;
979
+ exports.loanComparisonResponseSchema = loanComparisonResponseSchema;
980
+ exports.loanOfferSchema = loanOfferSchema;
981
+ exports.loanPaymentResponseSchema = loanPaymentResponseSchema;
982
+ exports.loanPaymentSchema = loanPaymentSchema;
983
+ exports.mortgagePaymentResponseSchema = mortgagePaymentResponseSchema;
984
+ exports.mortgagePaymentSchema = mortgagePaymentSchema;
985
+ exports.mortgageSearchSchema = mortgageSearchSchema;
986
+ exports.personalApplicantSchema = personalApplicantSchema;
987
+ exports.personalApplicationSchema = personalApplicationSchema;
988
+ exports.personalBankingComparisonResponseSchema = personalBankingComparisonResponseSchema;
989
+ exports.personalBankingOfferSchema = personalBankingOfferSchema;
990
+ exports.personalBankingSearchSchema = personalBankingSearchSchema;
991
+ exports.personalCreditCardComparisonResponseSchema = personalCreditCardComparisonResponseSchema;
992
+ exports.personalCreditCardOfferSchema = personalCreditCardOfferSchema;
993
+ exports.personalCreditCardSearchSchema = personalCreditCardSearchSchema;
994
+ exports.personalLoanSearchSchema = personalLoanSearchSchema;
995
+ exports.savingsComparisonResponseSchema = savingsComparisonResponseSchema;
996
+ exports.savingsOfferSchema = savingsOfferSchema;
997
+ exports.savingsSearchSchema = savingsSearchSchema;
998
+ exports.studentLoanSearchSchema = studentLoanSearchSchema;
999
+ exports.submitDocumentsResponseSchema = submitDocumentsResponseSchema;
1000
+ exports.submitDocumentsSchema = submitDocumentsSchema;
1001
+ exports.trackOfferStatusResponseSchema = trackOfferStatusResponseSchema;
1002
+ exports.trackOfferStatusSchema = trackOfferStatusSchema;
1003
+ //# sourceMappingURL=index.js.map
1004
+ //# sourceMappingURL=index.js.map