Files
StarPunk/starpunk/mcp_server/tools.py
T

373 lines
13 KiB
Python

"""
MCP tools for StarPunk (v2.15.0, ADR-075)
Reading tools call the notes, tags and search services. Writing tools build
a Micropub request and hand it to the Micropub handlers, so an MCP post goes
through exactly the same checks and side effects (scopes, drafts-only
tokens, crossposting, webmentions, WebSub) as one from any Micropub client.
Scopes are the Micropub ones: reading needs any StarPunk token; drafts and
tags need create, update, delete or draft; writing needs create (or draft),
update, delete or media.
"""
import base64
import binascii
from pathlib import Path
from typing import Any, Callable, Optional
from urllib.parse import urlparse
import anyio.to_thread
from flask import Flask
from mcp.server import MCPServer
from mcp.server.auth.middleware.auth_context import get_access_token
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations
from pydantic import BaseModel, Field
from starpunk.indieauth import check_scope
from starpunk.micropub import MicropubError
DRAFT_SCOPES = ("create", "update", "delete", "draft")
MAX_LIMIT = 100
class Photo(BaseModel):
"""A photo for a note"""
url: str = Field(description="URL from upload_media, or any public image URL")
alt: str = Field(default="", description="Alt text describing the photo")
def _token_info() -> dict:
"""The caller's token as the Micropub handlers expect it"""
token = get_access_token()
if token is None:
raise ToolError("Not authenticated")
return {"me": token.subject, "client_id": token.client_id, "scope": " ".join(token.scopes)}
def _require(info: dict, *scopes: str) -> None:
if not any(check_scope(s, info["scope"]) for s in scopes):
raise ToolError(f"This needs the {' or '.join(scopes)} scope; reconnect and grant it")
def _sees_drafts(info: dict) -> bool:
return any(check_scope(s, info["scope"]) for s in DRAFT_SCOPES)
def _clamp(limit: int) -> int:
return max(1, min(int(limit), MAX_LIMIT))
def _note_url(slug: str, title=None) -> str:
from starpunk.utils import post_url
return post_url(slug, title)
def _summary(note) -> dict:
from starpunk.utils import iso_utc
return {
"url": note.url,
"slug": note.slug,
"title": note.title,
"summary": note.summary,
"kind": note.kind,
"status": "published" if note.published else "draft",
"published": iso_utc(note.created_at),
"excerpt": note.excerpt,
}
def _find_note(url_or_slug: str):
"""A note by its URL on this site or its slug"""
from starpunk.micropub import _note_from_url
from starpunk.notes import get_note
value = (url_or_slug or "").strip()
if urlparse(value).scheme:
return _note_from_url(value)
note = get_note(slug=value.strip("/").split("/")[-1]) if value else None
if note is None:
raise ToolError("Note not found")
return note
def _status_after(url: str) -> dict:
"""Summary of the note at url, as it is now"""
return _summary(_find_note(url))
def register_tools(server: MCPServer, app: Flask) -> None:
"""Add StarPunk's tools to the MCP server"""
site = app.config["SITE_URL"].rstrip("/")
async def run(fn: Callable[..., Any], *args, **kwargs) -> Any:
"""Run fn in a worker thread inside a Flask request context for SITE_URL"""
def call():
with app.test_request_context(base_url=site):
try:
return fn(*args, **kwargs)
except MicropubError as e:
raise ToolError(e.error_description or e.error) from e
except ValueError as e:
raise ToolError(str(e)) from e
return await anyio.to_thread.run_sync(call)
read_only = ToolAnnotations(read_only_hint=True, open_world_hint=False)
# Reading
@server.tool(annotations=read_only)
async def search_notes(query: str, include_drafts: bool = False, limit: int = 20) -> dict:
"""Full-text search of the site's notes. Returns matches with a snippet;
use get_note for the whole note."""
info = _token_info()
if include_drafts:
_require(info, *DRAFT_SCOPES)
def search():
from starpunk.search import has_fts_table, search_notes as fts
db_path = Path(app.config["DATABASE_PATH"])
if not has_fts_table(db_path):
raise ToolError("Search is not available on this server")
results = fts(query=query, db_path=db_path, published_only=not include_drafts, limit=_clamp(limit))
return {
"results": [
{"url": _note_url(r["slug"], r.get("article_title")), "slug": r["slug"], "title": r.get("title"),
"snippet": r.get("snippet")}
for r in results
]
}
return await run(search)
@server.tool(annotations=read_only)
async def list_notes(include_drafts: bool = False, limit: int = 20, offset: int = 0) -> dict:
"""The site's notes, newest first. Drafts are left out unless
include_drafts is true."""
info = _token_info()
if include_drafts:
_require(info, *DRAFT_SCOPES)
def notes():
from starpunk.notes import list_notes as list_all
found = list_all(published_only=not include_drafts, limit=_clamp(limit), offset=max(0, offset))
return {"notes": [_summary(n) for n in found], "offset": max(0, offset)}
return await run(notes)
@server.tool(annotations=read_only)
async def get_note(url_or_slug: str) -> dict:
"""One note in full: Markdown content, title (name), tags (category),
photos, status, reply/like/repost/bookmark target and crosspost links,
as Microformats2 properties."""
info = _token_info()
def one():
from starpunk.micropub import note_to_mf2
note = _find_note(url_or_slug)
if not note.published and not _sees_drafts(info):
raise ToolError("Note not found")
return {"url": note.url, "slug": note.slug,
"properties": note_to_mf2(note)["properties"]}
return await run(one)
@server.tool(annotations=read_only)
async def list_tags(filter: str = "") -> dict:
"""Tags in use on the site, most used first, optionally only those
containing filter."""
info = _token_info()
_require(info, *DRAFT_SCOPES)
def tags():
from starpunk.micropub import _all_categories
return {"tags": _all_categories(filter)}
return await run(tags)
@server.tool(annotations=read_only)
async def get_site_config() -> dict:
"""What the site supports: post types and the crosspost targets
(syndicate-to uids) that create_note's syndicate_to accepts."""
info = _token_info()
def config():
from starpunk.micropub import handle_query
response = handle_query({"q": "config"}, info)
# Flask views may return (response, status[, headers])
if isinstance(response, tuple):
response = response[0]
return response.get_json()
return await run(config)
# Writing
@server.tool(annotations=ToolAnnotations(destructive_hint=False, open_world_hint=True))
async def create_note(
content: str = "",
title: Optional[str] = None,
summary: Optional[str] = None,
tags: Optional[list[str]] = None,
draft: bool = True,
photos: Optional[list[Photo]] = None,
in_reply_to: Optional[str] = None,
like_of: Optional[str] = None,
repost_of: Optional[str] = None,
bookmark_of: Optional[str] = None,
syndicate_to: Optional[list[str]] = None,
slug: Optional[str] = None,
published_at: Optional[str] = None,
) -> dict:
"""Create a note (Markdown). It is a draft unless draft is false;
publishing makes it public and crossposts it to the syndicate_to
targets. A title makes it an article, at /article/<slug>; summary is its
short summary, shown on the homepage and in feeds and crossposts. The
slug is made from the title for articles and from the time for other
notes, so leave slug out unless a specific one is wanted. At most one of
like_of, repost_of and bookmark_of. published_at is an ISO 8601 date."""
info = _token_info()
_require(info, "create", "draft")
props: dict[str, list] = {"post-status": ["draft" if draft else "published"]}
if content:
props["content"] = [content]
if title:
props["name"] = [title]
if summary:
props["summary"] = [summary]
if tags:
props["category"] = list(tags)
if photos:
props["photo"] = [{"value": p.url, "alt": p.alt} for p in photos]
for name, value in (("in-reply-to", in_reply_to), ("like-of", like_of),
("repost-of", repost_of), ("bookmark-of", bookmark_of),
("published", published_at)):
if value:
props[name] = [value]
data: dict[str, Any] = {"type": ["h-entry"], "properties": props}
if syndicate_to:
data["mp-syndicate-to"] = list(syndicate_to)
if slug:
data["mp-slug"] = slug
def create():
from starpunk.micropub import handle_create
_, _, headers = handle_create(data, info)
return _status_after(headers["Location"])
return await run(create)
@server.tool(annotations=ToolAnnotations(destructive_hint=True, idempotent_hint=True, open_world_hint=True))
async def update_note(
url: str,
content: Optional[str] = None,
title: Optional[str] = None,
summary: Optional[str] = None,
tags: Optional[list[str]] = None,
add_tags: Optional[list[str]] = None,
remove_tags: Optional[list[str]] = None,
draft: Optional[bool] = None,
photos: Optional[list[Photo]] = None,
in_reply_to: Optional[str] = None,
) -> dict:
"""Change a note. Only the fields given change: content replaces the
text, title replaces the title ("" removes it), summary likewise, tags replaces all
tags, add_tags/remove_tags adjust them, photos replaces all photos,
draft false publishes a draft (and crossposts it) and true unpublishes.
Edits to published notes follow to their crossposts."""
info = _token_info()
_require(info, "update")
replace: dict[str, list] = {}
if content is not None:
replace["content"] = [content]
if title is not None:
replace["name"] = [title]
if summary is not None:
replace["summary"] = [summary]
if tags is not None:
replace["category"] = list(tags)
if draft is not None:
replace["post-status"] = ["draft" if draft else "published"]
if photos is not None:
replace["photo"] = [{"value": p.url, "alt": p.alt} for p in photos]
if in_reply_to is not None:
replace["in-reply-to"] = [in_reply_to]
data: dict[str, Any] = {"action": "update", "url": url, "replace": replace}
if add_tags:
data["add"] = {"category": list(add_tags)}
if remove_tags:
data["delete"] = {"category": list(remove_tags)}
def update():
from starpunk.micropub import handle_update
note = _find_note(url)
data["url"] = note.url
handle_update(data, info)
return _status_after(data["url"])
return await run(update)
@server.tool(annotations=ToolAnnotations(destructive_hint=True, idempotent_hint=True, open_world_hint=False))
async def delete_note(url: str) -> dict:
"""Delete a note. It can be restored with undelete_note."""
info = _token_info()
_require(info, "delete")
def delete():
from starpunk.micropub import handle_delete
note_url = _find_note(url).url
handle_delete({"url": note_url}, info)
return {"url": note_url, "status": "deleted"}
return await run(delete)
@server.tool(annotations=ToolAnnotations(destructive_hint=False, idempotent_hint=True, open_world_hint=False))
async def undelete_note(url: str) -> dict:
"""Restore a deleted note."""
info = _token_info()
_require(info, "delete")
note_url = url if urlparse(url).scheme else f"{site}/note/{url.strip('/')}"
def undelete():
from starpunk.micropub import handle_delete
handle_delete({"url": note_url}, info, undelete=True)
return _status_after(note_url)
return await run(undelete)
@server.tool(annotations=ToolAnnotations(destructive_hint=False, open_world_hint=False))
async def upload_media(filename: str, data_base64: str) -> dict:
"""Upload an image (JPEG, PNG, GIF, WebP or HEIC, base64-encoded) and
get its URL, to use as a photo in create_note or update_note."""
info = _token_info()
_require(info, "media", "create")
try:
data = base64.b64decode(data_base64, validate=True)
except (binascii.Error, ValueError):
raise ToolError("data_base64 is not valid base64")
def upload():
from starpunk.media import save_media
media = save_media(data, filename)
return {"url": f"{site}/media/{media['path']}"}
return await run(upload)