Backend Framework · Pydantic v2 + ASGI

FastAPI Pydantic Schemas & /.well-known/ Routes

Build type-safe FastAPI Pydantic v2 schemas for /.well-known/agent-card.json, MCP server.json, and RFC 9728 oauth-protected-resource with HTTP 401 WWW-Authenticate headers and zero redirect_slashes surprises.

Manifest Parameters

Zero Telemetry · Strict CSP
Authentication & OAuth Scopes
A2A Agent Card (v0.3) Options
Exact Well-Known Endpoint URL application/json
https://agent.example.com/.well-known/agent-card.json
/.well-known/agent-card.json
{
  "protocolVersion": "0.3.0",
  "name": "Acme Cloud Assistant",
  "description": "Autonomous API diagnostics, billing lookups, and workflow execution via A2A and MCP.",
  "url": "https://agent.example.com/a2a",
  "preferredTransport": "JSONRPC",
  "version": "1.0.0",
  "provider": {
    "organization": "Acme Corp",
    "url": "https://agent.example.com"
  },
  "documentationUrl": "https://docs.example.com/agents",
  "capabilities": {
    "streaming": true,
    "pushNotifications": false,
    "stateTransitionHistory": true
  },
  "defaultInputModes": [
    "text/plain",
    "application/json"
  ],
  "defaultOutputModes": [
    "application/json",
    "text/plain"
  ],
  "securitySchemes": {
    "oauth2": {
      "type": "oauth2",
      "flows": {
        "authorizationCode": {
          "authorizationUrl": "https://auth.example.com/oauth/authorize",
          "tokenUrl": "https://auth.example.com/oauth/token",
          "scopes": {
            "agent:invoke": "Authorize agent:invoke access",
            "mcp:tools": "Authorize mcp:tools access",
            "mcp:read": "Authorize mcp:read access"
          }
        }
      }
    }
  },
  "security": [
    {
      "oauth2": [
        "agent:invoke",
        "mcp:tools",
        "mcp:read"
      ]
    }
  ],
  "skills": [
    {
      "id": "diagnose-api",
      "name": "Diagnose API Errors",
      "description": "Inspect trace IDs, rate limits, and webhook delivery status.",
      "tags": [
        "diagnostics",
        "support"
      ],
      "examples": [
        "Run Diagnose API Errors for the current workspace"
      ]
    },
    {
      "id": "lookup-usage",
      "name": "Query Account Usage",
      "description": "Return bounded billing-period token and quota usage metrics.",
      "tags": [
        "billing",
        "analytics"
      ],
      "examples": [
        "Run Query Account Usage for the current workspace"
      ]
    }
  ]
}
curl Verification Command
curl -fsSL -D - "https://agent.example.com/.well-known/agent-card.json" | head -n 40
HTTP 401 WWW-Authenticate Header (RFC 9728 / MCP-PRO-002)
WWW-Authenticate: Bearer resource_metadata="https://agent.example.com/.well-known/oauth-protected-resource", scope="agent:invoke mcp:tools mcp:read"
Live Well-Known Audit 98.4% Lack Agent Cards

Verify live A2A, MCP, OAuth & AEO discovery in production

In RungLab's N=140 B2B SaaS Readiness Benchmark, 98.4% (62/63) of full-telemetry domains lacked agent-card.json. Audit your live domain with ReadyCheck, cut MCP schema token tax with MCPDiet, or automate fleet discovery checks via Apify & RapidAPI.

Required Endpoints, Paths & MIME Types

Path / Endpoint Purpose Required Content-Type
/.well-known/agent-card.json FastAPI Pydantic-validated JSONResponse endpoint application/json
/.well-known/oauth-protected-resource RFC 9728 route paired with OAuth2 Bearer HTTPException WWW-Authenticate header application/json

FastAPI Pydantic v2 Agent Card & RFC 9728 Endpoints (discovery.py)

discovery.py
from fastapi import FastAPI, HTTPException, Header
from fastapi.responses import JSONResponse
from pydantic import BaseModel, HttpUrl

app = FastAPI(title="Acme Agent API")

