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.Copy
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.Copy
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.Copy
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.Copy
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:Copy
**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:Copy
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())
Example 7: Agent Discovery with ERC-8004
Search the on-chain agent registry to find and verify AI agents before interacting with them.Copy
import httpx
async def discover_agents(capability: str, min_results: int = 1) -> dict:
"""
Search the ERC-8004 Identity Registry for agents matching a capability.
Args:
capability: What the agent should be able to do (e.g., "lending", "risk")
min_results: Minimum number of results expected
Returns:
Dict with matching agents and discovery metadata
"""
async with httpx.AsyncClient() as client:
response = await client.get(
"https://api.credprotocol.com/mcp/agents/search",
params={"q": capability, "limit": 10}
)
data = response.json()
return {
"query": capability,
"found": data["total_results"],
"sufficient": data["total_results"] >= min_results,
"agents": [
{
"id": agent["agent_id"],
"name": agent["metadata"]["name"] if agent["metadata"] else None,
"owner": agent["owner"],
}
for agent in data["agents"]
]
}
# Usage
results = await discover_agents("credit scoring")
for agent in results["agents"]:
print(f"Agent #{agent['id']}: {agent['name']} (owner: {agent['owner'][:10]}...)")
Example 8: AI Agent Integration with Agent Discovery
Example prompt for an AI agent combining wallet analysis with agent discovery:Copy
**User:** Find me agents that do risk analysis, and check if their owners have good credit.
**AI Agent Actions:**
1. Call `search_agents("risk analysis")` → Found 3 agents
2. Call `get_credit_scores_batch(["0x742d...", "0xAb58...", "0x1234..."])` → Scores for agent owners
**AI Agent Response:**
I found **3 registered risk analysis agents** in the ERC-8004 registry:
1. **Risk Analyzer Pro** (Agent #42) — Owner score: 891 (Very Good)
2. **DeFi Risk Scout** (Agent #87) — Owner score: 745 (Good)
3. **Credit Risk Bot** (Agent #156) — Owner score: 623 (Low)
Agents #42 and #87 have owners with strong credit profiles, suggesting
established on-chain participants. Agent #156's owner has a low score,
which may warrant additional verification before relying on its outputs.