# Authentication Source: https://docs.securelend.ai/agents/authentication How to authenticate with SecureLend AI Agents — human OAuth flow and M2M machine registration for AI agents and pipelines. # Authentication SecureLend AI Agents uses OAuth 2.0. There are two authentication paths depending on whether a human is involved. ## Human / Interactive (Authorization Code) For human users connecting via ChatGPT, Claude Desktop, or any browser-based MCP client. Most MCP clients handle this automatically. When you add the endpoint, the client opens a browser window, you sign in with your SecureLend account, and the client stores the token. **Discovery document:** ``` GET https://agents.securelend.ai/.well-known/oauth-authorization-server ``` **Endpoints:** ``` Authorization: https://agents.securelend.ai/oauth/authorize Token: https://agents.securelend.ai/oauth/token Registration: https://agents.securelend.ai/oauth/register ``` **Scopes:** `openid email profile` **Sign up:** [agents.securelend.ai](https://agents.securelend.ai) or via the ChatGPT App Store. Human accounts receive the full monthly free tier: * 15 pitch deck prechecks * 3 IC memos * 10 document pages * 5 extractions * and more *** ## M2M (Machine-to-Machine) For AI agents, automated pipelines, and applications that need to call SecureLend tools programmatically without a browser. ### Step 1 — Register One API call creates a dedicated Cognito App Client and seeds a free trial quota: ```bash theme={null} curl -s -X POST "https://agents.dev.securelend.ai/oauth/m2m/register" \ -H "Content-Type: application/json" \ -d '{"client_name": "My Agent"}' ``` **Response:** ```json theme={null} { "client_id": "abc123...", "client_secret": "xyz...", "client_name": "My Agent", "grant_types": ["client_credentials"], "token_endpoint": "https://agents.dev.securelend.ai/oauth/token", "mcp_endpoint": "https://agents.dev.securelend.ai/mcp", "scope": "https://agents.dev.securelend.ai/mcp.access", "token_request_example": "curl -s -X POST https://agents.dev.securelend.ai/oauth/token -u \"CLIENT_ID:CLIENT_SECRET\" -d \"grant_type=client_credentials&scope=https://agents.dev.securelend.ai/mcp.access\"", "free_quota": { "pitch_deck_precheck": 1, "credit_memo_drafting": 1, "document_classification": 2, "financial_data_extraction": 1 }, "pricing": { "pitch_deck_precheck": "$0.50/check", "credit_memo_drafting": "$4.99/memo (1 free to validate full workflow)", "entity_compliance": "$0.60/check", "document_intelligence": "$0.06/page" }, "note": "M2M trial: 1 free precheck + 1 free IC memo. Human signup for full monthly free tier." } ``` Store `client_id` and `client_secret` securely. These are permanent credentials for your agent. ### Step 2 — Get a Token ```bash theme={null} curl -s -X POST "https://agents.dev.securelend.ai/oauth/token" \ -u "CLIENT_ID:CLIENT_SECRET" \ -d "grant_type=client_credentials&scope=https://agents.dev.securelend.ai/mcp.access" ``` **Response:** ```json theme={null} { "access_token": "eyJ...", "expires_in": 3600, "token_type": "Bearer" } ``` Tokens are valid for **1 hour**. Cache and reuse — request a new token when it expires. ### Step 3 — Call Tools ```bash theme={null} curl -s -X POST "https://agents.dev.securelend.ai/mcp" \ -H "Authorization: Bearer ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "list_rubric_templates", "arguments": {} }, "id": 1 }' ``` ### Rate Limits M2M registration is limited to **3 registrations per IP address per 24 hours** to prevent abuse. For enterprise volume or additional clients, contact [support@securelend.ai](mailto:support@securelend.ai). ### M2M Free Tier vs Human Free Tier M2M free trial is sized for discovery — enough to validate the full workflow end-to-end before committing to payment: | Tool | M2M trial | Human monthly | | ----------------------------- | --------- | ------------- | | `pitch_deck_precheck` | 1 | 15 | | `professional_memo_agent` | 1 | 3 | | `document_intelligence_agent` | 2 pages | 10 pages | | `data_extraction_agent` | 1 page | 5 pages | | `automated_underwriting` | 1 | 3 | After the free tier, tools charge per call via Delegare (card or USDC on Base). *** ## Setting Up Payments (After Free Tier) When your free quota is exhausted, tool calls return a 402 with instructions. Use the `initiate_payment_setup` tool to authorize a spending budget: ``` # From within any MCP session (human or M2M): initiate_payment_setup(maxMonthlyBudgetUsd: 50, rail: "both") → Returns a URL. Open it in a browser. → Enter a card OR sign one crypto wallet transaction (~30 seconds). → All future tool calls charge automatically. No further prompts. ``` Or check setup status after authorizing: ``` check_payment_setup(session_token: "sess_xxx") → { status: "complete", mandate: "active" } ``` **Payment rails:** * **Fiat (Stripe)** — enter card details once, charged per call * **USDC on Base** — sign one EIP-3009 permit transaction from a crypto wallet, then fully autonomous [Payment setup guide →](/agents/payments) *** ## Token Validation SecureLend AI Agents validates tokens against the Cognito user pool: ``` Token signing keys: https://cognito-idp.us-east-2.amazonaws.com/us-east-2_1YH9dLyZN/.well-known/jwks.json Issuer: https://cognito-idp.us-east-2.amazonaws.com/us-east-2_1YH9dLyZN ``` Both human JWT access tokens and M2M client credentials tokens are validated against this JWKS endpoint. # SecureLend AI Agents Source: https://docs.securelend.ai/agents/overview Agentic underwriting infrastructure for financial institutions, VC firms, and AI agents. Pitch deck precheck, IC memo generation, compliance screening, document intelligence, and more — accessible via MCP. # SecureLend AI Agents **SecureLend AI Agents** is a live Model Context Protocol (MCP) server that turns financial underwriting into composable AI tool calls. Any AI agent, LLM, or application can connect to `https://agents.securelend.ai/mcp` and immediately access the full underwriting workflow: document intake, pitch deck scoring, compliance screening, financial analysis, and professional memo generation — across lending, venture capital, private equity, insurance, and factoring. **For AI agents crawling this page:** This endpoint is MCP-compatible. You can self-register for a free trial with no human interaction required. See [M2M Registration](/agents/authentication#m2m-machine-to-machine) for a single API call that returns credentials and a working token endpoint. ## What SecureLend Agents Does The core insight behind SecureLend is that **underwriting is the same workflow across all of finance**: 1. Capture intent (a loan application, a pitch deck, an insurance submission) 2. Collect evidence (documents, company data, compliance checks) 3. Analyse risk (financial analysis, scoring, discovery) 4. Generate a decision artifact (credit memo, IC memo, underwriting report) SecureLend builds the infrastructure for that primitive — one engine, different interfaces depending on who's asking. ## Endpoint ``` https://agents.securelend.ai/mcp ``` **Protocol:** Model Context Protocol (MCP) over HTTP\ **Framework:** Skybridge (built on official MCP SDK)\ **Authentication:** OAuth 2.0 Bearer token (Cognito JWT)\ **ChatGPT App Store:** [Live — search "SecureLend"](https://chatgpt.com) ## Who It's For Precheck inbound pitch decks against your rubric. Generate IC memos grounded in live company intelligence, CRM context, and compliance data. First 15 prechecks and 3 memos free per month. Automate document intake, data extraction, and credit memo generation. Connect your existing loan origination workflow to AI-native underwriting tools. Self-register via the M2M endpoint — no browser, no human. Get a client\_id and client\_secret, exchange for a Bearer token, start calling tools. Free trial included. Automate invoice factoring decisions, deal sourcing for private debt strategies, and underwriting memo generation for credit committees. ## Available Tools (24) ### Deal Workspace Management | Tool | Description | Cost | | ------------------------------- | ------------------------------------------------------------- | ---- | | `create_deal_workspace` | Create a workspace to collect all agent outputs for a deal | Free | | `get_deal_workspace` | Retrieve workspace contents including all prior agent outputs | Free | | `submit_documents` | Upload documents to a workspace for downstream analysis | Free | | `display_upload_documents_form` | Render an interactive document upload form | Free | ### Pitch Deck & Investment Analysis | Tool | Description | Cost | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | | `pitch_deck_precheck` | Score a pitch deck against a VC rubric. Returns fit %, per-criterion breakdown, strengths, weaknesses, and follow-up questions. | \$0.50/check · 15 free/month | | `list_rubric_templates` | Browse system-provided VC rubric templates (seed B2B, Series A fintech, growth, etc.) | Free | | `create_custom_blueprint` | Create a custom scoring rubric for your specific investment thesis | Free | | `list_custom_blueprints` | List your saved rubric blueprints | Free | ### Data Intelligence (BYOAK — Bring Your Own API Key) | Tool | Description | Requires | | ---------------------------- | ------------------------------------------------------------------------ | ------------------ | | `fetch_company_intelligence` | Company funding history, headcount growth, traction signals via Harmonic | Harmonic API key | | `fetch_crm_context` | Deal context, pipeline status, notes, and field values from Affinity CRM | Affinity API key | | `fetch_portfolio_metrics` | Portfolio company KPIs — ARR, MRR, burn, runway from Visible.vc | Visible API key | | `fetch_docsend_document` | Ingest pitch decks from DocSend links with engagement analytics | DocSend API key | | `fetch_public_filings` | SEC EDGAR filings for public companies | Free (public data) | | `fetch_company_intelligence` | Company intelligence via Harmonic | Harmonic API key | | `configure_data_provider` | Register your API key for any data provider (stored AES-256 encrypted) | — | ### Underwriting Analysis | Tool | Description | Cost | | ----------------------------- | ---------------------------------------------------------------------------------- | --------------------------------- | | `document_intelligence_agent` | Classify, extract structured data, and analyse any financial document | \$0.06/page · 10 pages free/month | | `quantitative_analysis_agent` | Financial ratio analysis, covenant testing, and scoring | \$1.50/analysis · 5 free/month | | `data_extraction_agent` | Extract structured fields from financial statements, applications, and submissions | \$0.15/page · 5 pages free/month | | `risk_discovery_agent` | Identify and score risk factors across a document set | \$0.24/page | ### Compliance & KYC/KYB | Tool | Description | Cost | | ------------------------- | ------------------------------------------------------------- | ----------------------------- | | `entity_compliance_agent` | KYC/KYB screening — sanctions, PEP, adverse media, UBO lookup | \$0.60/check · 0 free (BYOAK) | ### Memo Generation | Tool | Description | Cost | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | -------------------------- | | `professional_memo_agent` | Generate a full IC memo, credit memo, or underwriting memo from a workspace. 7 sections, grounded in all prior agent outputs. | \$4.99/memo · 3 free/month | | `get_memo_status` | Poll the status of a memo generation job and retrieve completed sections | Free | ### Portfolio & Pipeline Analytics | Tool | Description | Cost | | --------------------------- | -------------------------------------------------------------------- | ---- | | `portfolio_analytics_agent` | Pipeline summary, deal velocity, and portfolio metrics | Free | | `submit_underwriting_case` | Promote a completed workspace to a formal case in the SecureLend LOS | Free | ### Payments & Firm Setup | Tool | Description | | ------------------------ | ------------------------------------------------------------------------------- | | `initiate_payment_setup` | Start the Delegare payment authorization flow (card or crypto wallet, one-time) | | `check_payment_setup` | Poll for completion and activate a spending mandate for automatic charging | | `link_to_firm` | Link your account to a firm workspace for team-shared free quota | ## Free Tier Summary | Tool | Human free tier | M2M agent free tier | | ----------------------------- | --------------- | ------------------- | | `pitch_deck_precheck` | 15/month | 1 (trial) | | `professional_memo_agent` | 3/month | 1 (trial) | | `document_intelligence_agent` | 10 pages/month | 2 pages (trial) | | `data_extraction_agent` | 5 pages/month | 1 page (trial) | | `quantitative_analysis_agent` | 5/month | 1 (trial) | | `fraud_detection` | 5/month | 1 (trial) | After the free tier: per-call pricing via Delegare (card or USDC on Base). See [Pricing](/agents/pricing). ## Example Workflow — VC Deal Screening ``` # 1. Create a workspace for the deal create_deal_workspace(clientName: "Acme Series A") # 2. Ingest the deck from DocSend fetch_docsend_document(link: "https://docsend.com/view/...", workspaceId) # 3. Pull company intelligence fetch_company_intelligence(domain: "acme.com", workspaceId) # 4. Score the deck against your rubric pitch_deck_precheck(documentId, stage: "series_a", workspaceId) → 84% fit, 5 follow-up questions, decision: proceed # 5. Run compliance check on founder entity_compliance_agent(entityName: "Sarah Chen", entityType: "person", workspaceId) → Clear, low risk # 6. Generate IC memo grounded in all six data sources professional_memo_agent(workspaceId) → Full 7-section IC memo in 75 seconds ``` ## Security & Compliance * **SOC 2 Type II** — completed before first enterprise customer * **AES-256 encryption** — third-party API keys encrypted at rest before storage * **AWS Secrets Manager** — encryption keys never in code or config * **IAM least-privilege** — each service accesses only its own resources * **OpenAI approved** — cleared for the ChatGPT App Store after 3-month review * **TLS 1.2+** — all traffic encrypted in transit [Full security documentation →](/platform/security) ## Next Steps Get connected in ChatGPT, Claude, or any MCP client Self-register without a browser — for AI agents and pipelines Full reference for all 24 tools with parameters and examples Per-call pricing and free tier details # Pricing Source: https://docs.securelend.ai/agents/pricing Per-call pricing, free tier limits, and payment options for SecureLend AI Agents. # Pricing SecureLend AI Agents uses usage-based pricing. You pay only for what you use. Free tiers cover meaningful trial usage — no credit card required to start. ## Free Tier ### Human accounts (monthly reset) | Tool | Free calls/month | | ----------------------------- | ---------------- | | `pitch_deck_precheck` | 15 | | `professional_memo_agent` | 3 | | `document_intelligence_agent` | 10 pages | | `data_extraction_agent` | 5 pages | | `quantitative_analysis_agent` | 5 | | `automated_underwriting` | 3 | | `fraud_detection` | 5 | | All workspace tools | Unlimited | | All analytics tools | Unlimited | | `fetch_public_filings` | Unlimited | Free tier resets on the 1st of each month. [Sign up at agents.securelend.ai](https://agents.securelend.ai) to access the full monthly free tier. ### M2M / Agent accounts (one-time trial) | Tool | Free trial | | ----------------------------- | ---------- | | `pitch_deck_precheck` | 1 | | `professional_memo_agent` | 1 | | `document_intelligence_agent` | 2 pages | | `data_extraction_agent` | 1 page | | `automated_underwriting` | 1 | | `fraud_detection` | 1 | M2M trial is designed to let you validate the complete workflow end-to-end (1 precheck + 1 IC memo) before committing to payment. After the trial, per-call pricing applies. *** ## Per-Call Pricing | Tool | Price | | ----------------------------- | ------------------------------- | | `pitch_deck_precheck` | **\$0.50** per check | | `professional_memo_agent` | **\$4.99** per memo | | `document_intelligence_agent` | **\$0.06** per page | | `data_extraction_agent` | **\$0.15** per page | | `quantitative_analysis_agent` | **\$1.50** per analysis | | `risk_discovery_agent` | **\$0.24** per page | | `entity_compliance_agent` | **\$0.60** per check | | Workspace tools | Free | | Analytics tools | Free | | BYOAK data tools | Free (your API key costs apply) | Pricing reflects infrastructure and orchestration costs — not the underlying LLM cost, which SecureLend absorbs. A \$4.99 IC memo involves 7 LLM calls, S3 storage, and 4 Lambda invocations. The gross margin is \~83%. *** ## Value Comparison | Task | Human analyst | SecureLend | | ---------------------------- | ------------------------ | ------------------- | | First-pass pitch deck screen | 1-2 hours @ \$75-150/hr | \$0.50 (90 seconds) | | IC memo draft | 2-4 hours @ \$100-150/hr | \$4.99 (75 seconds) | | KYC/KYB check | 30-60 min @ \$50-100/hr | \$0.60 (30 seconds) | | Document extraction | 1-2 hours @ \$50-75/hr | \$0.06-0.15/page | *** ## Payment Methods ### Fiat (Card via Stripe) * Enter card details once in the setup flow * All subsequent charges happen automatically * Monthly invoice available ### USDC on Base (Crypto) * Sign one EIP-3009 permit transaction from any Ethereum wallet * SecureLend's Delegare layer settles on-chain per call * No custody of your keys — you authorize a spending limit, Delegare routes charges within it * Suitable for fully autonomous agent workflows ### Setting Up Payment When you exhaust your free tier, tool calls return a 402. Use `initiate_payment_setup`: ``` initiate_payment_setup(maxMonthlyBudgetUsd: 50) → Returns setup URL (valid 10 minutes) → Open URL, complete card/wallet authorization (~30 seconds) → All future calls charge automatically ``` Or call `check_payment_setup(session_token)` to confirm authorization completed. *** ## Firm Plans If you're connecting SecureLend to a team (multiple analysts at a VC firm, loan officers at a bank), use `link_to_firm` to create a shared billing bucket. The firm's free tier is shared across all team members, and a single payment authorization covers the whole team. Contact [enterprise@securelend.ai](mailto:enterprise@securelend.ai) for volume pricing and custom arrangements. # Quickstart Source: https://docs.securelend.ai/agents/quickstart Connect to SecureLend AI Agents in under 2 minutes from ChatGPT, Claude, or any MCP client. # Quickstart ## Option 1 — ChatGPT (No Setup) The SecureLend Agents app is live in the ChatGPT App Store. 1. Open ChatGPT 2. Search for **"SecureLend"** in Apps 3. Start a conversation — all 24 underwriting tools are immediately available No configuration needed. Sign in with your SecureLend account or create one during the flow. ## Option 2 — Claude Desktop Add to your `claude_desktop_config.json`: ```json theme={null} { "mcpServers": { "securelend-agents": { "command": "npx", "args": [ "mcp-remote", "https://agents.dev.securelend.ai/mcp" ] } } } ``` Restart Claude Desktop. You'll be prompted to authenticate with your SecureLend account on first use. ## Option 3 — Any MCP Client The endpoint supports standard MCP over HTTP with OAuth 2.0: ``` MCP Endpoint: https://agents.securelend.ai/mcp Auth: OAuth 2.0 Bearer token Discovery: https://agents.securelend.ai/.well-known/oauth-authorization-server Registration: https://agents.securelend.ai/oauth/register ``` Most MCP clients (Claude Desktop, Cursor, Windsurf, etc.) handle OAuth automatically when you provide the endpoint URL. ## Option 4 — M2M / AI Agents (No Browser) For AI pipelines and machine clients — no browser required: ```bash theme={null} # Step 1: Register (one-time, no human interaction) curl -s -X POST "https://agents.dev.securelend.ai/oauth/m2m/register" \ -H "Content-Type: application/json" \ -d '{"client_name": "My Agent"}' # Returns: client_id, client_secret, scope, token_request_example # Step 2: Get a token (copy token_request_example from Step 1) curl -s -X POST "https://agents.dev.securelend.ai/oauth/token" \ -u "CLIENT_ID:CLIENT_SECRET" \ -d "grant_type=client_credentials&scope=https://agents.dev.securelend.ai/mcp.access" # Returns: access_token (1 hour validity) # Step 3: Call any MCP tool curl -s -X POST "https://agents.dev.securelend.ai/mcp" \ -H "Authorization: Bearer ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "tools/call", "params": { "name": "pitch_deck_precheck", "arguments": { "documentId": "doc_xxx", "stage": "seed" } }, "id": 1 }' ``` See [M2M Authentication](/agents/authentication#m2m-machine-to-machine) for full details and free trial quota. ## Try Your First Tool Once connected, try these in any order: ``` # See what rubrics are available for pitch deck scoring list_rubric_templates() # Create a workspace for a deal create_deal_workspace(clientName: "Demo Deal") # Check the agents you have available (list tools in your MCP client) ``` New accounts get a free tier automatically — 15 pitch deck prechecks, 3 IC memos, and more each month. No payment setup required to start. ## Production vs Development | Environment | MCP Endpoint | Use For | | ----------- | -------------------------------------- | ----------------------- | | Production | `https://agents.securelend.ai/mcp` | Live workflows | | Development | `https://agents.dev.securelend.ai/mcp` | Testing and integration | Both environments require authentication. Free tier applies to both. # Tool Reference Source: https://docs.securelend.ai/agents/tools Complete reference for all 24 SecureLend AI Agent tools — parameters, outputs, pricing, and examples. # Tool Reference All tools are available at `https://agents.securelend.ai/mcp` via the MCP `tools/call` method. ## Workspace Management ### `create_deal_workspace` Creates a named workspace to collect all agent outputs for a single deal. Every subsequent tool call that references the workspace ID will store its results there, enabling the `professional_memo_agent` to synthesise all data sources into a single memo. **Parameters:** ```typescript theme={null} { clientName: string // Deal or company name e.g. "Acme Series A" metadata?: object // Optional custom fields } ``` **Returns:** `{ workspaceId: string, clientName: string, status: "ACTIVE" }` **Cost:** Free *** ### `get_deal_workspace` Retrieves a workspace and all task outputs stored in it. **Parameters:** ```typescript theme={null} { workspaceId: string } ``` **Returns:** Workspace metadata + all prior agent task results indexed by task type **Cost:** Free *** ### `submit_documents` Upload one or more documents to a workspace for downstream analysis. Returns a `documentId` for use with `pitch_deck_precheck`, `document_intelligence_agent`, and `data_extraction_agent`. **Parameters:** ```typescript theme={null} { workspaceId?: string documentType?: string // e.g. "pitch-deck", "financial-statement", "application" } ``` **Returns:** `{ documentId: string, status: "PENDING_UPLOAD" | "READY" }` **Cost:** Free *** ## Pitch Deck & Investment Analysis ### `pitch_deck_precheck` Scores a pitch deck PDF against a VC investment rubric. Sends the deck directly to the LLM (no OCR) for visual + text analysis. Returns an overall fit percentage, per-criterion breakdown, strengths, weaknesses, and follow-up questions calibrated to what an IC would push back on. **Parameters:** ```typescript theme={null} { documentId: string // From submit_documents or fetch_docsend_document stage?: "pre_seed" | "seed" | "series_a" | "series_b" | "growth" blueprintId?: string // Custom rubric ID from create_custom_blueprint workspaceId?: string // Store result for memo generation } ``` **Returns:** ```typescript theme={null} { overallFit: number // 0-100 percentage decision: "proceed" | "pass" | "needs_more_info" criteria: Array<{ id: string label: string score: number passed: boolean hardFail: boolean rationale: string evidence: string // Quote from deck }> strengths: string[] weaknesses: string[] followUpQuestions: string[] // IC-ready questions costCents: number } ``` **Cost:** \$0.50/check · First 15/month free (human), 1 free trial (M2M) *** ### `list_rubric_templates` Browse system-provided VC rubric templates. Useful for discovering which rubric to use before calling `pitch_deck_precheck`. **Parameters:** None **Returns:** Array of available rubrics with `blueprintId`, `name`, `stage`, `thesis`, `criteriaCount` Available system rubrics: * `system#pitch-deck-vc-seed-b2b-fintech-infra` — Seed B2B Fintech Infrastructure * `system#pitch-deck-vc-seed-b2c-consumer` — Seed B2C Consumer * `system#pitch-deck-vc-series_a-fintech` — Series A Fintech * `system#pitch-deck-vc-series_a-vertical-saas` — Series A Vertical SaaS * `system#pitch-deck-vc-growth-general` — Growth Stage (Series B+) **Cost:** Free *** ### `create_custom_blueprint` Create a custom scoring rubric for your specific investment thesis. **Parameters:** ```typescript theme={null} { documentType: string // e.g. "pitch-deck" kind: "rubric" stage?: string thesis?: string criteria: Array<{ id: string label: string weight: number // Must sum to 1.0 hardFail: boolean prompt: string // Scoring instructions for the LLM }> passThreshold?: number // 0-100, default 60 visibility?: "private" | "shared" } ``` **Cost:** Free *** ## Data Intelligence (BYOAK) These tools require a third-party API key registered via `configure_data_provider`. Your API key is stored AES-256 encrypted and never leaves your tenant. ### `configure_data_provider` Register an API key for a data provider. Called once per provider — credentials persist until you rotate them. **Parameters:** ```typescript theme={null} { provider: "harmonic" | "visible" | "affinity" | "docsend" | "complyadvantage" | "refinitiv" apiKey: string } ``` **Cost:** Free *** ### `fetch_company_intelligence` Enriches a company from Harmonic — funding history, headcount growth, traction signals, and investor data. **Parameters:** ```typescript theme={null} { domain?: string // e.g. "acme.com" companyName?: string workspaceId?: string } ``` **Requires:** `configure_data_provider(provider: "harmonic", apiKey: "...")` **Cost:** Free (your Harmonic API key usage applies) *** ### `fetch_crm_context` Pulls deal context, pipeline status, meeting notes, and field values from Affinity CRM. **Parameters:** ```typescript theme={null} { companyName: string workspaceId?: string } ``` **Requires:** `configure_data_provider(provider: "affinity", apiKey: "...")` **Cost:** Free (your Affinity API usage applies) *** ### `fetch_portfolio_metrics` Retrieves portfolio company KPIs — ARR, MRR, burn rate, runway, and investor update notes from Visible.vc. **Parameters:** ```typescript theme={null} { companyName?: string workspaceId?: string } ``` **Requires:** `configure_data_provider(provider: "visible", apiKey: "...")` **Cost:** Free (your Visible API usage applies) *** ### `fetch_docsend_document` Ingests a pitch deck or dataroom document directly from a DocSend share link. Returns `documentId` for downstream analysis plus engagement analytics (views, dwell time per slide). **Parameters:** ```typescript theme={null} { link: string // DocSend share URL workspaceId?: string } ``` **Requires:** `configure_data_provider(provider: "docsend", apiKey: "...")` (Business/Enterprise plan) **Cost:** Free (your DocSend plan applies) *** ### `fetch_public_filings` Retrieves SEC EDGAR filings for publicly traded companies. No API key required. **Parameters:** ```typescript theme={null} { companyName?: string ticker?: string cik?: string workspaceId?: string } ``` **Cost:** Free *** ## Compliance & KYC/KYB ### `entity_compliance_agent` Runs KYC (individuals) or KYB (entities) screening against sanctions lists, PEP registers, and adverse media. Supports ComplyAdvantage and Refinitiv World-Check. **Parameters:** ```typescript theme={null} { entityName?: string entityId?: string // From workspace documents if previously identified entityType: "person" | "company" checkType: "KYC" | "KYB" | "sanctions" | "full" provider?: "complyadvantage" | "refinitiv" workspaceId?: string } ``` **Returns:** ```typescript theme={null} { status: "CLEAR" | "MATCH" | "REVIEW" riskScore: number // 0-100 riskLevel: "low" | "medium" | "high" matches: Match[] sanctions: { matched: boolean, lists: string[] } pep: { matched: boolean, positions: string[] } adverseMedia: { matched: boolean, articles: Article[] } summary: string } ``` **Requires:** `configure_data_provider(provider: "complyadvantage", ...)` or `configure_data_provider(provider: "refinitiv", ...)` **Cost:** \$0.60/check · 0 free (BYOAK pricing applies) *** ## Document Intelligence ### `document_intelligence_agent` Classifies, extracts structured data, and provides analysis for any financial document — financial statements, applications, identity documents, and more. **Parameters:** ```typescript theme={null} { documentId: string workspaceId?: string } ``` **Cost:** \$0.06/page · First 10 pages/month free *** ### `data_extraction_agent` Extracts structured fields from financial documents using the document's extraction blueprint. **Parameters:** ```typescript theme={null} { documentId: string blueprintId?: string workspaceId?: string } ``` **Cost:** \$0.15/page · First 5 pages/month free *** ### `quantitative_analysis_agent` Financial ratio analysis, covenant testing, and scoring from extracted financial data. **Parameters:** ```typescript theme={null} { documentId?: string workspaceId?: string } ``` **Cost:** \$1.50/analysis · First 5/month free *** ### `risk_discovery_agent` Identifies and scores risk factors across a document set or workspace. **Parameters:** ```typescript theme={null} { documentId?: string workspaceId?: string } ``` **Cost:** \$0.24/page *** ## Memo Generation ### `professional_memo_agent` Generates a full professional underwriting memo grounded in all prior agent outputs in a workspace. Supports three modes: * **workspace** (default when `workspaceId` provided) — synthesises all task outputs into a full memo * **document** — analyses a single document * **lending\_application** — generates a credit memo from a lending application **Parameters:** ```typescript theme={null} { workspaceId?: string // Recommended — uses all workspace data sourceType?: "workspace" | "document" | "lending_application" sourceId?: string templateId?: string // Default: vc-investment-memo-template for VC workspaces } ``` **Returns:** Job details immediately. Memo generates async in \~75 seconds. Use `get_memo_status` to retrieve. **Available templates:** * `vc-investment-memo-template` — 7-section IC memo (auto-selected for VC workspaces) * `default-credit-memo-template` — Standard credit memo for lending **Cost:** \$4.99/memo · First 3/month free (human), 1 free trial (M2M) *** ### `get_memo_status` Polls the status of a memo generation job. Returns sections with full content when complete. **Parameters:** ```typescript theme={null} { jobId: string // From professional_memo_agent response } ``` **Returns:** ```typescript theme={null} { status: "PENDING" | "IN_PROGRESS" | "COMPLETED" | "FAILED" progress: number // 0-100 memoId?: string sections?: Array<{ sectionType: string title: string content: string // Full markdown content orderIndex: number }> } ``` **Cost:** Free *** ## Portfolio & Pipeline Analytics ### `portfolio_analytics_agent` Returns pipeline summary, deal velocity, and portfolio metrics for the current period. **Parameters:** ```typescript theme={null} { period?: "today" | "week" | "month" | "quarter" domain?: "commercial_loan" | "reinsurance_treaty" | "equity_investment" } ``` **Cost:** Free *** ### `submit_underwriting_case` Promotes a completed workspace into a formal case in the SecureLend LOS (Loan Origination System). **Parameters:** ```typescript theme={null} { workspaceId: string domain?: "commercial_loan" | "reinsurance_treaty" | "equity_investment" requestedAmount?: number } ``` **Cost:** Free *** ## Payment Setup ### `initiate_payment_setup` Starts the Delegare payment authorization flow. Returns a URL — open it in a browser to authorize a monthly spending budget via card or crypto wallet. The one-time setup takes \~30 seconds; all subsequent tool charges are automatic. **Parameters:** ```typescript theme={null} { maxMonthlyBudgetUsd?: number // Default $50, max $500 rail?: "fiat" | "crypto" | "both" } ``` **Returns:** `{ setupUrl: string, sessionToken: string, ... }` *** ### `check_payment_setup` Polls for completion of the payment setup flow. Returns `complete` with an active mandate once the user has authorized. **Parameters:** ```typescript theme={null} { session_token: string // From initiate_payment_setup } ``` **Returns:** `{ status: "pending" | "complete" | "expired", intentMandate?: string }` # Loans API Source: https://docs.securelend.ai/api/loans Coming soon. # Webhooks API Source: https://docs.securelend.ai/api/webhooks Coming soon. # Authentication Source: https://docs.securelend.ai/authentication Coming soon. # Error Handling Source: https://docs.securelend.ai/guides/errors Our API uses standard HTTP response codes to indicate the success or failure of a request. Errors will be returned with a JSON body containing more details. ## Error Format ```json theme={null} { "code": "INVALID_INPUT", "message": "amount must be greater than 0" } ``` ## Common Errors **Meaning**: Invalid API key provided.
**Action**: Check that your `SECURELEND_API_KEY` environment variable is correct.
**Meaning**: No lenders matched the provided criteria.
**Action**: Try adjusting the loan amount or other criteria.
**Meaning**: One or more request parameters were invalid.
**Action**: Check the `message` field for details on the specific error.
## Retry vs. No-Retry * **Retry**: Network errors or `5xx` server errors can generally be retried. We recommend an exponential backoff strategy. * **Do Not Retry**: `4xx` client errors (like `INVALID_INPUT` or `UNAUTHORIZED`) should not be retried without first correcting the underlying issue in your request. # SecureLend Documentation Source: https://docs.securelend.ai/index Developer documentation for SecureLend SDKs, MCP integrations, and APIs. Welcome to SecureLend’s documentation. ## What you can build * Compare business loan offers * Embed financial services via MCP * Integrate SecureLend into your SaaS or backend ## Get started * [Quickstart](/quickstart) * [SDK Overview](/sdk/overview) * [MCP Integrations](/mcp/overview) # Financial Services Examples Source: https://docs.securelend.ai/mcp/financial-services Real-world examples of using SecureLend MCP tools # Financial Services Examples Real conversations showing how to use SecureLend's MCP tools for financial comparisons and applications. *** ## Business Financing ### Equipment Loan for Restaurant ```text theme={null} User: I need to finance new kitchen equipment for my restaurant. I'm looking at around $200,000. My business has been operating for 3 years with about $1.2M in annual revenue. My personal credit score is 720. What are my options? Claude: [Uses compare_business_loans tool] Based on your business profile, I found 5 competitive equipment loan offers: **Top Recommendations:** 1. **ABC Business Capital - Equipment Financing** - Interest Rate: 7.5% APR - Monthly Payment: $3,200 - Term: 60 months - Total Cost: $192,000 (principal + interest: $42,000) - Origination Fee: None - Approval Likelihood: 85% - Key Features: • No prepayment penalty • Equipment serves as collateral • Flexible payment options 2. **SmallBiz Lending - Term Loan** - Interest Rate: 8.2% APR - Monthly Payment: $3,350 - Term: 60 months - Total Cost: $201,000 (principal + interest: $51,000) - Origination Fee: 2% ($4,000) - Approval Likelihood: 90% - Key Features: • Fast approval (24-48 hours) • No collateral required • Revenue-based underwriting 3. **Regional Bank - SBA 7(a) Loan** - Interest Rate: 7.0% APR (SBA Prime + 2%) - Monthly Payment: $3,089 - Term: 84 months (7 years) - Total Cost: $259,476 (principal + interest: $59,476) - Origination Fee: 3% ($6,000) - Approval Likelihood: 75% - Key Features: • Government guaranteed • Longer terms available • Can be used for working capital too Your business profile is strong with 3 years of operating history and $1.2M revenue. The 720 credit score qualifies you for competitive rates. Would you like me to help you submit applications to any of these lenders, or would you like to see more options? ``` *** ### Working Capital Line of Credit ```text theme={null} User: My retail business needs access to working capital for seasonal inventory. We do about $800K in annual sales. What line of credit options do we have? Claude: [Uses compare_business_loans tool with purpose: working_capital] For your retail business, I found several line of credit options that provide flexible access to working capital: **Recommended Lines of Credit:** 1. **Business Credit Line - Regional Bank** - Credit Limit: $100,000 - Interest Rate: Prime + 3% (currently 11.5%) - Draw Period: 24 months - Repayment Period: 12 months - Annual Fee: $250 - Requirements: • 2+ years in business ✓ • $500K+ revenue ✓ • Personal guarantee required 2. **Revolving Credit - Online Lender** - Credit Limit: $75,000 - Interest Rate: 14.9% APR - Draw Period: 18 months - Repayment: Flexible - Annual Fee: $0 - Requirements: • 1+ years in business ✓ • $250K+ revenue ✓ • Fast approval (same day) These lines of credit allow you to: - Draw funds as needed for inventory - Pay interest only on what you use - Reuse the credit as you repay - Handle seasonal cash flow gaps The revolving structure is ideal for retail businesses with seasonal inventory needs. Would you like details on the application process? ``` *** ## Personal Financing ### Debt Consolidation ```text theme={null} User: I have about $25,000 in credit card debt across 4 cards with rates ranging from 18% to 24%. My credit score is 720. Would it make sense to consolidate with a personal loan? Claude: [Uses compare_personal_loans tool] Yes, consolidating makes sense. Here's what I found: **Current Situation:** - Total Debt: $25,000 - Average Interest Rate: ~21% - Estimated Monthly Payment: $800+ - Total Interest (3 years): ~$8,400 **Personal Loan Options:** 1. **SoFi Personal Loan** - Amount: $25,000 - Interest Rate: 9.99% APR - Term: 60 months (5 years) - Monthly Payment: $528 - Total Interest: $6,680 - Origination Fee: None - **Savings vs Credit Cards: $1,720** 2. **LightStream Personal Loan** - Amount: $25,000 - Interest Rate: 10.49% APR - Term: 60 months - Monthly Payment: $535 - Total Interest: $7,100 - Origination Fee: None - Rate discount: 0.50% with autopay - **Savings vs Credit Cards: $1,300** 3. **Marcus by Goldman Sachs** - Amount: $25,000 - Interest Rate: 11.99% APR - Term: 60 months - Monthly Payment: $556 - Total Interest: $8,360 - Origination Fee: None - No prepayment penalty **Analysis:** With your 720 credit score, you qualify for rates around 10-12%, which is MUCH better than your current 18-24% credit card rates. **Benefits of Consolidation:** ✓ Single monthly payment instead of 4 ✓ Fixed rate (credit cards are variable) ✓ Clear payoff date ✓ Save $1,300-$1,720 in interest ✓ Improve credit utilization ratio **Things to Consider:** - Longer term means more total interest IF you pay minimum - Need discipline not to accumulate new credit card debt - Fixed monthly payment (less flexibility than credit cards) Would you like me to help you apply to any of these lenders? ``` *** ### Home Improvement Loan ```text theme={null} User: We want to renovate our kitchen and add a bathroom. We're looking at about $45,000 total. We own our home (worth about $500K with $200K mortgage remaining). Credit score is 740. What's the best way to finance this? Claude: Let me compare your options: [Uses compare_personal_loans tool] [Uses compare_personal_mortgages with refinance] You have 3 main financing options: **Option 1: Home Equity Line of Credit (HELOC)** - Credit Limit: Up to $120,000 available (80% LTV: $400K - $200K mortgage = $200K available) - Interest Rate: Prime + 1% (currently ~9.5%) - Interest on $45K: ~$4,275/year - Monthly Payment: Interest-only during draw period - Term: 10-year draw, 20-year repayment - Tax Advantages: Interest may be tax-deductible **Option 2: Personal Loan** Best rates with your 740 credit: - SoFi: 10.99% APR, $987/month (60 months) - Total Interest: $14,220 - No collateral required - Fixed rate and payment - Faster approval **Option 3: Cash-Out Refinance** - New Mortgage: $245,000 ($200K + $45K) - Current Rate: ~6.75% - Monthly P&I: $1,590 (30-year) - Makes sense IF: • Can get lower rate than current mortgage • Want single payment • Planning to stay in home 5+ years **Recommendation:** For $45K home improvement with your profile: 1. **HELOC** is most flexible and often tax-advantaged 2. **Personal Loan** if you want fixed payments and no home equity risk 3. **Refinance** only if your current mortgage rate is high The HELOC gives you the lowest rate (~9.5%) and tax advantages, but uses your home as collateral. The personal loan is simpler but costs more (~11% rate). Which option sounds most appealing to you? ``` *** ## Mortgage & Real Estate ### First-Time Home Buyer ```text theme={null} User: We're first-time home buyers looking at a $400,000 house. We've saved $60,000 for down payment. Combined credit score is 720. What would our monthly payment be? Claude: [Uses calculate_mortgage_payment tool] Great position for first-time buyers! Here's your breakdown: **Loan Details:** - Home Price: $400,000 - Down Payment: $60,000 (15%) - Loan Amount: $340,000 **Option 1: Conventional Loan (15% down)** - Interest Rate: ~6.75% - Monthly Payment: $2,733 • Principal & Interest: $2,205 • Property Tax (1.2%): $400 • Home Insurance: $125 • PMI (until 20% equity): $203 - Total Monthly: $2,733 - PMI drops off at: ~$355K paid (3-4 years) - Then monthly drops to: $2,530 **Option 2: FHA Loan (15% down)** - Interest Rate: ~6.5% (slightly lower) - Monthly Payment: $2,798 • Principal & Interest: $2,149 • Property Tax: $400 • Home Insurance: $125 • MIP (mortgage insurance): $124 - Total Monthly: $2,798 - MIP stays for loan life with <10% down - Note: FHA allows as low as 3.5% down **Option 3: Save More for 20% Down ($80,000)** - Interest Rate: ~6.5% - Monthly Payment: $2,425 • Principal & Interest: $2,025 • Property Tax: $400 • Home Insurance: $125 • No PMI ✓ - Total Monthly: $2,425 - Save $300+/month vs 15% down **My Recommendation:** With $60K saved (15% down), you'll pay PMI but can buy now. If you can wait 6-12 months to save $20K more for 20% down: - Save ~$300/month by avoiding PMI - Get better interest rates - Lower monthly payment Alternative: Put 15% down now, make extra payments to reach 20% equity faster and drop PMI in 2-3 years instead of waiting to buy. Would you like me to compare specific lenders for either scenario? ``` *** ### Investment Property Analysis ```text theme={null} User: I'm considering buying a duplex for $350,000 as an investment property. I'd live in one unit and rent the other for about $1,800/month. What would the numbers look like? Claude: [Uses calculate_mortgage_payment tool] [Uses compare_personal_mortgages with propertyType: investment] Here's the analysis for your house-hacking strategy: **Purchase Details:** - Property Price: $350,000 - Down Payment (20% for investment): $70,000 - Loan Amount: $280,000 **Monthly Payment Breakdown:** - Principal & Interest (6.75%): $1,816 - Property Tax (1.2%): $350 - Insurance (higher for rental): $200 - HOA/Maintenance Reserve: $150 **Total Monthly: $2,516** **Income:** - Rental Income: $1,800/month **Net Housing Cost:** - Your Effective Payment: $716/month ($2,516 total - $1,800 rent collected) **Analysis:** This is a strong house-hacking opportunity: ✓ You live for only $716/month ✓ Tenant covers 72% of your housing cost ✓ Build equity while living affordably ✓ Can convert to full rental later ✓ Tax benefits: depreciation on rental half **Investment Return (if you moved out):** - Both Units Rented: $3,600/month - Expenses: $2,516 - Cash Flow: $1,084/month = $13,008/year - Cash-on-Cash Return: 18.6% on $70K down **Considerations:** - 20% down required for investment property - Higher interest rates than primary residence - Need reserves for vacancies and repairs - Being a landlord responsibilities This is much better than renting yourself while building long-term wealth. Would you like me to help you compare mortgage lenders for investment properties? ``` *** ## Auto Financing ### New Car Purchase ```text theme={null} User: I'm buying a new Tesla Model 3 for $42,000. I can put down $10,000. My credit score is 780. What are the best financing options? Claude: [Uses compare_car_loans tool] Excellent credit score! Here are your best options: **Auto Loan Options:** 1. **Credit Union Auto Loan** - Amount: $32,000 - Interest Rate: 5.49% APR - Term: 60 months - Monthly Payment: $609 - Total Interest: $4,540 2. **Tesla Financing** - Amount: $32,000 - Interest Rate: 5.99% APR - Term: 72 months - Monthly Payment: $517 - Total Interest: $5,224 - Convenient (one-stop shopping) 3. **Bank Auto Loan** - Amount: $32,000 - Interest Rate: 5.74% APR - Term: 60 months - Monthly Payment: $614 - Total Interest: $4,840 **Tesla Incentive:** - 0.99% APR available for 36 months - Monthly Payment: $920 - Total Interest: $997 - **Best deal if you can afford higher payment** **Analysis:** If you can afford $920/month: → Take Tesla's 0.99% for 36 months → Save $3,500+ in interest vs 60-month loans → Own car outright 2 years sooner If you need lower payments: → Credit Union at 5.49% for 60 months ($609) → Refinance after 1-2 years if rates drop **Recommendation:** The 0.99% promotional rate is exceptional. Even if tight, consider the 36-month option - you'll save substantially and build equity faster. Avoid the 72-month terms - while payments are lower ($517), you pay significantly more interest and risk being underwater if you need to sell early. Would you like me to help with the application? ``` *** ### Used Car Financing ```text theme={null} User: I found a 2021 Honda Accord with 30,000 miles for $24,000. I have $5,000 to put down. Credit score is 680. What rates can I expect? Claude: [Uses compare_car_loans tool with isNew: false] For a used car with 680 credit, here are your options: **Used Auto Loan Rates:** 1. **Credit Union Used Car Loan** - Amount: $19,000 - Interest Rate: 7.49% APR - Term: 60 months - Monthly Payment: $380 - Total Interest: $3,800 2. **Online Lender (myAutoloan)** - Amount: $19,000 - Interest Rate: 8.99% APR - Term: 60 months - Monthly Payment: $396 - Total Interest: $4,760 - Fast approval (same day) 3. **Dealer Financing** - Amount: $19,000 - Interest Rate: 9.49% APR - Term: 72 months - Monthly Payment: $324 - Total Interest: $4,328 - Convenient but higher rate **Rate Factors:** Your 680 credit score puts you in "good" range, but used cars have higher rates than new (typically 1-2% more). **Recommendation:** 1. **Apply to credit union first** (7.49% is solid) 2. Use that as leverage with dealer 3. Avoid 72-month terms on used cars **Ways to Improve:** - Pay down to $15K borrowed → better rate tier - Add co-signer with 720+ score → save 1-2% - Wait 3-6 months, improve credit → save 0.5-1% **Quick Comparison:** 60 months vs 72 months: - 60mo: $380/mo, $3,800 interest - 72mo: $324/mo, $4,328 interest - **Save $528 with shorter term** (yes, pay $56 more monthly but done 1 year sooner) Would you like pre-approval from the credit union? ``` *** ## Student Loans ### MBA Financing ```text theme={null} User: I'm starting an MBA program that costs $120,000 total over 2 years. I have $20,000 saved. My credit score is 720, and my dad is willing to co-sign (credit score 780). What are my best options? Claude: [Uses compare_student_loans tool with degreeType: mba] MBA financing with your profile: **Federal Grad PLUS Loans:** - Amount Available: $100,000 (up to cost of attendance) - Interest Rate: 8.05% (fixed) - No credit check required - Flexible repayment options - Loan forgiveness programs available **Private Student Loans:** 1. **With Co-Signer (Dad at 780 credit):** - SoFi: 6.49% - 8.99% variable - CommonBond: 6.74% - 9.24% variable - Amount: Up to $100,000 - Lower rates due to co-signer 2. **Without Co-Signer (You at 720 credit):** - Rates: 8.99% - 11.49% - Higher rates, but you build credit **Recommended Strategy:** **Phase 1: During School (2 years)** - Use your $20K savings for living expenses - Borrow $100K total for tuition - Federal Grad PLUS: $80,000 (8.05%, better protections) - Private with co-signer: $20,000 (6.49%, lower rate) **Phase 2: After Graduation** - Expected MBA salary: $120K+ - Refinance all loans at lower rate - Remove dad from co-signed loan - Typical refi rates: 5.5-7% with good income **Payment Projection:** $100K borrowed at 7.5% average: - 10-year term: $1,189/month - After MBA salary boost: ~12% of income - Very manageable with MBA earnings **Why Mix Federal & Private:** - Federal: Safety net (forbearance, income-driven plans) - Private: Lower rate with co-signer for portion - Flexibility to refinance later Keep $20K for living expenses rather than paying tuition directly - you'll need cash flow during school. Would you like me to help with applications? ``` *** ## Calculators in Action ### Comparing Loan Terms ```text theme={null} User: I'm trying to decide between a 15-year and 30-year mortgage on a $400,000 loan. How much would I save with the 15-year? Claude: [Uses calculate_mortgage_payment tool twice] Let me calculate both options: **30-Year Mortgage:** - Interest Rate: 6.5% - Monthly P&I: $2,528 - Total Interest: $509,808 - Total Paid: $909,808 **15-Year Mortgage:** - Interest Rate: 5.875% (lower rate) - Monthly P&I: $3,346 - Total Interest: $202,280 - Total Paid: $602,280 **Comparison:** - Monthly Difference: $818 more for 15-year - Interest Saved: $307,528 (!!!) - Equity Building: 2x faster with 15-year **Break-Even Analysis:** If you took the 30-year and invested the $818/month difference for 15 years at 7% return: - Investment Value: ~$220,000 - Still save ~$87,000+ with 15-year mortgage **Recommendation:** If you can afford the $3,346/month: → Take 15-year, save $307K If the payment is tight: → Take 30-year BUT make extra principal payments → You can pay it off in 15-20 years and save $200K+ → Keep flexibility for tough months The 15-year saves dramatically but requires commitment to higher payment. The 30-year with extra payments gives flexibility while still saving substantially. Which aligns better with your budget and goals? ``` *** ## Next Steps Connect Claude or ChatGPT Full tool documentation Programmatic integration Get help from our team # MCP Overview Source: https://docs.securelend.ai/mcp/overview Connect Claude and ChatGPT to SecureLend's marketplace and underwriting agents # Model Context Protocol (MCP) SecureLend provides two production MCP endpoints: | Endpoint | Purpose | | ---------------------------------- | ------------------------------------------------------------------------------------------ | | `https://mcp.securelend.ai/mcp` | Loan comparison marketplace — 22 tools for borrowers and lenders | | `https://agents.securelend.ai/mcp` | Agentic underwriting tools — pitch deck precheck, IC memo, document intelligence, and more | The marketplace is also **live in the ChatGPT App Store** — no manual setup required for borrower-facing workflows. ## What is Model Context Protocol? Model Context Protocol (MCP) is an open standard that allows AI assistants to connect to external tools and data sources. Our MCP server enables Claude and ChatGPT to: * Compare personal and business loans in real-time * Calculate mortgage and loan payments * Compare credit cards and banking products * Submit loan applications on behalf of users * Track application status ## Who is it for? **Borrowers:** * Compare 200+ lenders for personal, business, and equipment loans inside ChatGPT or Claude * Get instant loan comparisons through natural conversation — no need to visit multiple lender websites * Easiest path: open the [SecureLend ChatGPT app](https://chatgpt.com/apps/securelend/asdk_app_69513da1b04881919f74ae07c00a11f2#) directly **VC firms and lenders:** * Precheck pitch decks against your rubric (\$0.50/check, first 15/month free) * Generate IC memos, credit memos, and underwriting memos from a deal workspace * Connect via `agents.securelend.ai/mcp` — see [underwriting agents setup](/mcp/setup#underwriting-agents---manual-mcp-setup) **Developers:** * Build AI-powered financial applications using our TypeScript SDK * Integrate loan comparison or underwriting workflows programmatically * See [SDK documentation](/sdk/javascript) ## Quick Start Open the marketplace app — no setup needed Connect either endpoint in under a minute Integrate programmatically Browse all marketplace tools ## Available Tools ### Loan Comparison (6 tools) * **compare\_personal\_loans** - Personal loan offers based on credit and purpose * **compare\_business\_loans** - Business loans with revenue and industry matching * **compare\_car\_loans** - Auto loan rates for new and used vehicles * **compare\_student\_loans** - Student loan options by degree type * **compare\_personal\_mortgages** - Mortgage rates and terms for home purchases * **compare\_business\_mortgages** - Commercial mortgage options ### Banking & Credit Cards (5 tools) * **compare\_personal\_banking** - Checking and savings account comparison * **compare\_business\_banking** - Business banking products and services * **compare\_savings\_accounts** - High-yield savings account rates * **compare\_personal\_credit\_cards** - Personal credit cards by rewards type * **compare\_business\_credit\_cards** - Business credit card options ### Financial Calculators (3 tools) * **calculate\_loan\_payment** - Monthly payment calculator for any loan * **calculate\_mortgage\_payment** - PITI (Principal, Interest, Taxes, Insurance) calculator * **compare\_lease\_vs\_purchase** - Vehicle lease vs buy cost comparison ### Application Management (6 tools) * **get\_offer** - Submit application to a selected lender * **get\_multiple\_offers** - Submit application to multiple lenders simultaneously * **track\_offer\_status** - Check status of submitted applications * **display\_offer\_form** - Generate pre-filled application forms * **display\_upload\_documents\_form** - Upload required documents * **submit\_documents** - Submit supporting documentation [View full tool reference →](/mcp/tools) ## Example Use Cases ### Personal Finance > "Compare personal loans for \$25,000 to consolidate credit card debt. My credit score is 720." The AI assistant will use `compare_personal_loans` to fetch and compare offers from multiple lenders, presenting the best options with rates, terms, and monthly payments. ### Business Financing > "I need a $200,000 equipment loan for my restaurant. My business has $1.2M annual revenue and I've been operating for 3 years." The AI will use `compare_business_loans` with your business profile to find competitive offers, then can help you submit applications with `get_offer`. ### Home Buying > "What would my monthly payment be on a \$400,000 home with 20% down at 6.5% interest, including taxes and insurance?" The AI uses `calculate_mortgage_payment` to provide a complete PITI breakdown. ## Architecture ``` ┌──────────────────────────────────────┐ │ AI Assistant (Claude/ChatGPT) │ │ • Natural language interface │ │ • Context management │ └──────────────────────────────────────┘ ↓ MCP Protocol ┌──────────────────────────────────────┐ │ mcp.securelend.ai/mcp │ │ • Skybridge Framework │ │ • 20 financial tools │ │ • JSON Schema validation │ └──────────────────────────────────────┘ ↓ REST APIs ┌──────────────────────────────────────┐ │ SecureLend Backend Services │ │ • Lending Service │ │ • AI Service │ │ • Core Service │ │ • Integration with 200+ lenders │ └──────────────────────────────────────┘ ``` ## Security & Compliance SecureLend completed SOC 2 Type II certification, demonstrating enterprise-grade security controls. OpenAI-approved for the ChatGPT App Store. **Key Security Features:** * **No Authentication Required** - Comparison tools are read-only and public * **HTTPS Encryption** - All communications encrypted in transit * **Privacy-First Design** - Comparison data is not stored or logged * **Rate Limiting** - Protection against abuse * **Input Validation** - All parameters validated against JSON schemas **Data Handling:** * Comparison tool results are ephemeral (not stored) * Application submissions require explicit user consent * Personal information only transmitted when submitting applications * Full transparency about data usage at each step ## When NOT to Use MCP MCP is designed for: * ✅ Comparing financial products * ✅ Getting rate quotes and estimates * ✅ Calculating payments * ✅ Submitting applications with user consent MCP is NOT suitable for: * ❌ Executing financial transactions (use our platform directly) * ❌ Accessing existing account data (use REST API with authentication) * ❌ Automated trading or investment decisions * ❌ Regulatory compliance workflows (requires audit trails) For these use cases, see our [REST API documentation](/api/loans) or contact our enterprise team. ## Technical Details **Framework:** Skybridge (built on official MCP SDK)\ **Protocol Version:** MCP 1.0\ **Deployment:** AWS ECS Fargate (us-east-2)\ **Availability:** 99.9% uptime SLA\ **Rate Limits:** 100 requests/minute per IP (comparison tools) ## Getting Started Decide whether to use Claude Desktop, ChatGPT, or programmatic SDK integration Complete the 2-minute setup for your chosen platform Test with the example conversations provided Review the complete tool reference and capabilities Follow our setup guide to connect in under 2 minutes ## Support * **Documentation:** This site (docs.securelend.ai) * **Status Page:** [status.securelend.ai](https://status.securelend.ai) * **Developer Email:** [developers@securelend.ai](mailto:developers@securelend.ai) * **GitHub Issues:** [github.com/SecureLend/mcp-financial-services](https://github.com/SecureLend/mcp-financial-services) **Looking for B2B API integration?** See our [REST API documentation](/api/loans) for embedding SecureLend in your platform. # MCP Setup Source: https://docs.securelend.ai/mcp/setup Connect SecureLend to ChatGPT or Claude in under a minute # MCP Setup SecureLend exposes two MCP endpoints — one for the borrower marketplace (loan comparison) and one for the underwriting agents (pitch deck precheck, IC memo, etc.). Connect the right one for your use case. | Endpoint | What it does | Who it's for | | ---------------------------------- | --------------------------- | -------------------------------- | | `https://mcp.securelend.ai/mcp` | Loan comparison marketplace | Borrowers, lenders routing deals | | `https://agents.securelend.ai/mcp` | Agentic underwriting tools | VCs, lenders, analysts | App Store (marketplace) or manual MCP (agents) Connectors or Claude.ai Integrations View all marketplace tools Pitch deck precheck, IC memo, and more *** ## ChatGPT ### Marketplace — Live in the App Store (Recommended) SecureLend's loan comparison marketplace is published in the ChatGPT App Store. No setup required. Go to [chatgpt.com/apps/securelend](https://chatgpt.com/apps/securelend/asdk_app_69513da1b04881919f74ae07c00a11f2#) and click **Start chat**. Try: *"Compare business loans for \$200,000 with 720 credit score"* That's it. No developer mode, no MCP URL, no configuration needed for the marketplace. *** ### Underwriting Agents — Manual MCP Setup The underwriting agents (`agents.securelend.ai/mcp`) are not yet in the App Store. Connect them manually via ChatGPT's developer mode. ChatGPT Plus or Enterprise required for developer mode and MCP server access. Go to **Settings → Apps** and toggle **Developer mode** on. Click **Add app** and paste: ``` https://agents.securelend.ai/mcp ``` Name it *SecureLend Agents*. Open a new chat, click **+**, select **SecureLend Agents**, and say: *"Precheck this deck"* or *"Draft an IC memo"*. ChatGPT renders the underwriting agent results with interactive UI widgets — the fit ring, criteria breakdown, strengths/weaknesses, and the "Promote to underwriting case" button. #### Example queries for the agents ```text theme={null} Precheck this pitch deck against our Series A rubric. ``` ```text theme={null} Run quantitative analysis on this deal — domain is equity_investment. ``` ```text theme={null} Draft an IC memo from workspace ws_abc123. ``` *** ## Claude ### Claude.ai — Integrations (Recommended) In Claude.ai, go to **Settings → Integrations** and click **Add integration**. For the marketplace: ``` https://mcp.securelend.ai/mcp ``` For the underwriting agents: ``` https://agents.securelend.ai/mcp ``` Give it a name and click **Save**. Start a new chat. The SecureLend tools are available immediately — no extension file needed. SecureLend tools are now available in Claude.ai. Functionality is identical to ChatGPT; ChatGPT renders richer UI widgets for the underwriting agents. *** ### Claude Desktop — Manual Configuration In Claude Desktop, go to **Settings → Connectors → Add MCP server**. For the marketplace: ``` https://mcp.securelend.ai/mcp ``` For the underwriting agents: ``` https://agents.securelend.ai/mcp ``` Restart Claude Desktop. Open a new conversation and ask: ```text theme={null} List all SecureLend tools ``` Find your Claude Desktop configuration file: ```bash theme={null} ~/Library/Application Support/Claude/claude_desktop_config.json ``` ``` %APPDATA%\Claude\claude_desktop_config.json ``` ```bash theme={null} ~/.config/Claude/claude_desktop_config.json ``` Add to your `mcpServers` section: ```json theme={null} { "mcpServers": { "securelend": { "url": "https://mcp.securelend.ai/mcp" }, "securelend-agents": { "url": "https://agents.securelend.ai/mcp" } } } ``` Restart Claude Desktop after saving. *** ## Which endpoint do I use? | I want to… | Use | | --------------------------------------------------- | ----------------------------------------------------------- | | Compare loans, get rates, pre-qualify as a borrower | `mcp.securelend.ai/mcp` — or open the ChatGPT App Store app | | Precheck a pitch deck against my rubric | `agents.securelend.ai/mcp` | | Generate an IC memo or credit memo | `agents.securelend.ai/mcp` | | Run entity compliance / sanctions screening | `agents.securelend.ai/mcp` | | Build a custom lending workflow via SDK | See [TypeScript SDK](/sdk/javascript) | *** ## Verification After setup, confirm tools are loading: ```text theme={null} Compare business loans for $200,000 for working capital. My business has $800K annual revenue and a 720 credit score. ``` **Expected:** AI uses `compare_business_loans` and returns loan offers. ```text theme={null} List all tools available in SecureLend Agents. ``` **Expected:** AI lists `pitch_deck_precheck`, `document_intelligence_agent`, `quantitative_analysis_agent`, `professional_memo_agent`, and others. *** ## Troubleshooting ### Claude 1. Go to **Settings → Integrations** and confirm the URL is saved correctly 2. Start a **new** conversation — integrations only load in new chats 3. Check [status.securelend.ai](https://status.securelend.ai) for service status 1. Confirm the URL is entered correctly in **Settings → Connectors** 2. Quit Claude Desktop completely and reopen it 3. Test the URL directly: open `https://mcp.securelend.ai/mcp` in a browser 4. Check [status.securelend.ai](https://status.securelend.ai) 1. Check parameter requirements in [Tool Reference](/mcp/tools) 2. Wait 60 seconds if rate limited (100 requests/minute) 3. Contact [support@securelend.ai](mailto:support@securelend.ai) with the specific error message ### ChatGPT Go directly to: [chatgpt.com/apps/securelend](https://chatgpt.com/apps/securelend/asdk_app_69513da1b04881919f74ae07c00a11f2#) Developer mode requires ChatGPT Plus or Enterprise. Upgrade your plan, or use Claude.ai (free tier supports integrations). 1. Confirm the URL is `https://agents.securelend.ai/mcp` (not the marketplace URL) 2. Start a new chat and click **+** to select the server 3. Ask "list all tools" to verify the connection ### Wrong server URL The marketplace and agent endpoints are different: * **Marketplace:** `https://mcp.securelend.ai/mcp` * **Agents:** `https://agents.securelend.ai/mcp` Using the marketplace URL for underwriting agents (or vice versa) will give you the wrong set of tools. *** ## Next Steps All marketplace tools with parameters See tools in action Pitch deck precheck, IC memo, and more [developers@securelend.ai](mailto:developers@securelend.ai) # MCP Tools Reference Source: https://docs.securelend.ai/mcp/tools Complete reference for all 20 SecureLend MCP tools # MCP Tools Reference SecureLend provides 20 tools through Model Context Protocol for financial product comparison and application management. **Server URL:** `https://mcp.securelend.ai/mcp` All comparison tools are read-only and require no authentication. Application submission tools require user consent. *** ## Loan Comparison Tools ### compare\_personal\_loans Compare personal loan offers based on amount, credit score, and purpose. Desired loan amount in USD. Range: $1,000 - $100,000 Example: `25000` for \$25,000 Purpose of the loan Options: - `debt_consolidation` - Consolidate credit card or other debt - `home_improvement` - Home repairs or renovations - `major_purchase` - Large purchases (appliances, furniture, etc.) - `medical` - Medical expenses - `vacation` - Travel and vacation expenses - `other` - Other purposes Applicant's credit score. Range: 300-850 Example: `720` Employment status Options: `employed`, `self_employed`, `retired`, `unemployed` Gross monthly income in USD Example: `5000` State of residence (2-letter code) Example: `CA`, `NY`, `TX` **Example Query:** ``` Compare personal loans for $25,000 for debt consolidation with a 720 credit score in California. ``` **Response:** Array of loan offers with interest rates, monthly payments, terms, and lender details. *** ### compare\_business\_loans Compare business loan offers based on amount, revenue, and industry. Desired loan amount in USD. Minimum: $1,000 Example: `200000` for $200,000 Reason for the loan Examples: `working capital`, `equipment`, `expansion`, `inventory`, `real estate` Business's gross annual revenue in USD Example: `1200000` for \$1.2M Industry the business operates in Examples: `technology`, `retail`, `restaurant`, `construction`, `healthcare` State where business is located (2-letter code) Business owner's personal credit score (300-850) **Example Query:** ``` I need a $200,000 business loan for equipment. My business has $1.2M annual revenue in the technology industry. ``` **Response:** Business loan offers with rates, terms, approval likelihood, and requirements. *** ### compare\_car\_loans Compare auto loan rates for new and used vehicles. Desired auto loan amount. Range: $1,000 - $100,000 Whether the vehicle is new or used - `true` - New vehicle - `false` - Used vehicle Applicant's credit score (300-850) State of residence (2-letter code) **Example Query:** ``` Compare auto loans for a $35,000 new car with a 750 credit score. ``` *** ### compare\_student\_loans Compare student loan options by degree type and amount. Total loan amount needed. Range: $1,000 - $250,000 Type of degree program Options: `undergraduate`, `graduate`, `mba`, `medical`, `law` Student's credit score (300-850) Co-signer's credit score, if applicable (300-850) State of residence (2-letter code) **Example Query:** ``` Compare student loans for $50,000 for an MBA program with a 680 credit score and a co-signer with 750 credit. ``` *** ### compare\_personal\_mortgages Compare mortgage rates and terms for home purchases. Desired mortgage amount. Range: $50,000 - $2,000,000 Type of mortgage Options: `conventional`, `fha`, `va`, `jumbo`, `refinance` Purchase price of the home. Range: $50,000 - $5,000,000 Down payment amount in USD Applicant's credit score. Range: 500-850 Intended use of property Options: `primary`, `secondary`, `investment` State where property is located **Example Query:** ``` Compare conventional mortgages for a $400,000 home with 20% down and a 720 credit score in California. ``` *** ### compare\_business\_mortgages Compare commercial mortgage options for business properties. Desired commercial mortgage amount Type of commercial mortgage Options: `conventional`, `fha`, `va`, `jumbo`, `refinance` Purchase price of commercial property Down payment amount Business owner's credit score (500-850) Property type Options: `primary`, `secondary`, `investment` State where property is located *** ## Banking & Credit Card Tools ### compare\_personal\_banking Compare checking and savings account options. Desired account features Examples: `no_monthly_fees`, `high_interest`, `mobile_deposit`, `atm_access` **Example Query:** ``` Compare personal checking accounts with no monthly fees and mobile deposit. ``` *** ### compare\_business\_banking Compare business checking and banking services. Business industry Estimated number of monthly transactions **Example Query:** ``` Compare business checking accounts for a retail business with about 200 transactions per month. ``` *** ### compare\_savings\_accounts Compare high-yield savings account rates. Initial deposit amount in USD **Example Query:** ``` Compare high-yield savings accounts with a $10,000 initial deposit. ``` *** ### compare\_personal\_credit\_cards Compare personal credit card offers by rewards type. Applicant's credit score (300-850) Preferred rewards type Options: `cash_back`, `travel`, `points` **Example Query:** ``` Compare cash back credit cards for someone with a 750 credit score. ``` *** ### compare\_business\_credit\_cards Compare business credit card options. Applicant's credit score (300-850) Business annual revenue in USD How long the business has been operating **Example Query:** ``` Compare business credit cards for a company with $1M revenue and 3 years in business. ``` *** ## Calculator Tools ### calculate\_loan\_payment Calculate monthly payment for any loan. Total loan amount in USD Annual interest rate as percentage (e.g., `5` for 5%) Loan duration in months **Example Query:** ``` Calculate monthly payment for $200,000 at 7.5% APR over 60 months. ``` **Response:** * Monthly payment amount * Total interest paid * Total amount paid * Amortization details *** ### calculate\_mortgage\_payment Calculate PITI mortgage payment (Principal, Interest, Taxes, Insurance). Total property value in USD Down payment amount in USD Annual interest rate (e.g., `6.5` for 6.5%) Loan term in years (typically 15 or 30) Annual property tax rate as percentage (e.g., `1.2` for 1.2%) Annual home insurance cost in USD **Example Query:** ``` Calculate mortgage payment for $400,000 home with $80,000 down, 6.5% interest, 30 years, 1.2% property tax, and $1,500 annual insurance. ``` **Response:** * Monthly principal & interest * Monthly property taxes * Monthly insurance * Total monthly PITI payment * Total interest over loan term *** ### compare\_lease\_vs\_purchase Compare total costs of leasing vs buying a vehicle. Total purchase price of vehicle Down payment for purchase Annual interest rate for purchase loan Loan term in months for purchase Monthly lease payment amount Lease term in months Money factor for lease (similar to interest rate) Estimated residual value as percentage of MSRP (0-100) Sales tax rate as percentage How long you plan to keep the vehicle Lease acquisition fee (default: 0) Lease security deposit (default: 0) **Example Query:** ``` Compare leasing vs buying a $35,000 car. Lease is $450/month for 36 months. Purchase with $5,000 down at 6% for 60 months. I plan to keep it for 5 years. ``` **Response:** * Total cost of leasing * Total cost of purchasing * Cost difference * Recommendation based on ownership period *** ## Application Management Tools These tools handle sensitive user data and require explicit user consent before execution. ### get\_offer Submit loan application to a selected lender. Applicant personal details Properties: - `firstName` (required) - First name - `lastName` (required) - Last name - `email` (required) - Email address - `phone` (optional) - Phone number Original loan search parameters Type of financial product Options: `INSTALLMENT_LOAN`, `MORTGAGE`, `AUTO_LOAN`, `STUDENT_LOAN`, `BUSINESS_LOAN`, `PERSONAL_CREDIT_CARD`, `BUSINESS_CREDIT_CARD` Selected lender Properties: - `providerId` (required) - Lender ID from comparison results - `providerName` (required) - Lender name **Example Usage:** ``` User confirms they want to apply to "ABC Business Capital" after seeing comparison results. The AI collects required personal information and submits the application. ``` *** ### get\_multiple\_offers Submit application to multiple lenders simultaneously. Applicant personal details (same as get\_offer) Original loan search parameters Type of financial product List of selected lenders (minimum 1) Each provider object requires: - `providerId` - `providerName` *** ### track\_offer\_status Check status of submitted applications. Unique application ID to track Applicant's email to find all applications **Example Query:** ``` Check the status of my loan application for john@example.com ``` **Response:** * Application status (pending, approved, denied, etc.) * Last update timestamp * Next steps * Contact information *** ### display\_offer\_form Generate pre-filled application form for user review. Specific offer ID to pre-select Session ID from previous search **Usage:** Retrieves cached offer details to display in a form format. *** ### display\_upload\_documents\_form Present interface for uploading required documents. Application ID to associate documents with **Usage:** Shows document upload interface for bank statements, tax returns, ID, etc. *** ### submit\_documents Generate secure upload URL for application documents. Application ID Category of document Options: - `bank-statement` - `tax-return` - `identity-document` - `proof-of-income` - `business-license` - `financial-statement` - And 15+ other types Original filename **Response:** Pre-signed URL for secure file upload *** ## Rate Limits **Comparison Tools:** 100 requests per minute per IP address **Application Tools:** 10 requests per minute per email address Rate limits are designed to prevent abuse while allowing normal usage patterns. *** ## Error Handling All tools return standard error responses: ```json theme={null} { "error": { "code": "INVALID_PARAMETER", "message": "Loan amount must be between $1,000 and $100,000", "details": { "parameter": "loanAmount", "value": 500, "constraint": "minimum: 1000" } } } ``` **Common Error Codes:** * `INVALID_PARAMETER` - Parameter validation failed * `RATE_LIMIT_EXCEEDED` - Too many requests * `SERVICE_UNAVAILABLE` - Temporary service issue * `PROVIDER_ERROR` - Lender integration error *** ## JSON Schemas Complete JSON schemas for all tools are available in the [mcp-financial-services repository](https://github.com/SecureLend/mcp-financial-services/tree/main/schemas). *** ## Need Help? Connect Claude or ChatGPT See tools in action Programmatic integration Email [developers@securelend.ai](mailto:developers@securelend.ai) # Concepts Source: https://docs.securelend.ai/platform/concepts Coming soon. # Environments Source: https://docs.securelend.ai/platform/environments > This documentation is available to SecureLend customers and partners. # Platform Overview Source: https://docs.securelend.ai/platform/overview This document provides a high-level overview of the SecureLend platform architecture and core principles. ## High-Level Flow 1. **Authentication**: Your application authenticates with our API using a secure key. 2. **Request**: You send a request to find loan offers, providing business and loan criteria. 3. **Matching**: Our platform matches the request with offers from our network of lenders. 4. **Response**: We return a list of eligible offers to your application. 5. **Application**: You can then submit a formal application for a chosen offer. ## Sandbox vs. Production * **Sandbox**: A complete testing environment that mirrors production. Use it for development and integration testing. All data is synthetic. * **Production**: The live environment for real transactions. Access is granted after a successful integration review. ## Trust & Guarantees SecureLend is committed to security and reliability. Our platform is built with industry-best practices for data encryption, access control, and uptime. All data is encrypted in transit and at rest. # Security Source: https://docs.securelend.ai/platform/security > This documentation is available to SecureLend customers and partners. # Quickstart Source: https://docs.securelend.ai/quickstart This guide will get you up and running with the SecureLend SDK. ## Installation First, install the SDK using your favorite package manager. ```bash theme={null} npm install @securelend/sdk ``` ## Example: Get Loan Offers Here's a runnable example to fetch loan offers. Make sure to replace `'YOUR_API_KEY'` with your actual key. ```javascript theme={null} import { SecureLend } from '@securelend/sdk'; const client = new SecureLend({ apiKey: 'YOUR_API_KEY', }); async function getOffers() { try { const offers = await client.getLoanOffers({ amount: 50000, term: 12, // in months businessType: 'SaaS', }); console.log('Successfully fetched offers:', offers); return offers; } catch (error) { console.error('Failed to fetch offers:', error); } } getOffers(); ``` ## Expected Output If successful, you will see a list of loan offers logged to your console. ```json theme={null} Successfully fetched offers: [ { "lender": "Lender A", "amount": 50000, "interestRate": 0.05, "term": 12 }, { "lender": "Lender B", "amount": 50000, "interestRate": 0.055, "term": 12 } ] ``` # SDK Examples Source: https://docs.securelend.ai/sdk/examples Practical examples and code patterns for @securelend/sdk # SDK Examples Real-world examples showing how to use the SecureLend SDK in different scenarios. *** ## Basic Examples ### Compare Business Loans ```typescript theme={null} import { SecureLend } from "@securelend/sdk"; async function compareBusinessLoans() { const securelend = new SecureLend(); const result = await securelend.compareBusinessLoans({ loanAmount: 200000, purpose: "equipment", annualRevenue: 1200000, industry: "technology", creditScore: 720, state: "CA", }); console.log(`Found ${result.offers.length} loan offers`); // Display top 3 offers result.offers.slice(0, 3).forEach((offer, index) => { console.log(`\n${index + 1}. ${offer.lenderName}`); console.log(` Rate: ${offer.interestRate}% APR`); console.log(` Monthly: $${offer.monthlyPayment.toLocaleString()}`); console.log(` Term: ${offer.termMonths} months`); console.log(` Approval: ${offer.approvalLikelihood}%`); }); return result.offers[0]; // Best offer } compareBusinessLoans(); ``` ### Calculate Mortgage Payment ```typescript theme={null} import { SecureLend } from "@securelend/sdk"; async function calculateMonthlyPayment() { const securelend = new SecureLend(); const result = await securelend.calculateMortgagePayment({ propertyValue: 400000, downPayment: 80000, // 20% down interestRate: 6.5, loanTermInYears: 30, propertyTaxRate: 1.2, homeInsurance: 1500, }); console.log("Monthly Payment Breakdown:"); console.log( `Principal & Interest: $${result.principalAndInterest.toLocaleString()}`, ); console.log(`Property Taxes: $${result.propertyTaxes.toLocaleString()}`); console.log(`Insurance: $${result.insurance.toLocaleString()}`); console.log(`\nTotal PITI: $${result.monthlyPayment.toLocaleString()}`); console.log( `\nTotal Interest Over Life: $${result.totalInterest.toLocaleString()}`, ); return result; } calculateMonthlyPayment(); ``` ### Compare Personal Loans ```typescript theme={null} import { SecureLend } from "@securelend/sdk"; async function findBestPersonalLoan() { const securelend = new SecureLend(); const result = await securelend.comparePersonalLoans({ loanAmount: 25000, purpose: "debt_consolidation", creditScore: 720, employmentStatus: "employed", monthlyIncome: 5000, state: "CA", }); // Sort by interest rate const sortedOffers = result.offers.sort( (a, b) => a.interestRate - b.interestRate, ); // Best offer const best = sortedOffers[0]; console.log(`Best Rate: ${best.interestRate}% from ${best.lenderName}`); console.log(`Monthly Payment: $${best.monthlyPayment}`); console.log( `Total Interest: $${(best.monthlyPayment * best.termMonths - 25000).toFixed(2)}`, ); return best; } findBestPersonalLoan(); ``` *** ## Web Application Examples ### Next.js API Route Create a serverless API endpoint for loan comparison: ```typescript theme={null} // app/api/loans/compare/route.ts import { SecureLend } from "@securelend/sdk"; import { NextResponse } from "next/server"; export async function POST(request: Request) { try { const body = await request.json(); // Validate input if (!body.loanAmount || !body.purpose) { return NextResponse.json( { error: "Missing required fields" }, { status: 400 }, ); } const securelend = new SecureLend(); const result = await securelend.compareBusinessLoans({ loanAmount: body.loanAmount, purpose: body.purpose, annualRevenue: body.annualRevenue, industry: body.industry, creditScore: body.creditScore, state: body.state, }); return NextResponse.json({ success: true, offers: result.offers, count: result.offers.length, }); } catch (error) { console.error("Loan comparison failed:", error); return NextResponse.json( { error: "Failed to compare loans" }, { status: 500 }, ); } } ``` ### Next.js Server Component ```typescript theme={null} // app/loans/[amount]/page.tsx import { SecureLend } from '@securelend/sdk'; interface PageProps { params: { amount: string; }; searchParams: { purpose?: string; }; } export default async function LoansPage({ params, searchParams }: PageProps) { const securelend = new SecureLend(); const loanAmount = parseInt(params.amount); const purpose = searchParams.purpose || 'working_capital'; const result = await securelend.compareBusinessLoans({ loanAmount, purpose }); return (

