runloopable / api /agent_card.py
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
816fa8a verified
Raw History Blame Contribute Delete
4.97 kB
"""Describe a workspace's MCP request door without reading its content."""
import os
import re
from urllib.parse import urlsplit
# A Space's own address arrives through APP_BASE_URL / AIOS_PUBLIC_BASE, which every deploy sets.
_HOSTS = {"runloopable.com", "www.runloopable.com"}
_LOCAL = {"localhost", "127.0.0.1", "::1"}
def _origin(value: str) -> str:
"""Accept an HTTP origin with no credentials, encoded characters or extra URL components."""
if not isinstance(value, str) or len(value) > 1000 or not re.fullmatch(
r"https?://(?:\[[0-9a-fA-F:]+\]|[a-zA-Z0-9.-]+)(?::[0-9]{1,5})?/?", value):
raise ValueError("The agent card needs a trusted application origin.")
parsed = urlsplit(value)
host, port = parsed.hostname, parsed.port
if not host or (port is not None and not 1 <= port <= 65535):
raise ValueError("The agent card needs a trusted application origin.")
if host not in _LOCAL and (parsed.scheme != "https" or len(host) > 253 or any(
not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", label)
for label in host.split("."))):
raise ValueError("The agent card needs a trusted application origin.")
authority = f"[{host}]" if ":" in host else host
if port is not None and port != (443 if parsed.scheme == "https" else 80):
authority += f":{port}"
return f"{parsed.scheme}://{authority}"
def _trusted_origin(base_url: str) -> str:
"""Keep the caller's deployment origin and refuse untrusted Host header values."""
origin = _origin(base_url)
parsed = urlsplit(origin)
trusted = {f"https://{host}" for host in _HOSTS}
for configured in (os.environ.get("APP_BASE_URL"), os.environ.get("AIOS_PUBLIC_BASE")):
if configured:
try:
trusted.add(_origin(configured))
except ValueError:
pass
if parsed.hostname not in _LOCAL and origin not in trusted:
raise ValueError("The agent card needs a trusted application origin.")
return origin
def build(rt, base_url: str) -> dict:
"""Build the card from the workspace name and fixed, implemented capabilities."""
origin = _trusted_origin(base_url)
name = rt.name
if not isinstance(name, str) or not name.strip():
raise ValueError("The workspace needs a name.")
root = origin + "/api/v1/external"
security = [{"oauth2": ["mcp:read"]}, {"apiKey": []}]
skills = []
for skill_id, title, description, write in (
("send_request", "Send a request", "Send a request within this workspace.", True),
("read_inbox", "Read an inbox", "Read requests you can access.", False),
("answer_request", "Answer a request", "Answer a request you can act on.", True),
("read_shared_knowledge", "Read shared knowledge", "Read shared knowledge you can access.", False),
):
skills.append({
"id": skill_id, "name": title, "description": description,
"tags": ["knowledge" if skill_id == "read_shared_knowledge" else "requests"],
"examples": [], "inputModes": ["application/json"], "outputModes": ["application/json"],
"securityRequirements": [{"oauth2": ["mcp:read", "mcp:write"]}, {"apiKey": []}]
if write else [{"oauth2": ["mcp:read"]}, {"apiKey": []}],
})
return {
"name": f"{name.strip()} agent",
"description": ("Workspace requests and shared knowledge through MCP tools. "
"Sign in with OAuth or a scoped API key. Your permissions apply to every action. "
"This card describes an MCP service. No A2A message endpoint is available."),
"supportedInterfaces": [{"url": root + "/mcp", "protocolBinding": "MCP",
"protocolVersion": "2025-06-18"}],
"provider": {"organization": "Loopable", "url": origin},
"version": "1.0.0",
"documentationUrl": origin + "/skill.md",
"capabilities": {"streaming": False, "pushNotifications": False,
"extensions": [], "extendedAgentCard": False},
"securitySchemes": {
"oauth2": {"type": "oauth2", "description": "Sign in to Loopable with OAuth and PKCE.",
"flows": {"authorizationCode": {
"authorizationUrl": root + "/oauth/authorize", "tokenUrl": root + "/oauth/token",
"scopes": {"mcp:read": "Read permitted content", "mcp:write": "Use permitted actions"},
}}},
"apiKey": {"type": "http", "scheme": "bearer", "bearerFormat": "API key",
"description": "Use a scoped Loopable API key with the owner's current permissions."},
},
"securityRequirements": security,
"defaultInputModes": ["application/json"], "defaultOutputModes": ["application/json"],
"skills": skills, "signatures": [], "iconUrl": "",
}