Skip to content

MCP Servers Architecture

Model Context Protocol (MCP) servers provide specialized tool backends that AI agents call to perform domain-specific tasks in the Loan Defenders system.

What is MCP?

MCP (Model Context Protocol) is a standardized protocol that allows AI agents to use external tools through a consistent interface. Think of MCP servers as "tool backends" that agents call to perform specialized tasks.

Key Concepts:

  • MCP Server: A process exposing tools via MCP protocol (runs on dedicated port)
  • Tool: A function the agent can call (e.g., calculate_dti_ratio, verify_employment)
  • Client: The AI agent that calls tools (via Microsoft Agent Framework)
  • Protocol: SSE (Server-Sent Events) based communication for real-time streaming

Benefits of MCP Architecture

  1. Standardized Interface: All tools use the same protocol, simplifying agent code
  2. Tool Discovery: Agents can discover available tools dynamically
  3. Separation of Concerns: Business logic isolated in dedicated servers
  4. Easy Swapping: Replace simulated tools with production services without changing agents
  5. Independent Scaling: Each MCP server can scale independently
  6. Security Isolation: Tools run in separate processes with controlled access

Our MCP Servers

The Loan Defenders system uses 3 specialized MCP servers, each running on a dedicated port and providing domain-specific tools.

1. Application Verification Server

Port: 8010 Purpose: Identity verification and data validation Implementation: loan_defenders/tools/mcp_servers/application_verification/

Tools Exposed

Tool Parameters Returns Purpose
validate_identity applicant_id, id_last_four ValidationResult Verify ID format and last 4 digits
verify_employment employment_status, employer_name EmploymentStatus Validate job information
retrieve_credit_report applicant_id CreditReport Fetch credit history (simulated)
detect_fraud_indicators application FraudIndicators Check for suspicious patterns
check_field_completeness application_data CompletenessCheck Ensure all required fields present

Used By Agents

  • IntakeAgent (Eagle Eye): Identity validation, field completeness
  • CreditAgent (Scarlet Witch): Credit report retrieval, fraud detection
  • IncomeAgent (Hawk-Income): Employment verification
  • RiskAgent (Doctor Strange): Fraud detection, final verification

Example Tool Call

result = await mcp_client.call_tool(
    "application-verification",
    "validate_identity",
    {
        "applicant_id": "550e8400-e29b-41d4-a716-446655440000",
        "id_last_four": "1234"
    }
)
# Returns: {"valid": true, "message": "ID verified"}

2. Document Processing Server

Port: 8011 Purpose: Document analysis and data extraction Implementation: loan_defenders/tools/mcp_servers/document_processing/

Tools Exposed

Tool Parameters Returns Purpose
extract_income document_type, document_data IncomeData Parse paystubs, tax returns
verify_document_authenticity document_hash AuthenticityCheck Check if document is genuine
extract_employment_info document EmploymentInfo Pull employer name, dates from documents

Used By Agents

  • IncomeAgent (Hawk-Income): Income extraction, employment info parsing

Example Tool Call

result = await mcp_client.call_tool(
    "document-processing",
    "extract_income",
    {
        "document_type": "paystub",
        "document_data": base64_encoded_document
    }
)
# Returns: {"monthly_income": 10000, "employer": "ACME Corp"}

3. Financial Calculations Server

Port: 8012 Purpose: Financial computations and risk analysis Implementation: loan_defenders/tools/mcp_servers/financial_calculations/

Tools Exposed

Tool Parameters Returns Purpose
calculate_dti_ratio monthly_debt, monthly_income float Debt-to-income ratio
calculate_ltv_ratio loan_amount, property_value float Loan-to-value ratio
calculate_monthly_payment loan_amount, rate, term float Mortgage payment amount
calculate_income_adequacy income, loan_amount AdequacyRating Can they afford the loan?
calculate_overall_risk credit, income, application RiskScore Composite risk score
calculate_credit_score_range score RiskCategory Categorize as LOW/MEDIUM/HIGH
recommend_loan_terms application, risk_assessment LoanTerms Suggest APR, term, payment

Used By Agents

  • CreditAgent (Scarlet Witch): DTI calculation, credit score categorization
  • IncomeAgent (Hawk-Income): Income adequacy checks
  • RiskAgent (Doctor Strange): Overall risk calculation, loan term recommendations

