feat: MCP server for AI clients (v2.15.0, ADR-075)

Add an MCP server at SITE_URL/mcp so AI assistants (claude.ai connectors,
Claude Code) can search, read and write notes.

- starpunk/mcp_server: official MCP SDK 2.3, stateless Streamable HTTP with
  JSON responses, served by uvicorn as a sidecar from the same image.
  Ten tools; writes go through the Micropub handlers.
- IndieAuth: RFC 8707 resource indicators bound to codes and tokens
  (migration 022), client ID metadata document + public client metadata,
  draft in scopes_supported, default MCP scopes, consent screen note.
- BACKGROUND_WORKERS_ENABLED flag so the sidecar runs no workers.
- Docs: ADR-075, architecture/mcp.md and updates; CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
PhilandClaude Opus 5.5 committed 2026-11-11 16:36:58 -07:00
1 parent 4ed2033cf9
commit 84411a16d9
27 files changed
+1248 -45

No files matched your search

+57 -17
View File
@@ -25,7 +25,11 @@ from starpunk.database import get_db
from starpunk.utils import absolute_url_for
CODE_LIFETIME_MINUTES = 10
SUPPORTED_SCOPES = ["create", "update", "delete", "media", "profile"]
SUPPORTED_SCOPES = ["create", "update", "delete", "media", "draft", "profile"]
# Scopes offered to an MCP client that asks for none (v2.15.0, ADR-075):
# the owner unticks what they don't want on the consent screen
MCP_DEFAULT_SCOPES = ["create", "update", "delete", "media", "draft"]
class AuthorizationRequestError(Exception):
@@ -56,6 +60,11 @@ def issuer() -> str:
return current_app.config["SITE_URL"].rstrip("/") + "/"
def mcp_resource() -> str:
"""The MCP endpoint's resource identifier (RFC 8707, v2.15.0)"""
return current_app.config["SITE_URL"].rstrip("/") + "/mcp"
def admin_me() -> str:
"""The single identity StarPunk issues tokens for"""
return current_app.config["ADMIN_ME"]
@@ -134,7 +143,7 @@ def validate_authorization_request(params: Dict[str, str]) -> Dict[str, Any]:
Returns:
Normalized request: client_id, redirect_uri, state, scopes,
code_challenge
code_challenge, resource
Raises:
AuthorizationRequestError
@@ -176,17 +185,31 @@ def validate_authorization_request(params: Dict[str, str]) -> Dict[str, Any]:
scopes = [s for s in (params.get("scope") or "").split() if s]
# RFC 8707 resource indicator: only the MCP endpoint is a named resource
# here (v2.15.0, ADR-075). Micropub clients don't send one.
resource = (params.get("resource") or "").strip() or None
if resource is not None:
if resource.rstrip("/") != mcp_resource():
raise AuthorizationRequestError(
"invalid_target", "Unknown resource; this server only issues tokens for its MCP endpoint"
)
resource = mcp_resource()
if not scopes:
scopes = list(MCP_DEFAULT_SCOPES)
return {
"client_id": client_id,
"redirect_uri": redirect_uri,
"state": params["state"],
"scopes": scopes,
"code_challenge": code_challenge,
"resource": resource,
}
def create_authorization_code(
client_id: str, redirect_uri: str, scope: str, code_challenge: str
client_id: str, redirect_uri: str, scope: str, code_challenge: str,
resource: Optional[str] = None,
) -> str:
"""Issue a single-use authorization code (stored hashed)"""
code = secrets.token_urlsafe(32)
@@ -195,8 +218,8 @@ def create_authorization_code(
db.execute(
"""
INSERT INTO indieauth_codes
(code_hash, client_id, redirect_uri, scope, code_challenge, expires_at)
VALUES (?, ?, ?, ?, ?, ?)
(code_hash, client_id, redirect_uri, scope, code_challenge, expires_at, resource)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
_hash(code),
@@ -205,6 +228,7 @@ def create_authorization_code(
scope,
code_challenge,
datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(minutes=CODE_LIFETIME_MINUTES),
resource,
),
)
db.commit()
@@ -218,7 +242,7 @@ def redeem_authorization_code(
Redeem an authorization code exactly once
Returns:
{"me": ..., "scope": ..., "client_id": ...}
{"me": ..., "scope": ..., "client_id": ..., "resource": ...}
Raises:
InvalidGrantError
@@ -240,7 +264,7 @@ def redeem_authorization_code(
raise InvalidGrantError("Authorization code is invalid, expired or already used")
row = db.execute(
"SELECT client_id, redirect_uri, scope, code_challenge FROM indieauth_codes WHERE code_hash = ?",
"SELECT client_id, redirect_uri, scope, code_challenge, resource FROM indieauth_codes WHERE code_hash = ?",
(_hash(code),),
).fetchone()
@@ -252,11 +276,20 @@ def redeem_authorization_code(
if not secrets.compare_digest(challenge, row["code_challenge"]):
raise InvalidGrantError("PKCE verification failed")
return {"me": admin_me(), "scope": row["scope"], "client_id": row["client_id"]}
return {
"me": admin_me(),
"scope": row["scope"],
"client_id": row["client_id"],
"resource": row["resource"],
}
def create_access_token(client_id: str, scope: str) -> Dict[str, Any]:
"""Issue an access token (stored hashed); returns the token response"""
def create_access_token(client_id: str, scope: str, resource: Optional[str] = None) -> Dict[str, Any]:
"""Issue an access token (stored hashed); returns the token response
resource is the RFC 8707 resource the token is for (the MCP endpoint),
or None for Micropub tokens.
"""
token = secrets.token_urlsafe(32)
lifetime_days = current_app.config.get("INDIEAUTH_TOKEN_LIFETIME_DAYS", 90)
expires_at = datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(days=lifetime_days)
@@ -264,10 +297,10 @@ def create_access_token(client_id: str, scope: str) -> Dict[str, Any]:
db = get_db(current_app)
db.execute(
"""
INSERT INTO indieauth_tokens (token_hash, client_id, scope, expires_at)
VALUES (?, ?, ?, ?)
INSERT INTO indieauth_tokens (token_hash, client_id, scope, expires_at, resource)
VALUES (?, ?, ?, ?, ?)
""",
(_hash(token), client_id, scope, expires_at),
(_hash(token), client_id, scope, expires_at, resource),
)
db.commit()
@@ -286,14 +319,15 @@ def verify_access_token(token: str) -> Optional[Dict[str, Any]]:
Check a bearer token issued by StarPunk
Returns:
{"me", "client_id", "scope"} if active, otherwise None
{"me", "client_id", "scope", "resource", "expires_at"} if active,
otherwise None
"""
if not token:
return None
db = get_db(current_app)
row = db.execute(
"""
SELECT id, client_id, scope FROM indieauth_tokens
SELECT id, client_id, scope, resource, expires_at FROM indieauth_tokens
WHERE token_hash = ? AND revoked_at IS NULL AND expires_at > datetime('now')
""",
(_hash(token),),
@@ -306,7 +340,13 @@ def verify_access_token(token: str) -> Optional[Dict[str, Any]]:
(row["id"],),
)
db.commit()
return {"me": admin_me(), "client_id": row["client_id"], "scope": row["scope"]}
return {
"me": admin_me(),
"client_id": row["client_id"],
"scope": row["scope"],
"resource": row["resource"],
"expires_at": row["expires_at"],
}
def revoke_access_token(token: str) -> None:
@@ -334,7 +374,7 @@ def list_active_tokens() -> List[Dict[str, Any]]:
db = get_db(current_app)
rows = db.execute(
"""
SELECT id, client_id, scope, created_at, expires_at, last_used_at
SELECT id, client_id, scope, resource, created_at, expires_at, last_used_at
FROM indieauth_tokens
WHERE revoked_at IS NULL AND expires_at > datetime('now')
ORDER BY created_at DESC