Skip to main content

MCP Usage Examples

This page provides practical examples of using Cred Protocol MCP services in various scenarios.

Example 1: Credit Score Check

A common use case is checking the credit score before approving a loan or granting access.
import httpx

async def check_creditworthiness(address: str, min_score: int = 700) -> dict:
    """
    Check if an address meets minimum credit requirements.
    
    Args:
        address: Ethereum address or ENS name
        min_score: Minimum required credit score
        
    Returns:
        Dict with approval status and score details
    """
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"https://api.credprotocol.com/mcp/sandbox/score/{address}",
            params={"include_factors": True}
        )
        data = response.json()
        
        return {
            "address": data["address"],
            "score": data["score"],
            "range": data["range"],
            "approved": data["score"] >= min_score,
            "factors": data.get("factors", [])
        }

# Usage
result = await check_creditworthiness("vitalik.eth", min_score=750)
if result["approved"]:
    print(f"✅ Approved! Score: {result['score']} ({result['range']})")
else:
    print(f"❌ Not approved. Score: {result['score']} (need 750+)")

Example 2: Batch Risk Assessment

Evaluate multiple addresses at once for portfolio risk analysis.
import httpx
from typing import List

async def batch_risk_assessment(addresses: List[str]) -> dict:
    """
    Assess credit risk across multiple addresses.
    
    Returns summary statistics and individual scores.
    """
    async with httpx.AsyncClient() as client:
        response = await client.post(
            "https://api.credprotocol.com/mcp/sandbox/score/batch",
            json={"addresses": addresses}
        )
        data = response.json()
        
        scores = [s["score"] for s in data["scores"]]
        
        return {
            "count": data["count"],
            "average_score": sum(scores) / len(scores),
            "min_score": min(scores),
            "max_score": max(scores),
            "high_risk_count": sum(1 for s in scores if s < 640),
            "scores": data["scores"]
        }

# Usage
addresses = [
    "vitalik.eth",
    "0x742d35Cc6634C0532925a3b844Bc9e7595f32345",
    "0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B"
]
risk = await batch_risk_assessment(addresses)
print(f"Portfolio avg score: {risk['average_score']:.0f}")
print(f"High risk addresses: {risk['high_risk_count']}")

Example 3: Identity Verification Gate

Only allow users with verified identity to access premium features.
import httpx

REQUIRED_ATTESTATIONS = ["ENS Name", "Gitcoin Passport"]

async def verify_identity(address: str) -> dict:
    """
    Check if address has required identity attestations.
    """
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"https://api.credprotocol.com/mcp/sandbox/identity/{address}"
        )
        data = response.json()
        
        attestations = set(data["attestations"])
        required = set(REQUIRED_ATTESTATIONS)
        
        return {
            "address": data["address"],
            "verified": required.issubset(attestations),
            "has": list(attestations),
            "missing": list(required - attestations)
        }

# Usage
result = await verify_identity("vitalik.eth")
if result["verified"]:
    print("✅ Identity verified - access granted")
else:
    print(f"❌ Missing: {result['missing']}")

Example 4: Portfolio Analysis Dashboard

Build a comprehensive view of a wallet’s holdings.
import httpx
import asyncio

CHAINS = {
    1: "Ethereum",
    10: "Optimism", 
    137: "Polygon",
    8453: "Base",
    42161: "Arbitrum"
}

async def get_portfolio_breakdown(address: str) -> dict:
    """
    Get portfolio value broken down by chain.
    """
    async with httpx.AsyncClient() as client:
        # Fetch total and chain-specific values in parallel
        tasks = [
            client.get(f"https://api.credprotocol.com/mcp/sandbox/portfolio/{address}")
        ]
        for chain_id in CHAINS:
            tasks.append(
                client.get(
                    f"https://api.credprotocol.com/mcp/sandbox/portfolio/{address}/chain/{chain_id}"
                )
            )
        
        responses = await asyncio.gather(*[t for t in tasks])
        
        total_data = responses[0].json()
        chain_data = [r.json() for r in responses[1:]]
        
        return {
            "address": total_data["address"],
            "total_usd": total_data["total_asset_usd"],
            "chains": sorted(
                [
                    {
                        "chain": c["chain_name"],
                        "value_usd": c["total_asset_usd"],
                        "percentage": (c["total_asset_usd"] / total_data["total_asset_usd"]) * 100
                    }
                    for c in chain_data
                ],
                key=lambda x: x["value_usd"],
                reverse=True
            )
        }

# Usage
portfolio = await get_portfolio_breakdown("vitalik.eth")
print(f"Total: ${portfolio['total_usd']:,.2f}")
for chain in portfolio["chains"]:
    print(f"  {chain['chain']}: ${chain['value_usd']:,.2f} ({chain['percentage']:.1f}%)")

Example 5: AI Agent Integration

Example prompt for an AI agent using MCP tools:
**User:** Can you analyze the wallet 0x742d35Cc6634C0532925a3b844Bc9e7595f32345?

**AI Agent Actions:**
1. Call `get_credit_score("0x742d35...")` → Score: 785 (Good)
2. Call `get_financial_summary("0x742d35...")` → Net worth: $45,230
3. Call `get_identity_attestations("0x742d35...")` → ENS, Gitcoin Passport

**AI Agent Response:**
This wallet has a **Good credit score of 785** with:
- Total net worth of **$45,230** across multiple chains
- Active DeFi positions with healthy collateral ratios
- Verified identity through ENS and Gitcoin Passport
- No history of liquidations or defaults

The wallet shows responsible DeFi usage and could qualify for 
undercollateralized lending up to $5,000.

Example 6: Webhook-Style Monitoring

Set up periodic monitoring of credit scores:
import httpx
import asyncio

MONITORED_ADDRESSES = [
    "vitalik.eth",
    "0x742d35Cc6634C0532925a3b844Bc9e7595f32345"
]
ALERT_THRESHOLD = 700

async def monitor_scores():
    """Monitor credit scores and alert on changes."""
    previous_scores = {}
    
    while True:
        async with httpx.AsyncClient() as client:
            for address in MONITORED_ADDRESSES:
                response = await client.get(
                    f"https://api.credprotocol.com/mcp/sandbox/score/{address}"
                )
                data = response.json()
                current_score = data["score"]
                
                # Check for significant changes
                if address in previous_scores:
                    change = current_score - previous_scores[address]
                    if abs(change) > 50:
                        print(f"⚠️ {address}: Score changed by {change:+d}")
                
                # Check for threshold breach
                if current_score < ALERT_THRESHOLD:
                    print(f"🚨 {address}: Score {current_score} below threshold!")
                
                previous_scores[address] = current_score
        
        # Check every 5 minutes
        await asyncio.sleep(300)

# Run monitor
asyncio.run(monitor_scores())

Next Steps