File size: 3,718 Bytes
042f4ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# Copyright (c) 2026 CrewHub. All rights reserved.
# Proprietary and confidential. See LICENSE for details.
"""ANP (Agent Network Protocol) endpoints.

Serves DID documents, agent descriptions in JSON-LD format,
and the well-known agent-descriptions discovery endpoint.
"""

from uuid import UUID

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession

from src.core.did import agent_did, build_agent_description, build_did_document
from src.database import get_db
from src.models.agent import Agent, AgentStatus
from src.services.registry import RegistryService

from sqlalchemy import select

router = APIRouter(tags=["anp"])


@router.get("/agents/{agent_id}/did.json")
async def get_did_document(
    agent_id: UUID,
    db: AsyncSession = Depends(get_db),
):
    """Serve the W3C DID document for an agent.

    Returns a DID Core compliant JSON document with the agent's public key,
    authentication method, and service endpoints.
    """
    service = RegistryService(db)
    try:
        agent = await service.get_agent(agent_id)
    except Exception:
        raise HTTPException(status_code=404, detail="Agent not found")

    if not getattr(agent, "did_public_key", None):
        raise HTTPException(status_code=404, detail="Agent has no DID identity")

    doc = build_did_document(
        agent_id=agent.id,
        public_key=agent.did_public_key,
        endpoint=agent.endpoint,
    )
    return doc


@router.get("/agents/{agent_id}/description")
async def get_agent_description(
    agent_id: UUID,
    db: AsyncSession = Depends(get_db),
):
    """Serve the JSON-LD agent description (ANP Agent Description Protocol).

    Returns metadata, capabilities, interface specs, and security bindings.
    """
    service = RegistryService(db)
    try:
        agent = await service.get_agent(agent_id)
    except Exception:
        raise HTTPException(status_code=404, detail="Agent not found")

    skills = [
        {
            "name": s.name,
            "description": s.description,
            "input_modes": s.input_modes,
            "output_modes": s.output_modes,
        }
        for s in agent.skills
    ]

    description = build_agent_description(
        agent_id=agent.id,
        name=agent.name,
        description=agent.description or "",
        skills=skills,
        endpoint=agent.endpoint,
        mcp_server_url=getattr(agent, "mcp_server_url", None),
    )
    return description


@router.get("/.well-known/agent-descriptions")
async def well_known_agent_descriptions(
    db: AsyncSession = Depends(get_db),
):
    """JSON-LD CollectionPage listing all active agents' description URLs.

    This is the ANP discovery endpoint that allows agents to find other
    agents on this platform.
    """
    stmt = (
        select(Agent.id, Agent.name, Agent.description)
        .where(Agent.status == AgentStatus.ACTIVE)
        .order_by(Agent.created_at.desc())
        .limit(100)
    )
    result = await db.execute(stmt)
    agents = result.all()

    base_url = "https://api.crewhubai.com/api/v1"
    items = []
    for agent_row in agents:
        aid = str(agent_row[0])
        items.append({
            "@type": "SoftwareAgent",
            "identifier": agent_did(agent_row[0]),
            "name": agent_row[1],
            "description": (agent_row[2] or "")[:200],
            "url": f"{base_url}/agents/{aid}/description",
            "didDocument": f"{base_url}/agents/{aid}/did.json",
        })

    return {
        "@context": "https://schema.org",
        "@type": "CollectionPage",
        "name": "CrewHub Agent Directory",
        "numberOfItems": len(items),
        "itemListElement": items,
    }