> ## Documentation Index
> Fetch the complete documentation index at: https://docs.credprotocol.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Examples

> Practical examples of using Cred Protocol MCP services

# 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.

<CodeGroup>
  ```python Python theme={null}
  import httpx

  API_KEY = "YOUR_API_KEY"
  HEADERS = {"Authorization": f"Bearer {API_KEY}"}

  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/score/{address}",
              headers=HEADERS,
              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+)")
  ```

  ```typescript TypeScript theme={null}
  const API_KEY = "YOUR_API_KEY";
  const HEADERS = { Authorization: `Bearer ${API_KEY}` };

  interface CreditCheck {
    address: string;
    score: number;
    range: string;
    approved: boolean;
    factors: Array<{ label: string; rating: string; description: string }>;
  }

  async function checkCreditworthiness(
    address: string,
    minScore: number = 700
  ): Promise<CreditCheck> {
    const response = await fetch(
      `https://api.credprotocol.com/mcp/score/${address}?include_factors=true`,
      { headers: HEADERS }
    );
    const data = await response.json();

    return {
      address: data.address,
      score: data.score,
      range: data.range,
      approved: data.score >= minScore,
      factors: data.factors || []
    };
  }

  // Usage
  const result = await checkCreditworthiness("vitalik.eth", 750);
  console.log(result.approved ? "Approved!" : "Not approved");
  ```

  ```bash cURL theme={null}
  # Check score and pipe to jq for analysis
  curl -s -H "Authorization: Bearer YOUR_API_KEY" \
    "https://api.credprotocol.com/mcp/score/vitalik.eth?include_factors=true" | \
    jq '{approved: (.score >= 750), score: .score, range: .range}'
  ```
</CodeGroup>

***

## Example 2: Batch Risk Assessment

Evaluate multiple addresses at once for portfolio risk analysis.

<CodeGroup>
  ```python Python theme={null}
  import httpx
  from typing import List

  API_KEY = "YOUR_API_KEY"
  HEADERS = {"Authorization": f"Bearer {API_KEY}"}

  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/score/batch",
              headers=HEADERS,
              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']}")
  ```

  ```typescript TypeScript theme={null}
  const API_KEY = "YOUR_API_KEY";
  const HEADERS = { Authorization: `Bearer ${API_KEY}` };

  interface RiskAssessment {
    count: number;
    averageScore: number;
    minScore: number;
    maxScore: number;
    highRiskCount: number;
    scores: Array<{ address: string; score: number; range: string }>;
  }

  async function batchRiskAssessment(addresses: string[]): Promise<RiskAssessment> {
    const response = await fetch("https://api.credprotocol.com/mcp/score/batch", {
      method: "POST",
      headers: { ...HEADERS, "Content-Type": "application/json" },
      body: JSON.stringify({ addresses })
    });
    const data = await response.json();

    const scores = data.scores.map((s: any) => s.score);

    return {
      count: data.count,
      averageScore: scores.reduce((a: number, b: number) => a + b, 0) / scores.length,
      minScore: Math.min(...scores),
      maxScore: Math.max(...scores),
      highRiskCount: scores.filter((s: number) => s < 640).length,
      scores: data.scores
    };
  }
  ```
</CodeGroup>

***

## Example 3: Identity Verification Gate

Only allow users with verified identity to access premium features.

<CodeGroup>
  ```python Python theme={null}
  import httpx

  API_KEY = "YOUR_API_KEY"
  HEADERS = {"Authorization": f"Bearer {API_KEY}"}
  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/identity/{address}",
              headers=HEADERS,
          )
          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']}")
  ```

  ```typescript TypeScript theme={null}
  const API_KEY = "YOUR_API_KEY";
  const HEADERS = { Authorization: `Bearer ${API_KEY}` };
  const REQUIRED_ATTESTATIONS = ["ENS Name", "Gitcoin Passport"];

  async function verifyIdentity(address: string) {
    const response = await fetch(
      `https://api.credprotocol.com/mcp/identity/${address}`,
      { headers: HEADERS }
    );
    const data = await response.json();

    const attestations = new Set(data.attestations);
    const missing = REQUIRED_ATTESTATIONS.filter(a => !attestations.has(a));

    return {
      address: data.address,
      verified: missing.length === 0,
      has: data.attestations,
      missing
    };
  }
  ```
</CodeGroup>

***

## Example 4: Portfolio Analysis Dashboard

Build a comprehensive view of a wallet's holdings.

<CodeGroup>
  ```python Python theme={null}
  import httpx
  import asyncio

  API_KEY = "YOUR_API_KEY"
  HEADERS = {"Authorization": f"Bearer {API_KEY}"}

  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/portfolio/{address}",
                  headers=HEADERS,
              )
          ]
          for chain_id in CHAINS:
              tasks.append(
                  client.get(
                      f"https://api.credprotocol.com/mcp/portfolio/{address}/chain/{chain_id}",
                      headers=HEADERS,
                  )
              )

          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}%)")
  ```
</CodeGroup>

***

## Example 5: AI Agent Integration

Example prompt for an AI agent using MCP tools:

```markdown theme={null}
**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:

```python theme={null}
import httpx
import asyncio

API_KEY = "YOUR_API_KEY"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

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/score/{address}",
                    headers=HEADERS,
                )
                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"Warning: {address}: Score changed by {change:+d}")

                # Check for threshold breach
                if current_score < ALERT_THRESHOLD:
                    print(f"Alert: {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.

<CodeGroup>
  ```python Python theme={null}
  import httpx

  API_KEY = "YOUR_API_KEY"
  HEADERS = {"Authorization": f"Bearer {API_KEY}"}

  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",
              headers=HEADERS,
              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]}...)")
  ```

  ```typescript TypeScript theme={null}
  const API_KEY = "YOUR_API_KEY";
  const HEADERS = { Authorization: `Bearer ${API_KEY}` };

  interface AgentResult {
    id: number;
    name: string | null;
    owner: string;
  }

  async function discoverAgents(capability: string): Promise<AgentResult[]> {
    const response = await fetch(
      `https://api.credprotocol.com/mcp/agents/search?q=${encodeURIComponent(capability)}&limit=10`,
      { headers: HEADERS }
    );
    const data = await response.json();

    return data.agents.map((agent: any) => ({
      id: agent.agent_id,
      name: agent.metadata?.name ?? null,
      owner: agent.owner,
    }));
  }

  // Usage
  const agents = await discoverAgents("risk analysis");
  agents.forEach(a => console.log(`Agent #${a.id}: ${a.name}`));
  ```

  ```bash cURL theme={null}
  # Search for lending-related agents
  curl -s -H "Authorization: Bearer YOUR_API_KEY" \
    "https://api.credprotocol.com/mcp/agents/search?q=lending&limit=5" | \
    jq '.agents[] | {id: .agent_id, name: .metadata.name, owner: .owner}'
  ```
</CodeGroup>

***

## Example 8: AI Agent Integration with Agent Discovery

Example prompt for an AI agent combining wallet analysis with agent discovery:

```markdown theme={null}
**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.
```

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Tools Reference" icon="wrench" href="/mcp-services/tools">
    Complete API reference for all tools
  </Card>

  <Card title="REST API" icon="plug" href="/api-reference/overview">
    Use the REST API directly
  </Card>
</CardGroup>
