Files
PhilandClaude Opus 5.5 84411a16d9 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>
2026-11-11 16:36:58 -07:00

260 lines
11 KiB
Python

"""
Tests for the MCP server (starpunk/mcp_server, v2.15.0, ADR-075)
Requests go through the real ASGI app (Streamable HTTP, stateless JSON) with
real StarPunk tokens, so the SDK's bearer checks, resource binding and DNS
rebinding protection are exercised along with the tools.
"""
import base64
import io
import json
import pytest
from PIL import Image
from starlette.testclient import TestClient
from starpunk.indieauth import create_access_token, revoke_access_token
from starpunk.mcp_server import create_asgi_app
SITE = "https://blog.example.com"
RESOURCE = SITE + "/mcp"
ALL_SCOPES = "create update delete media draft"
HEADERS = {
"Accept": "application/json, text/event-stream",
"Content-Type": "application/json",
"MCP-Protocol-Version": "2025-11-25",
}
@pytest.fixture
def app(tmp_path):
from starpunk import create_app
data = tmp_path / "data"
return create_app(
{
"TESTING": True,
"SITE_URL": SITE,
"ADMIN_ME": "https://example.com",
"SESSION_SECRET": "test-secret",
"DATA_PATH": data,
"NOTES_PATH": data / "notes",
"DATABASE_PATH": data / "starpunk.db",
}
)
@pytest.fixture
def http(app):
with TestClient(create_asgi_app(app), base_url=SITE) as client:
yield client
@pytest.fixture
def token(app):
"""Make a token bound to the MCP resource (or another) with given scopes"""
def make(scope=ALL_SCOPES, resource=RESOURCE):
with app.app_context():
return create_access_token("https://claude.ai/client.json", scope, resource=resource)["access_token"]
return make
def rpc(http, token, method, params=None, headers=None):
body = {"jsonrpc": "2.0", "id": 1, "method": method}
if params is not None:
body["params"] = params
auth = {"Authorization": f"Bearer {token}"} if token else {}
return http.post("/mcp", json=body, headers={**HEADERS, **auth, **(headers or {})})
def call(http, token, name, **arguments):
"""Call a tool; returns (is_error, parsed JSON result or error text)"""
response = rpc(http, token, "tools/call", {"name": name, "arguments": arguments})
assert response.status_code == 200, response.text
result = response.json()["result"]
text = result["content"][0]["text"]
if result.get("isError"):
return True, text
return False, json.loads(text)
def ok(http, token, name, **arguments):
is_error, result = call(http, token, name, **arguments)
assert not is_error, result
return result
class TestAuth:
def test_no_token_points_to_resource_metadata(self, http):
response = rpc(http, None, "tools/list")
assert response.status_code == 401
assert f'resource_metadata="{SITE}/.well-known/oauth-protected-resource/mcp"' in (
response.headers["www-authenticate"]
)
def test_protected_resource_metadata(self, http):
data = http.get("/.well-known/oauth-protected-resource/mcp").json()
assert data["resource"] == RESOURCE
# Must equal the issuer in /.well-known/oauth-authorization-server
assert data["authorization_servers"] == [SITE + "/"]
def test_micropub_token_refused(self, http, token):
assert rpc(http, token(resource=None), "tools/list").status_code == 401
def test_other_resource_refused(self, http, token):
assert rpc(http, token(resource="https://other.example/mcp"), "tools/list").status_code == 401
def test_revoked_token_refused(self, app, http, token):
value = token()
with app.app_context():
revoke_access_token(value)
assert rpc(http, value, "tools/list").status_code == 401
def test_unknown_host_refused(self, http, token):
response = rpc(http, token(), "tools/list", headers={"Host": "evil.example"})
assert response.status_code in (400, 403, 421)
def test_lists_tools(self, http, token):
response = rpc(http, token(), "tools/list")
names = {t["name"] for t in response.json()["result"]["tools"]}
assert names == {
"search_notes", "list_notes", "get_note", "list_tags", "get_site_config",
"create_note", "update_note", "delete_note", "undelete_note", "upload_media",
}
def test_read_tools_are_marked_read_only(self, http, token):
tools = {t["name"]: t for t in rpc(http, token(), "tools/list").json()["result"]["tools"]}
assert tools["list_notes"]["annotations"]["readOnlyHint"] is True
assert tools["delete_note"]["annotations"]["destructiveHint"] is True
class TestWriting:
def test_create_defaults_to_draft(self, http, token):
note = ok(http, token(), "create_note", content="Hello from MCP", tags=["ai"])
assert note["status"] == "draft"
assert note["url"].startswith(SITE + "/note/")
def test_create_published_article(self, http, token):
tok = token()
note = ok(http, tok, "create_note", content="Body", title="An article", draft=False)
assert note["status"] == "published"
props = ok(http, tok, "get_note", url_or_slug=note["url"])["properties"]
assert props["name"] == ["An article"]
assert props["post-status"] == ["published"]
def test_draft_only_token_cannot_publish(self, http, token):
note = ok(http, token("draft"), "create_note", content="Sneaky", draft=False)
assert note["status"] == "draft"
def test_create_needs_scope(self, http, token):
is_error, message = call(http, token("update"), "create_note", content="x")
assert is_error and "create or draft" in message
def test_update_tags_and_publish(self, http, token):
tok = token()
note = ok(http, tok, "create_note", content="Tagged", tags=["one", "two"])
updated = ok(http, tok, "update_note", url=note["slug"], add_tags=["three"],
remove_tags=["one"], draft=False)
assert updated["status"] == "published"
props = ok(http, tok, "get_note", url_or_slug=note["slug"])["properties"]
assert props["category"] == ["two", "three"]
def test_update_content_and_remove_title(self, http, token):
tok = token()
note = ok(http, tok, "create_note", content="Old", title="Title")
ok(http, tok, "update_note", url=note["url"], content="New", title="")
props = ok(http, tok, "get_note", url_or_slug=note["url"])["properties"]
assert props["content"] == ["New"]
assert "name" not in props
def test_update_needs_scope(self, http, token):
note = ok(http, token(), "create_note", content="x")
is_error, _ = call(http, token("create"), "update_note", url=note["url"], content="y")
assert is_error
def test_delete_and_undelete(self, http, token):
tok = token()
note = ok(http, tok, "create_note", content="Gone soon", draft=False)
assert ok(http, tok, "delete_note", url=note["url"])["status"] == "deleted"
assert call(http, tok, "get_note", url_or_slug=note["slug"])[0]
assert ok(http, tok, "undelete_note", url=note["slug"])["status"] == "published"
def test_note_on_other_site_refused(self, http, token):
is_error, message = call(http, token(), "delete_note", url="https://other.example/note/x")
assert is_error and "not on this site" in message
def test_upload_media_then_attach(self, http, token):
tok = token()
buffer = io.BytesIO()
Image.new("RGB", (40, 30), "red").save(buffer, format="PNG")
media = ok(http, tok, "upload_media", filename="red.png",
data_base64=base64.b64encode(buffer.getvalue()).decode())
assert media["url"].startswith(SITE + "/media/")
note = ok(http, tok, "create_note", photos=[{"url": media["url"], "alt": "A red square"}])
props = ok(http, tok, "get_note", url_or_slug=note["slug"])["properties"]
assert props["photo"][0]["alt"] == "A red square"
def test_upload_rejects_bad_base64(self, http, token):
is_error, message = call(http, token(), "upload_media", filename="x.png", data_base64="!!!")
assert is_error and "base64" in message
class TestReading:
def test_list_hides_drafts_by_default(self, http, token):
tok = token()
ok(http, tok, "create_note", content="Draft")
ok(http, tok, "create_note", content="Public", draft=False)
assert [n["excerpt"] for n in ok(http, tok, "list_notes")["notes"]] == ["Public"]
assert len(ok(http, tok, "list_notes", include_drafts=True)["notes"]) == 2
def test_drafts_need_a_posting_scope(self, http, token):
ok(http, token(), "create_note", content="Secret draft")
reader = token("media")
assert call(http, reader, "list_notes", include_drafts=True)[0]
assert ok(http, reader, "list_notes")["notes"] == []
def test_draft_hidden_from_get_without_scope(self, http, token):
note = ok(http, token(), "create_note", content="Secret draft")
is_error, _ = call(http, token("media"), "get_note", url_or_slug=note["slug"])
assert is_error
def test_search(self, http, token):
tok = token()
ok(http, tok, "create_note", content="Pancakes on Sunday", draft=False)
ok(http, tok, "create_note", content="Waffles", draft=False)
results = ok(http, tok, "search_notes", query="pancakes")["results"]
assert len(results) == 1 and results[0]["url"].startswith(SITE + "/note/")
def test_tags(self, http, token):
tok = token()
ok(http, tok, "create_note", content="x", tags=["Cats", "dogs"])
assert set(ok(http, tok, "list_tags")["tags"]) == {"Cats", "dogs"}
assert ok(http, tok, "list_tags", filter="cat")["tags"] == ["Cats"]
def test_site_config(self, http, token):
config = ok(http, token("media"), "get_site_config")
assert config["media-endpoint"] == SITE + "/micropub/media"
assert "syndicate-to" in config
class TestSidecarApp:
def test_workers_off_when_built_from_environment(self, monkeypatch, tmp_path):
"""create_asgi_app() without an app never starts background workers"""
import starpunk
seen = {}
real = starpunk.create_app
def spy(config=None):
seen.update(config or {})
return real({**(config or {}), "TESTING": True, "SITE_URL": SITE,
"SESSION_SECRET": "x", "ADMIN_ME": "https://example.com", "DATA_PATH": tmp_path,
"NOTES_PATH": tmp_path / "notes", "DATABASE_PATH": tmp_path / "db.sqlite"})
monkeypatch.setattr(starpunk, "create_app", spy)
create_asgi_app()
assert seen["BACKGROUND_WORKERS_ENABLED"] is False