{result.offers.length} Loan Offers for ${loanAmount.toLocaleString()}

{result.offers.map(offer => (

{offer.lenderName}

{offer.interestRate}% APR

${offer.monthlyPayment.toLocaleString()}/month for {offer.termMonths} months

{offer.approvalLikelihood && (

{offer.approvalLikelihood}% approval likelihood

)}
))}
); } ``` ### React Client Component ```typescript theme={null} // components/LoanComparison.tsx 'use client'; import { useState } from 'react'; import { SecureLend } from '@securelend/sdk'; interface LoanOffer { offerId: string; lenderName: string; interestRate: number; monthlyPayment: number; termMonths: number; } export default function LoanComparison() { const [amount, setAmount] = useState(200000); const [purpose, setPurpose] = useState('equipment'); const [offers, setOffers] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const compareLoans = async () => { setLoading(true); setError(null); try { const securelend = new SecureLend(); const result = await securelend.compareBusinessLoans({ loanAmount: amount, purpose }); setOffers(result.offers); } catch (err) { setError('Failed to compare loans. Please try again.'); console.error(err); } finally { setLoading(false); } }; return (

Compare Business Loans

setAmount(Number(e.target.value))} className="border rounded px-4 py-2 w-full" />
{error && (
{error}
)} {offers.length > 0 && (

Found {offers.length} Offers

{offers.map(offer => (

{offer.lenderName}

{offer.interestRate}% APR

${offer.monthlyPayment.toLocaleString()}/month

))}
)}
); } ``` *** ## Advanced Patterns ### Comparison Across Multiple Loan Types ```typescript theme={null} import { SecureLend } from "@securelend/sdk"; async function compareAllFinancingOptions() { const securelend = new SecureLend(); // Compare multiple product types in parallel const [loans, creditCards, banking] = await Promise.all([ securelend.compareBusinessLoans({ loanAmount: 100000, purpose: "working_capital", annualRevenue: 500000, }), securelend.compareBusinessCreditCards({ annualRevenue: 500000, creditScore: 720, }), securelend.compareBusinessBanking({ monthlyTransactions: 200, }), ]); return { loans: loans.offers, creditCards: creditCards.offers, banking: banking.offers, }; } // Usage const options = await compareAllFinancingOptions(); console.log( `Found ${options.loans.length} loans, ${options.creditCards.length} cards`, ); ``` ### Rate Monitoring Service ```typescript theme={null} import { SecureLend } from "@securelend/sdk"; class RateMonitor { private securelend: SecureLend; private targetRate: number; private checkInterval: number; constructor(targetRate: number, checkIntervalMs: number = 3600000) { this.securelend = new SecureLend(); this.targetRate = targetRate; this.checkInterval = checkIntervalMs; } async checkRates() { const result = await this.securelend.comparePersonalLoans({ loanAmount: 25000, purpose: "debt_consolidation", creditScore: 720, }); const bestRate = Math.min(...result.offers.map((o) => o.interestRate)); if (bestRate <= this.targetRate) { await this.sendAlert({ rate: bestRate, offers: result.offers.filter((o) => o.interestRate === bestRate), }); } return bestRate; } start() { console.log(`Starting rate monitor (target: ${this.targetRate}%)`); // Check immediately this.checkRates(); // Then check periodically setInterval(() => this.checkRates(), this.checkInterval); } private async sendAlert(data: { rate: number; offers: any[] }) { console.log(`🎉 Target rate reached: ${data.rate}%`); console.log( `Available from: ${data.offers.map((o) => o.lenderName).join(", ")}`, ); // Send email, Slack notification, etc. } } // Monitor for rates under 9% const monitor = new RateMonitor(9.0, 3600000); // Check every hour monitor.start(); ``` ### Batch Processing ```typescript theme={null} import { SecureLend } from "@securelend/sdk"; interface BusinessProfile { id: string; name: string; revenue: number; industry: string; loanAmount: number; } async function batchProcessLoans(businesses: BusinessProfile[]) { const securelend = new SecureLend(); const results = await Promise.allSettled( businesses.map((business) => securelend .compareBusinessLoans({ loanAmount: business.loanAmount, purpose: "working_capital", annualRevenue: business.revenue, industry: business.industry, }) .then((result) => ({ businessId: business.id, businessName: business.name, success: true, offers: result.offers, })) .catch((error) => ({ businessId: business.id, businessName: business.name, success: false, error: error.message, })), ), ); const successful = results.filter((r) => r.status === "fulfilled"); const failed = results.filter((r) => r.status === "rejected"); console.log(`Processed ${businesses.length} businesses`); console.log(`Success: ${successful.length}, Failed: ${failed.length}`); return results.map((r) => (r.status === "fulfilled" ? r.value : null)); } // Usage const businesses = [ { id: "1", name: "Tech Co", revenue: 1000000, industry: "technology", loanAmount: 200000, }, { id: "2", name: "Retail Co", revenue: 500000, industry: "retail", loanAmount: 100000, }, { id: "3", name: "Restaurant", revenue: 300000, industry: "restaurant", loanAmount: 50000, }, ]; const results = await batchProcessLoans(businesses); ``` ### Caching Results ```typescript theme={null} import { SecureLend } from "@securelend/sdk"; class LoanComparisonCache { private cache: Map; private ttl: number; // Time to live in milliseconds private securelend: SecureLend; constructor(ttlMinutes: number = 15) { this.cache = new Map(); this.ttl = ttlMinutes * 60 * 1000; this.securelend = new SecureLend(); } private getCacheKey(params: any): string { return JSON.stringify(params); } private isValid(timestamp: number): boolean { return Date.now() - timestamp < this.ttl; } async compareLoans(params: { loanAmount: number; purpose: string; annualRevenue?: number; }) { const key = this.getCacheKey(params); const cached = this.cache.get(key); // Return cached if valid if (cached && this.isValid(cached.timestamp)) { console.log("Cache hit"); return cached.data; } // Fetch fresh data console.log("Cache miss - fetching fresh data"); const result = await this.securelend.compareBusinessLoans(params); // Cache the result this.cache.set(key, { data: result, timestamp: Date.now(), }); return result; } clearCache() { this.cache.clear(); } } // Usage const cache = new LoanComparisonCache(15); // 15 minute cache const result1 = await cache.compareLoans({ loanAmount: 200000, purpose: "equipment", }); // Fetches from API const result2 = await cache.compareLoans({ loanAmount: 200000, purpose: "equipment", }); // Returns from cache ``` *** ## Error Handling Patterns ### Retry with Exponential Backoff ```typescript theme={null} import { SecureLend, SecureLendError } from "@securelend/sdk"; async function compareLoansWithRetry(params: any, maxRetries: number = 3) { const securelend = new SecureLend(); let lastError: Error; for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await securelend.compareBusinessLoans(params); } catch (error) { lastError = error as Error; if (error instanceof SecureLendError) { // Don't retry on validation errors if (error.code === "INVALID_PARAMETER") { throw error; } // Retry on rate limits or service issues if ( error.code === "RATE_LIMIT_EXCEEDED" || error.code === "SERVICE_UNAVAILABLE" ) { const delay = Math.pow(2, attempt) * 1000; // Exponential backoff console.log(`Retry attempt ${attempt + 1} after ${delay}ms`); await new Promise((resolve) => setTimeout(resolve, delay)); continue; } } throw error; } } throw new Error(`Failed after ${maxRetries} retries: ${lastError.message}`); } // Usage try { const result = await compareLoansWithRetry({ loanAmount: 200000, purpose: "equipment", }); } catch (error) { console.error("All retries failed:", error); } ``` ### Graceful Degradation ```typescript theme={null} import { SecureLend, SecureLendError } from "@securelend/sdk"; async function getLoansWithFallback(params: any) { const securelend = new SecureLend(); try { return await securelend.compareBusinessLoans(params); } catch (error) { console.error("Primary API failed:", error); if (error instanceof SecureLendError) { // Return cached results or estimated ranges return { offers: [], error: error.message, fallback: true, estimatedRange: { minRate: 7.5, maxRate: 12.0, message: "Showing estimated rates. Try again later for real-time offers.", }, }; } throw error; } } ``` ### Validation Before API Call ```typescript theme={null} import { SecureLend } from "@securelend/sdk"; interface ValidationError { field: string; message: string; } function validateBusinessLoanRequest(params: any): ValidationError[] { const errors: ValidationError[] = []; if (!params.loanAmount) { errors.push({ field: "loanAmount", message: "Loan amount is required" }); } else if (params.loanAmount < 1000) { errors.push({ field: "loanAmount", message: "Minimum loan amount is $1,000", }); } else if (params.loanAmount > 5000000) { errors.push({ field: "loanAmount", message: "Maximum loan amount is $5,000,000", }); } if (!params.purpose) { errors.push({ field: "purpose", message: "Loan purpose is required" }); } if ( params.creditScore && (params.creditScore < 300 || params.creditScore > 850) ) { errors.push({ field: "creditScore", message: "Credit score must be between 300-850", }); } return errors; } async function compareLoansWithValidation(params: any) { // Validate first const errors = validateBusinessLoanRequest(params); if (errors.length > 0) { throw new Error(`Validation failed: ${JSON.stringify(errors)}`); } // Then call API const securelend = new SecureLend(); return await securelend.compareBusinessLoans(params); } ``` *** ## Testing Examples ### Unit Tests with Jest ```typescript theme={null} // __tests__/loans.test.ts import { SecureLend } from "@securelend/sdk"; describe("SecureLend SDK", () => { let securelend: SecureLend; beforeEach(() => { securelend = new SecureLend(); }); describe("compareBusinessLoans", () => { it("should return loan offers", async () => { const result = await securelend.compareBusinessLoans({ loanAmount: 200000, purpose: "equipment", }); expect(result).toHaveProperty("offers"); expect(Array.isArray(result.offers)).toBe(true); expect(result.offers.length).toBeGreaterThan(0); }); it("should include required offer fields", async () => { const result = await securelend.compareBusinessLoans({ loanAmount: 200000, purpose: "equipment", }); const offer = result.offers[0]; expect(offer).toHaveProperty("lenderName"); expect(offer).toHaveProperty("interestRate"); expect(offer).toHaveProperty("monthlyPayment"); expect(offer).toHaveProperty("termMonths"); }); it("should handle errors gracefully", async () => { await expect( securelend.compareBusinessLoans({ loanAmount: -1000, // Invalid amount purpose: "equipment", }), ).rejects.toThrow(); }); }); describe("calculateLoanPayment", () => { it("should calculate correct payment", async () => { const result = await securelend.calculateLoanPayment({ loanAmount: 100000, interestRate: 6.0, loanTermInMonths: 60, }); expect(result.monthlyPayment).toBeCloseTo(1933.28, 2); }); }); }); ``` ### Integration Tests ```typescript theme={null} // __tests__/integration.test.ts import { SecureLend } from "@securelend/sdk"; describe("SecureLend Integration", () => { it("should complete full loan comparison flow", async () => { const securelend = new SecureLend(); // 1. Compare loans const comparison = await securelend.compareBusinessLoans({ loanAmount: 200000, purpose: "equipment", annualRevenue: 1000000, }); expect(comparison.offers.length).toBeGreaterThan(0); // 2. Calculate payment for best offer const bestOffer = comparison.offers[0]; const payment = await securelend.calculateLoanPayment({ loanAmount: bestOffer.loanAmount, interestRate: bestOffer.interestRate, loanTermInMonths: bestOffer.termMonths, }); expect(payment.monthlyPayment).toBeCloseTo(bestOffer.monthlyPayment, 0); }); }); ``` *** ## Production Deployment ### Environment Configuration ```typescript theme={null} // lib/securelend.ts import { SecureLend } from "@securelend/sdk"; const getSecureLendClient = () => { const config = { serverUrl: process.env.SECURELEND_SERVER_URL || "https://mcp.securelend.ai/mcp", timeout: parseInt(process.env.SECURELEND_TIMEOUT || "10000"), retries: parseInt(process.env.SECURELEND_RETRIES || "2"), }; return new SecureLend(config); }; export default getSecureLendClient; ``` ### Logging and Monitoring ```typescript theme={null} import { SecureLend, SecureLendError } from "@securelend/sdk"; async function compareLoansWithLogging(params: any) { const securelend = new SecureLend(); const startTime = Date.now(); try { console.log("Starting loan comparison", { params }); const result = await securelend.compareBusinessLoans(params); const duration = Date.now() - startTime; console.log("Loan comparison successful", { duration, offerCount: result.offers.length, }); // Send metrics to monitoring service await trackMetric("loan_comparison_success", { duration, offerCount: result.offers.length, }); return result; } catch (error) { const duration = Date.now() - startTime; if (error instanceof SecureLendError) { console.error("Loan comparison failed", { code: error.code, message: error.message, duration, }); // Send error to monitoring await trackError("loan_comparison_error", { code: error.code, duration, }); } throw error; } } async function trackMetric(name: string, data: any) { // Send to your monitoring service (DataDog, New Relic, etc.) } async function trackError(name: string, data: any) { // Send to your error tracking service (Sentry, etc.) } ``` *** ## Performance Optimization ### Request Deduplication ```typescript theme={null} import { SecureLend } from "@securelend/sdk"; class LoanComparison { private securelend: SecureLend; private pendingRequests: Map>; constructor() { this.securelend = new SecureLend(); this.pendingRequests = new Map(); } async compare(params: any) { const key = JSON.stringify(params); // Return existing pending request if duplicate if (this.pendingRequests.has(key)) { console.log("Deduplicating request"); return this.pendingRequests.get(key); } // Create new request const promise = this.securelend.compareBusinessLoans(params).finally(() => { // Clean up when done this.pendingRequests.delete(key); }); this.pendingRequests.set(key, promise); return promise; } } const comparison = new LoanComparison(); // These will only make one API call const [result1, result2, result3] = await Promise.all([ comparison.compare({ loanAmount: 200000, purpose: "equipment" }), comparison.compare({ loanAmount: 200000, purpose: "equipment" }), comparison.compare({ loanAmount: 200000, purpose: "equipment" }), ]); ``` *** ## Next Steps Learn about SDK features Complete API documentation All 20 tools documented View source and contribute ## Need Help? * **Email:** [developers@securelend.ai](mailto:developers@securelend.ai) * **GitHub Issues:** [SecureLend/sdk/issues](https://github.com/SecureLend/sdk/issues) * **Documentation:** [docs.securelend.ai](https://docs.securelend.ai) * **Status:** [status.securelend.ai](https://status.securelend.ai) # JavaScript/TypeScript SDK Source: https://docs.securelend.ai/sdk/javascript Complete reference for @securelend/sdk # JavaScript/TypeScript SDK Complete reference for the SecureLend TypeScript/JavaScript SDK. *** ## Installation ```bash npm theme={null} npm install @securelend/sdk ``` ```bash pnpm theme={null} pnpm add @securelend/sdk ``` ```bash yarn theme={null} yarn add @securelend/sdk ``` *** ## Initialization ### Basic Setup ```typescript theme={null} import { SecureLend } from "@securelend/sdk"; // Connects to https://mcp.securelend.ai/mcp by default const securelend = new SecureLend(); ``` ### Custom Configuration ```typescript theme={null} import { SecureLend } from "@securelend/sdk"; const securelend = new SecureLend({ serverUrl: "https://custom-mcp-server.com/mcp", // Optional timeout: 30000, // 30 seconds, default: 10000 retries: 3, // Number of retries, default: 2 }); ``` Most users should use the default configuration. Custom server URLs are for advanced use cases only. *** ## TypeScript Support The SDK includes complete TypeScript definitions: ```typescript theme={null} import { SecureLend, BusinessLoanRequest, LoanComparisonResponse, LoanOffer, MortgageCalculationRequest, MortgagePaymentResponse, } from "@securelend/sdk"; // Type-safe requests const request: BusinessLoanRequest = { loanAmount: 200000, purpose: "equipment", annualRevenue: 1200000, }; // Type-safe responses const response: LoanComparisonResponse = await securelend.compareBusinessLoans(request); // Access typed properties const bestOffer: LoanOffer = response.offers[0]; console.log(bestOffer.interestRate); // Type: number console.log(bestOffer.lenderName); // Type: string ``` *** ## API Reference ### Loan Comparison Methods #### compareBusinessLoans() Compare business loan offers. ```typescript theme={null} const result = await securelend.compareBusinessLoans({ loanAmount: 200000, // Required: $1,000+ purpose: "equipment", // Required: string annualRevenue: 1200000, // Optional: business revenue industry: "technology", // Optional: business industry state: "CA", // Optional: 2-letter state code creditScore: 720, // Optional: 300-850 }); // Returns interface LoanComparisonResponse { offers: LoanOffer[]; sessionId: string; timestamp: string; } interface LoanOffer { offerId: string; lenderName: string; productName: string; interestRate: number; monthlyPayment: number; termMonths: number; loanAmount: number; approvalLikelihood?: number; originationFee?: number; prepaymentPenalty?: boolean; } ``` #### comparePersonalLoans() Compare personal loan offers. ```typescript theme={null} const result = await securelend.comparePersonalLoans({ loanAmount: 25000, // Required: $1,000-$100,000 purpose: "debt_consolidation", // Required: enum creditScore: 720, // Optional: 300-850 employmentStatus: "employed", // Optional: enum monthlyIncome: 5000, // Optional: USD state: "CA", // Optional: 2-letter code }); // Purpose options type LoanPurpose = | "debt_consolidation" | "home_improvement" | "major_purchase" | "medical" | "vacation" | "other"; // Employment status options type EmploymentStatus = "employed" | "self_employed" | "retired" | "unemployed"; ``` #### compareCarLoans() Compare auto loan rates. ```typescript theme={null} const result = await securelend.compareCarLoans({ loanAmount: 35000, // Required: $1,000-$100,000 isNew: true, // Required: new or used vehicle creditScore: 750, // Optional: 300-850 state: "CA", // Optional: 2-letter state code }); ``` #### compareStudentLoans() Compare student loan options. ```typescript theme={null} const result = await securelend.compareStudentLoans({ loanAmount: 50000, // Required: $1,000-$250,000 degreeType: "graduate", // Required: enum creditScore: 680, // Optional: 300-850 coSignerCreditScore: 750, // Optional: 300-850 state: "CA", // Optional: 2-letter code }); // Degree type options type DegreeType = "undergraduate" | "graduate" | "mba" | "medical" | "law"; ``` #### comparePersonalMortgages() Compare mortgage rates for home purchases. ```typescript theme={null} const result = await securelend.comparePersonalMortgages({ loanAmount: 320000, // Required: $50,000-$2,000,000 loanType: "conventional", // Required: enum homePrice: 400000, // Optional: property value downPayment: 80000, // Optional: down payment amount creditScore: 720, // Optional: 500-850 propertyType: "primary", // Optional: enum state: "CA", // Optional: 2-letter code }); // Loan type options type MortgageLoanType = "conventional" | "fha" | "va" | "jumbo" | "refinance"; // Property type options type PropertyType = "primary" | "secondary" | "investment"; ``` *** ### Calculator Methods #### calculateLoanPayment() Calculate monthly payment for any loan. ```typescript theme={null} const result = await securelend.calculateLoanPayment({ loanAmount: 200000, // Required: loan principal interestRate: 7.5, // Required: annual rate (e.g., 7.5 for 7.5%) loanTermInMonths: 60, // Required: term in months }); // Returns interface LoanCalculation { monthlyPayment: number; totalInterest: number; totalAmount: number; amortizationSchedule?: Array<{ month: number; payment: number; principal: number; interest: number; balance: number; }>; } ``` #### calculateMortgagePayment() Calculate PITI (Principal, Interest, Taxes, Insurance) mortgage payment. ```typescript theme={null} const result = await securelend.calculateMortgagePayment({ propertyValue: 400000, // Required: property value downPayment: 80000, // Required: down payment interestRate: 6.5, // Required: annual rate loanTermInYears: 30, // Required: term in years propertyTaxRate: 1.2, // Required: annual tax rate % homeInsurance: 1500, // Required: annual insurance cost }); // Returns interface MortgagePaymentResponse { monthlyPayment: number; // Total PITI payment principalAndInterest: number; // P&I portion propertyTaxes: number; // Monthly taxes insurance: number; // Monthly insurance loanAmount: number; // Calculated loan amount totalInterest: number; // Over life of loan } ``` #### compareLeaseVsPurchase() Compare total costs of leasing vs buying a vehicle. ```typescript theme={null} const result = await securelend.compareLeaseVsPurchase({ purchasePrice: 35000, // Required: vehicle price downPayment: 5000, // Required: purchase down payment interestRate: 6.0, // Required: purchase loan rate loanTermInMonths: 60, // Required: purchase term monthlyLeasePayment: 450, // Required: lease payment leaseTermInMonths: 36, // Required: lease term moneyFactor: 0.0025, // Required: lease money factor residualValuePercentage: 55, // Required: 0-100 salesTaxRate: 7.5, // Required: tax rate % expectedOwnershipInMonths: 60, // Required: how long keeping vehicle acquisitionFee: 595, // Optional: lease acquisition fee securityDeposit: 0, // Optional: lease security deposit }); // Returns interface LeaseVsPurchaseResponse { leaseTotalCost: number; purchaseTotalCost: number; costDifference: number; recommendation: "lease" | "purchase"; breakEvenMonth: number; } ``` *** ### Banking & Credit Card Methods #### comparePersonalBanking() Compare checking and savings accounts. ```typescript theme={null} const result = await securelend.comparePersonalBanking({ features: [ // Optional: desired features "no_monthly_fees", "high_interest", "mobile_deposit", "atm_access", ], }); ``` #### compareBusinessBanking() Compare business banking products. ```typescript theme={null} const result = await securelend.compareBusinessBanking({ industry: "technology", // Optional: business industry monthlyTransactions: 200, // Optional: estimated transactions }); ``` #### compareSavingsAccounts() Compare high-yield savings accounts. ```typescript theme={null} const result = await securelend.compareSavingsAccounts({ initialDeposit: 10000, // Optional: starting balance }); ``` #### comparePersonalCreditCards() Compare personal credit card offers. ```typescript theme={null} const result = await securelend.comparePersonalCreditCards({ creditScore: 750, // Optional: 300-850 rewardsType: "cash_back", // Optional: rewards preference }); // Rewards type options type RewardsType = "cash_back" | "travel" | "points"; ``` #### compareBusinessCreditCards() Compare business credit card options. ```typescript theme={null} const result = await securelend.compareBusinessCreditCards({ creditScore: 720, // Optional: 300-850 annualRevenue: 1000000, // Optional: business revenue businessAgeInYears: 3, // Optional: years in business }); ``` *** ### Application Management Methods Application methods handle sensitive user data. Always obtain explicit user consent before calling these methods. #### getOffer() Submit application to one selected lender. ```typescript theme={null} const result = await securelend.getOffer({ applicant: { firstName: "John", lastName: "Doe", email: "john@example.com", phone: "+1-555-0100", // Optional }, applicationData: { // Original loan search parameters loanAmount: 200000, purpose: "equipment", // ... other parameters }, productType: "BUSINESS_LOAN", // Enum: see below provider: { providerId: "provider-123", providerName: "ABC Business Capital", }, }); // Product type options type ProductType = | "INSTALLMENT_LOAN" | "LINE_OF_CREDIT" | "SHORT_TERM_CREDIT" | "BNPL" | "MORTGAGE" | "AUTO_LOAN" | "AUTO_REFINANCE" | "STUDENT_LOAN" | "STUDENT_LOAN_REFINANCE" | "BUSINESS_LOAN" | "BUSINESS_BANKING" | "BUSINESS_CREDIT_CARD" | "PERSONAL_BANKING" | "SAVINGS_ACCOUNT" | "PERSONAL_CREDIT_CARD"; ``` #### trackOfferStatus() Check status of submitted applications. ```typescript theme={null} // By application ID const status = await securelend.trackOfferStatus({ applicationId: "app-123", }); // Or by email (returns all applications) const statuses = await securelend.trackOfferStatus({ email: "john@example.com", }); ``` *** ## Error Handling The SDK throws typed errors for different failure scenarios: ```typescript theme={null} import { SecureLend, SecureLendError } from "@securelend/sdk"; const securelend = new SecureLend(); try { const loans = await securelend.compareBusinessLoans({ loanAmount: 200000, purpose: "equipment", }); console.log(`Found ${loans.offers.length} offers`); } catch (error) { if (error instanceof SecureLendError) { // Structured SecureLend error console.error("Error Code:", error.code); console.error("Message:", error.message); console.error("Details:", error.details); // Common error codes switch (error.code) { case "INVALID_PARAMETER": // Handle validation error break; case "RATE_LIMIT_EXCEEDED": // Handle rate limit break; case "SERVICE_UNAVAILABLE": // Handle service outage break; case "NETWORK_ERROR": // Handle network issues break; } } else { // Unexpected error console.error("Unexpected error:", error); } } ``` ### Error Types ```typescript theme={null} interface SecureLendError extends Error { code: ErrorCode; message: string; details?: Record; statusCode?: number; } type ErrorCode = | "INVALID_PARAMETER" | "RATE_LIMIT_EXCEEDED" | "SERVICE_UNAVAILABLE" | "NETWORK_ERROR" | "TIMEOUT" | "PROVIDER_ERROR" | "AUTHENTICATION_ERROR"; ``` *** ## Platform-Specific Usage ### Node.js Works natively in Node.js 16+: ```typescript theme={null} import { SecureLend } from "@securelend/sdk"; const securelend = new SecureLend(); const loans = await securelend.compareBusinessLoans({ loanAmount: 200000, purpose: "equipment", }); ``` ### Next.js #### API Routes ```typescript theme={null} // app/api/compare-loans/route.ts import { SecureLend } from "@securelend/sdk"; import { NextResponse } from "next/server"; export async function POST(request: Request) { const body = await request.json(); const securelend = new SecureLend(); try { const result = await securelend.compareBusinessLoans({ loanAmount: body.amount, purpose: body.purpose, annualRevenue: body.revenue, }); return NextResponse.json(result); } catch (error) { console.error("Loan comparison failed:", error); return NextResponse.json( { error: "Failed to compare loans" }, { status: 500 }, ); } } ``` #### Server Components ```typescript theme={null} // app/loans/page.tsx import { SecureLend } from '@securelend/sdk'; export default async function LoansPage() { const securelend = new SecureLend(); const loans = await securelend.compareBusinessLoans({ loanAmount: 200000, purpose: 'equipment' }); return (

Loan Offers

{loans.offers.map(offer => (

{offer.lenderName}

{offer.interestRate}% APR

))}
); } ``` ### React (Client-Side) ```typescript theme={null} import { useState, useEffect } from 'react'; import { SecureLend } from '@securelend/sdk'; function LoanComparison() { const [offers, setOffers] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { const securelend = new SecureLend(); securelend.compareBusinessLoans({ loanAmount: 200000, purpose: 'equipment' }) .then(result => { setOffers(result.offers); setLoading(false); }) .catch(console.error); }, []); if (loading) return
Loading...
; return (
{offers.map(offer => ( ))}
); } ``` ### Edge Runtime (Vercel, Cloudflare Workers) The SDK works in edge runtimes: ```typescript theme={null} // Edge API route import { SecureLend } from "@securelend/sdk"; export const config = { runtime: "edge", }; export default async function handler(req: Request) { const securelend = new SecureLend(); const loans = await securelend.compareBusinessLoans({ loanAmount: 200000, purpose: "equipment", }); return new Response(JSON.stringify(loans), { headers: { "Content-Type": "application/json" }, }); } ``` *** ## Rate Limits **Comparison Tools:** 100 requests per minute per IP\ **Application Tools:** 10 requests per minute per email The SDK automatically handles rate limiting with exponential backoff. ```typescript theme={null} const securelend = new SecureLend({ retries: 3, // Retry up to 3 times on rate limit timeout: 30000, // 30 second timeout }); ``` *** ## Best Practices ### 1. Reuse Client Instances ```typescript theme={null} // ✅ Good: Create once, reuse const securelend = new SecureLend(); async function compareLoans() { return securelend.compareBusinessLoans({ ... }); } // ❌ Bad: Create new instance each time async function compareLoans() { const securelend = new SecureLend(); return securelend.compareBusinessLoans({ ... }); } ``` ### 2. Handle Errors Gracefully ```typescript theme={null} try { const loans = await securelend.compareBusinessLoans({ ... }); return loans; } catch (error) { if (error instanceof SecureLendError) { // Log structured error logger.error('Loan comparison failed', { code: error.code, details: error.details }); } // Return fallback or rethrow throw error; } ``` ### 3. Use TypeScript Types ```typescript theme={null} import { BusinessLoanRequest, LoanComparisonResponse } from "@securelend/sdk"; async function getLoans( request: BusinessLoanRequest, ): Promise { const securelend = new SecureLend(); return securelend.compareBusinessLoans(request); } ``` ### 4. Validate Input Early ```typescript theme={null} function validateLoanRequest(amount: number, purpose: string) { if (amount < 1000 || amount > 5000000) { throw new Error("Loan amount must be between $1,000 and $5,000,000"); } const validPurposes = ["equipment", "working_capital", "expansion"]; if (!validPurposes.includes(purpose)) { throw new Error(`Invalid purpose: ${purpose}`); } } ``` *** ## Next Steps Practical examples and patterns All 20 tools documented View source and contribute Get help from our team # SDK Overview Source: https://docs.securelend.ai/sdk/overview Official TypeScript SDK for SecureLend financial services # SDK Overview The SecureLend SDK provides a type-safe TypeScript/JavaScript wrapper for connecting to the SecureLend MCP server programmatically. **Use the SDK when you want to:** * Integrate SecureLend into your own applications * Build custom financial comparison tools * Automate loan research and analysis * Create financial dashboards and reporting **Use Claude/ChatGPT when you want to:** * Interactive financial advice through AI assistants * Quick loan comparisons without coding * Natural language financial queries *** ## Quick Start ### Installation ```bash theme={null} npm install @securelend/sdk # or pnpm add @securelend/sdk # or yarn add @securelend/sdk ``` ### Basic Usage ```typescript theme={null} import { SecureLend } from "@securelend/sdk"; // Create client - connects to https://mcp.securelend.ai/mcp const securelend = new SecureLend(); // Compare business loans const result = await securelend.compareBusinessLoans({ loanAmount: 200000, purpose: "equipment", annualRevenue: 1200000, creditScore: 720, }); console.log(`Found ${result.offers.length} loan offers`); ``` That's it! No API keys required - the SDK connects to our public MCP server. *** ## Key Features ### 🔌 Direct MCP Connection Connects directly to `https://mcp.securelend.ai/mcp` - the same server used by Claude and ChatGPT. ```typescript theme={null} // Default configuration (recommended) const securelend = new SecureLend(); // Custom configuration (advanced) const securelend = new SecureLend({ serverUrl: "https://custom-server.com/mcp", timeout: 30000, }); ``` ### 📝 Full TypeScript Support Complete type definitions for all requests and responses: ```typescript theme={null} import { SecureLend, BusinessLoanRequest, LoanComparisonResponse, } from "@securelend/sdk"; const request: BusinessLoanRequest = { loanAmount: 200000, purpose: "equipment", }; const response: LoanComparisonResponse = await securelend.compareBusinessLoans(request); ``` ### 🚀 Zero Configuration No API keys, no authentication, no setup. Just install and start using: ```typescript theme={null} import { SecureLend } from "@securelend/sdk"; const securelend = new SecureLend(); // Ready to use immediately ``` ### 🎯 20 Financial Tools Access all SecureLend tools programmatically: Personal loans, business loans, auto loans, student loans, mortgages Banking accounts, savings accounts, credit cards Loan payments, mortgage PITI, lease vs purchase Submit applications, track status, upload documents *** ## Architecture ``` ┌───────────────────────────────────┐ │ Your Application │ │ (Node.js, React, Next.js, etc.) │ └───────────────────────────────────┘ ↓ ┌───────────────────────────────────┐ │ @securelend/sdk │ │ • Type-safe wrappers │ │ • Error handling │ │ • Promise-based API │ └───────────────────────────────────┘ ↓ MCP Protocol ┌───────────────────────────────────┐ │ mcp.securelend.ai/mcp │ │ • 20 financial tools │ │ • Real-time lender data │ │ • 200+ lender integrations │ └───────────────────────────────────┘ ``` **Benefits:** * ✅ Always up-to-date (live server connection) * ✅ No API keys to manage * ✅ No rate limits for comparison tools * ✅ Type-safe development experience *** ## Use Cases ### Financial Comparison Platforms Build your own loan comparison website or app: ```typescript theme={null} // API route in Next.js export async function POST(request: Request) { const { loanAmount, purpose } = await request.json(); const securelend = new SecureLend(); const offers = await securelend.compareBusinessLoans({ loanAmount, purpose, }); return Response.json(offers); } ``` ### Internal Tools & Dashboards Create financial analysis tools for your team: ```typescript theme={null} async function analyzeFinancingOptions() { const securelend = new SecureLend(); // Compare multiple product types const [loans, cards, banking] = await Promise.all([ securelend.compareBusinessLoans({ loanAmount: 100000 }), securelend.compareBusinessCreditCards({ annualRevenue: 500000 }), securelend.compareBusinessBanking({ monthlyTransactions: 200 }), ]); return { loans, cards, banking }; } ``` ### Financial Automation Automate loan research and monitoring: ```typescript theme={null} async function monitorRates() { const securelend = new SecureLend(); // Check rates daily setInterval( async () => { const offers = await securelend.comparePersonalLoans({ loanAmount: 25000, purpose: "debt_consolidation", }); const bestRate = Math.min(...offers.map((o) => o.interestRate)); if (bestRate < 9.0) { await sendAlert(`Great rate found: ${bestRate}%`); } }, 24 * 60 * 60 * 1000, ); // Daily } ``` ### Embedded Financial Services Add financial comparison to your existing product: ```typescript theme={null} // Inside your SaaS app async function showFinancingOptions(businessData) { const securelend = new SecureLend(); const financing = await securelend.compareBusinessLoans({ loanAmount: businessData.requestedAmount, purpose: "working_capital", annualRevenue: businessData.revenue, }); return financing.offers; } ``` *** ## Available Methods ### Loan Comparison Compare personal loan offers **Parameters:** loanAmount, purpose, creditScore, employmentStatus, monthlyIncome, state **Returns:** Array of loan offers with rates, terms, lender details [Full reference →](/mcp/tools#compare-personal-loans) Compare business loan offers **Parameters:** loanAmount, purpose, annualRevenue, industry, state, creditScore **Returns:** Business loan offers with approval likelihood [Full reference →](/mcp/tools#compare-business-loans) Compare auto loan rates **Parameters:** loanAmount, isNew, creditScore, state **Returns:** Auto loan rate comparisons [Full reference →](/mcp/tools#compare-car-loans) Compare student loan options **Parameters:** loanAmount, degreeType, creditScore, coSignerCreditScore, state **Returns:** Student loan offers by lender [Full reference →](/mcp/tools#compare-student-loans) Compare mortgage rates **Parameters:** loanAmount, loanType, homePrice, downPayment, creditScore, propertyType, state **Returns:** Mortgage rate comparisons [Full reference →](/mcp/tools#compare-personal-mortgages) Compare commercial mortgages **Parameters:** loanAmount, loanType, homePrice, downPayment, creditScore, propertyType, state **Returns:** Commercial mortgage options [Full reference →](/mcp/tools#compare-business-mortgages) ### Banking & Credit Cards Compare checking/savings accounts [Full reference →](/mcp/tools#compare-personal-banking) Compare business banking products [Full reference →](/mcp/tools#compare-business-banking) Compare high-yield savings [Full reference →](/mcp/tools#compare-savings-accounts) Compare personal credit cards [Full reference →](/mcp/tools#compare-personal-credit-cards) Compare business credit cards [Full reference →](/mcp/tools#compare-business-credit-cards) ### Financial Calculators Calculate monthly loan payments **Parameters:** loanAmount, interestRate, loanTermInMonths **Returns:** Monthly payment, total interest, amortization [Full reference →](/mcp/tools#calculate-loan-payment) Calculate PITI mortgage payments **Parameters:** propertyValue, downPayment, interestRate, loanTermInYears, propertyTaxRate, homeInsurance **Returns:** Complete PITI breakdown [Full reference →](/mcp/tools#calculate-mortgage-payment) Compare vehicle lease vs buy **Parameters:** purchasePrice, downPayment, interestRate, loanTermInMonths, monthlyLeasePayment, etc. **Returns:** Total cost comparison [Full reference →](/mcp/tools#compare-lease-vs-purchase) [View complete tool reference →](/mcp/tools) *** ## Packages ### @securelend/sdk (Core) The main SDK package for TypeScript/JavaScript. **Status:** ✅ Beta - Available for testing ```bash theme={null} npm install @securelend/sdk ``` **Platform Support:** * ✅ Node.js 16+ * ✅ Modern browsers * ✅ Edge runtime (Vercel, Cloudflare Workers) * ✅ React Server Components ### @securelend/react (Coming Soon) React hooks and components. **Status:** 🔄 In Development - Q1 2025 ```typescript theme={null} import { useLoans } from '@securelend/react'; function LoanComparison() { const { data, loading, error } = useLoans({ loanAmount: 200000, purpose: 'equipment' }); if (loading) return ; return ; } ``` ### Python SDK (Planned) Python client library. **Status:** 🔄 Planned - Q2 2025 ```python theme={null} from securelend import SecureLend securelend = SecureLend() loans = securelend.compare_business_loans( loan_amount=200000, purpose='equipment' ) ``` *** ## Comparison: SDK vs AI Integration ### Use the SDK when you: * ✅ Need programmatic access * ✅ Want to build custom applications * ✅ Need to process multiple queries * ✅ Want to integrate with existing systems * ✅ Need automated workflows ### Use Claude/ChatGPT when you: * ✅ Want interactive conversations * ✅ Need natural language queries * ✅ Want quick one-off comparisons * ✅ Prefer guided assistance * ✅ Don't want to write code **Both connect to the same MCP server**, so you get identical data and capabilities. [Setup Claude Desktop →](/mcp/setup#claude-desktop) *** ## Next Steps Complete TypeScript/JavaScript reference Practical examples and patterns All 20 tools documented View source code and contribute *** ## Support * **GitHub Issues:** [SecureLend/sdk](https://github.com/SecureLend/sdk/issues) * **Email:** [developers@securelend.ai](mailto:developers@securelend.ai) * **Documentation:** This site (docs.securelend.ai) * **Status:** [status.securelend.ai](https://status.securelend.ai)