Example Tool Call

result = await mcp_client.call_tool(
    "financial-calculations",
    "calculate_dti_ratio",
    {
        "monthly_debt": 1500,
        "monthly_income": 10000
    }
)
# Returns: 0.15 (15% DTI ratio)

Agent-to-MCP Server Mapping

graph LR
    subgraph "AI Agents"
        I[IntakeAgent<br/>Eagle Eye]
        C[CreditAgent<br/>Scarlet Witch]
        IN[IncomeAgent<br/>Hawk-Income]
        R[RiskAgent<br/>Doctor Strange]
    end

    subgraph "MCP Servers"
        AV[Application<br/>Verification<br/>:8010]
        DP[Document<br/>Processing<br/>:8011]
        FC[Financial<br/>Calculations<br/>:8012]
    end

    I --> AV
    C --> AV
    C --> FC
    IN --> AV
    IN --> DP
    IN --> FC
    R --> AV
    R --> DP
    R --> FC

Starting MCP Servers

All MCP servers must be running before starting the API server. Start them in separate terminal windows:

# Terminal 1: Application Verification Server
uv run python -m loan_defenders.tools.mcp_servers.application_verification.server

# Terminal 2: Document Processing Server
uv run python -m loan_defenders.tools.mcp_servers.document_processing.server

# Terminal 3: Financial Calculations Server
uv run python -m loan_defenders.tools.mcp_servers.financial_calculations.server

Each server will output:

INFO:     Started server process
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8010 (Press CTRL+C to quit)

Production Considerations

Current Limitations (Demo System)

The current MCP servers simulate real-world services:

  • Application Verification: Simulates credit bureau APIs (would use Experian, TransUnion, Equifax)
  • Document Processing: Simulates OCR and document verification (would use real document analysis)
  • Financial Calculations: Uses simplified formulas (would integrate with actual financial systems)

Production Requirements

For production deployment, MCP servers would need:

  1. Real External API Integration:
  2. Credit bureaus (Experian, Equifax, TransUnion)
  3. Employment verification services (The Work Number, Truework)
  4. Document verification providers (Socure, Onfido)
  5. Bank account verification (Plaid, Finicity)

  6. Security Enhancements:

  7. API key management and rotation
  8. Rate limiting and circuit breakers
  9. Request authentication and authorization
  10. Encrypted communication (TLS/mTLS)

  11. Scalability:

  12. Load balancing across multiple instances
  13. Caching for frequently accessed data
  14. Async processing for long-running operations
  15. Connection pooling for external APIs

  16. Monitoring:

  17. Request/response logging
  18. Error tracking and alerting
  19. Performance metrics (latency, throughput)
  20. Cost tracking for external API usage

  21. Compliance:

  22. GDPR/CCPA data handling
  23. PCI DSS for financial data
  24. SOC 2 audit requirements
  25. Data retention policies

Configuration

MCP server ports are configurable via environment variables in .env:

# MCP Server Ports (Optional - defaults shown)
MCP_APPLICATION_VERIFICATION_PORT=8010
MCP_DOCUMENT_PROCESSING_PORT=8011
MCP_FINANCIAL_CALCULATIONS_PORT=8012

Update loan_defenders/config/agents.yaml if ports change:

mcp_servers:
  application_verification:
    url: "http://localhost:8010"
  document_processing:
    url: "http://localhost:8011"
  financial_calculations:
    url: "http://localhost:8012"

Troubleshooting

MCP Server Won't Start

Issue: Address already in use error

Solution:

# Find process using the port
lsof -i :8010

# Kill the process
kill -9 <PID>

# Or change the port in .env
MCP_APPLICATION_VERIFICATION_PORT=8013

Agent Can't Connect to MCP Server

Issue: Agent reports "Connection refused"

Solution: 1. Verify MCP server is running: lsof -i :8010 2. Check URL in loan_defenders/config/agents.yaml 3. Restart MCP servers and API server 4. Check firewall rules

Tool Call Errors

Issue: Agent tool call returns error

Solution: 1. Check MCP server logs for error details 2. Verify tool parameters match expected format 3. Ensure all required parameters provided 4. Check for validation errors in tool logic

Next Steps