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