class AgentSkill(BaseModel):
    id: str
    name: str
    description: str
    tags: list[str] = []

class AgentCard(BaseModel):
    protocolVersion: str = "0.3.0"
    name: str
    description: str
    url: HttpUrl
    preferredTransport: str = "JSONRPC"
    version: str = "1.0.0"
    capabilities: dict[str, bool]
    skills: list[AgentSkill]

DISCOVERY_HEADERS = {
    "Access-Control-Allow-Origin": "*",
    "Cache-Control": "public, max-age=300",
}

@app.get("/.well-known/agent-card.json", include_in_schema=False)
async def agent_card() -> JSONResponse:
    card = AgentCard(
        name="Acme Python Agent",
        description="FastAPI autonomous diagnostics and MCP tool gateway.",
        url="https://agent.example.com/a2a",
        capabilities={"streaming": True, "pushNotifications": False, "stateTransitionHistory": True},
        skills=[AgentSkill(id="diagnose", name="Diagnose Trace", description="Inspect request trace.", tags=["ops"])],
    )
    return JSONResponse(content=card.model_dump(mode="json"), headers=DISCOVERY_HEADERS)

@app.get("/.well-known/oauth-protected-resource", include_in_schema=False)
async def oauth_protected_resource() -> JSONResponse:
    payload = {
        "resource": "https://agent.example.com/mcp",
        "authorization_servers": ["https://auth.example.com"],
        "scopes_supported": ["mcp:read", "mcp:tools"],
        "bearer_methods_supported": ["header"],
    }
    return JSONResponse(content=payload, headers=DISCOVERY_HEADERS)

FastAPI HTTP 401 Dependency Emitting RFC 9728 WWW-Authenticate

auth_dep.py
async def verify_mcp_bearer(authorization: str | None = Header(default=None)) -> str:
    if not authorization or not authorization.startswith("Bearer "):
        raise HTTPException(
            status_code=401,
            detail="Missing bearer token",
            headers={
                "WWW-Authenticate": 'Bearer resource_metadata="https://agent.example.com/.well-known/oauth-protected-resource", scope="mcp:read mcp:tools"'
            },
        )
    return authorization.removeprefix("Bearer ").strip()

Key Empirical & Architectural Takeaways

  • Pydantic v2 BaseModel + HttpUrl validates at startup/serialization time that your Agent Card url is well-formed and matches A2A v0.3 structure.
  • Passing include_in_schema=False keeps OpenAPI /openapi.json clean (and trims MCP/OpenAPI token overhead if you generate tools from OpenAPI).
  • FastAPI's default redirect_slashes=True can trigger HTTP 307 redirects if routes are registered with mismatched trailing slashes — register exact paths without trailing slashes.

Common Production Pitfalls to Avoid

  • Raising HTTPException(status_code=401) without headers={'WWW-Authenticate': ...} causes MCP clients to fail automatic OAuth discovery (MCP-PRO-002).
  • Forgetting CORSMiddleware or explicit Access-Control-Allow-Origin headers on JSONResponse blocks browser validators.
  • Putting FastAPI behind an HTTP-only Uvicorn proxy without --proxy-headers causes request.url.scheme to read http:// instead of https://.

More Agent Discovery Specifications & Framework Guides

← Back to AI Agent Discovery Generator & Validator Hub

Frequently Asked Questions

Why should I use card.model_dump(mode='json') with JSONResponse?

Pydantic's HttpUrl returns a Url object in Python mode; mode='json' safely serializes HttpUrl fields into standard JSON strings without TypeError.

How do I prevent FastAPI from issuing 307 redirects on /.well-known/oauth-protected-resource?

Define the decorator path without a trailing slash (`@app.get('/.well-known/oauth-protected-resource')`) and ensure reverse proxies do not rewrite paths with trailing slashes.

Should I apply strict security headers to FastAPI API routes too?

Yes — add HSTS, nosniff, Referrer-Policy, and strict CSP via middleware (see our /security-headers/fastapi/ guide) while keeping CORS open on public /.well-known/* routes.