latest changes

This commit is contained in:
Joren de Graaf
2026-10-20 14:17:46 +02:00
parent dd1ee39afa
commit 03d7afc6a1
28 changed files with 1929 additions and 15 deletions
+79 -2
View File
@@ -1,5 +1,7 @@
"""Streamable HTTP MCP server for project management. Run on port 8766."""
import os
import base64
import binascii
from datetime import date
from typing import Any, Literal
from urllib.parse import urlsplit
@@ -28,7 +30,8 @@ from mcp.server.transport_security import TransportSecuritySettings
from pydantic import AnyHttpUrl
from projects import services
from projects.models import Activity, Card, CardComment, CardRevision, Column, Project, Tag
from projects.models import Activity, Card, CardComment, CardRevision, CardAttachment, Column, Project, Tag
from projects import attachments
def _verified(raw):
@@ -101,7 +104,7 @@ def _column_data(column):
def _safe(operation):
try:
return operation()
except (Http404, Project.DoesNotExist, Card.DoesNotExist, Column.DoesNotExist, CardRevision.DoesNotExist, Tag.DoesNotExist, get_user_model().DoesNotExist):
except (Http404, Project.DoesNotExist, Card.DoesNotExist, Column.DoesNotExist, CardRevision.DoesNotExist, CardAttachment.DoesNotExist, Tag.DoesNotExist, get_user_model().DoesNotExist):
raise ToolError('not_found: project or card is unavailable')
except PermissionDenied:
raise ToolError('permission_denied: write access required')
@@ -261,6 +264,14 @@ def create_server():
return _card_data(services.update_card(user, card, expected_revision=expected_revision, origin='mcp', **values))
return await sync_to_async(lambda: _safe(run))()
@server.tool(structured_output=True, description='Preview or atomically update 1–100 cards in one project. Supply every card ID and current revision. Changes may contain column_id, priority, assignee_id (null clears), or tag_ids (empty list clears). Dry run has no writes. Retries require the same idempotency key and payload.')
async def cards_bulk_update(project: str, card_ids: list[str], expected_revisions: dict[str, int], changes: dict[str, Any], dry_run: bool = True, idempotency_key: str | None = None) -> dict[str, Any]:
def run():
user = _actor('projects:write')
p = _project(user, project, write=True)
return services.bulk_update_cards(user, p, card_ids, expected_revisions, changes, dry_run=dry_run, idempotency_key=idempotency_key, origin='mcp')
return await sync_to_async(lambda: _safe(run))()
@server.tool(structured_output=True, description='List cards in an accessible project; filter by priority, column, or archived state.')
async def cards_list(project: str, priority: Literal['low', 'medium', 'high'] | None = None, card_type: Literal['feature', 'bug', 'task', 'research', 'idea'] | None = None, column_id: str | None = None, tag_id: int | None = None, assignee_id: int | None = None, archived: bool = False, limit: int = 50, offset: int = 0) -> dict[str, Any]:
def run():
@@ -314,6 +325,72 @@ def create_server():
return {'items': [{'id': c.pk, 'body': c.body, 'author_id': c.author_id, 'created_at': c.created_at.isoformat()} for c in card.comments.order_by('-created_at')[:min(max(limit, 1), 100)]]}
return await sync_to_async(lambda: _safe(run))()
@server.tool(structured_output=True, description='List card and progress-note attachment metadata. Set comment_id to limit to one progress note; otherwise includes both kinds. Paginated, with a card UUID required.')
async def attachments_list(card_id: str, comment_id: int | None = None, limit: int = 50, offset: int = 0) -> dict[str, Any]:
def run():
card = _card(_actor(), card_id)
qs = CardAttachment.objects.filter(card=card).order_by('created_at', 'id')
if comment_id is not None:
if not card.comments.filter(pk=comment_id).exists(): raise ValidationError('Progress note does not belong to this card.')
qs = qs.filter(comment_id=comment_id)
return {'items': [attachments.attachment_data(a) for a in qs[max(offset, 0):max(offset, 0) + min(max(limit, 1), 100)]], 'total': qs.count()}
return await sync_to_async(lambda: _safe(run))()
@server.tool(structured_output=True, description='Get attachment metadata by stable UUID after checking access to its card.')
async def attachments_get(attachment_id: str) -> dict[str, Any]:
def run():
item = CardAttachment.objects.get(pk=UUID(attachment_id))
_card(_actor(), str(item.card_id))
return attachments.attachment_data(item)
return await sync_to_async(lambda: _safe(run))()
@server.tool(structured_output=True, description='Fetch exact attachment bytes as base64 (maximum 2 MiB), with SHA-256 and UTF-8 text for supported text files. Access to the card is required.')
async def attachments_fetch(attachment_id: str) -> dict[str, Any]:
def run():
item = CardAttachment.objects.get(pk=UUID(attachment_id))
_card(_actor(), str(item.card_id))
if item.byte_size > attachments.MAX_MCP_BYTES: raise ValidationError('Attachment exceeds MCP fetch limit; download via the authenticated web UI.')
with item.file.open('rb') as stream: data = stream.read(attachments.MAX_MCP_BYTES + 1)
if len(data) != item.byte_size: raise ValidationError('Stored file size differs from metadata.')
result = {**attachments.attachment_data(item), 'content_base64': base64.b64encode(data).decode('ascii')}
if item.mime_type == 'text/plain': result['text'] = data.decode('utf-8')
return result
return await sync_to_async(lambda: _safe(run))()
@server.tool(structured_output=True, description='Upload exact file bytes encoded as standard base64 to a card or specified progress note. Maximum 2 MiB. Optional source_path and source_commit record an immutable repository snapshot; server paths are never read.')
async def attachments_upload(card_id: str, filename: str, content_base64: str, comment_id: int | None = None, title: str = '', description: str = '', source_path: str = '', source_commit: str = '') -> dict[str, Any]:
def run():
user = _actor('projects:write'); card = _card(user, card_id, write=True)
if len(content_base64) > (attachments.MAX_MCP_BYTES * 4 // 3 + 8): raise ValidationError('MCP upload exceeds 2 MiB.')
try: data = base64.b64decode(content_base64, validate=True)
except (binascii.Error, ValueError): raise ValidationError('Invalid base64 content.')
if len(data) > attachments.MAX_MCP_BYTES: raise ValidationError('MCP upload exceeds 2 MiB.')
item = attachments.upload_attachment(user, card, filename=filename, data=data, comment_id=comment_id,
title=title, description=description, source='mcp', source_path=source_path, source_commit=source_commit)
return attachments.attachment_data(item)
return await sync_to_async(lambda: _safe(run))()
@server.tool(structured_output=True, description='Update an attachment display title or description. File bytes and provenance remain unchanged.')
async def attachments_update(attachment_id: str, title: str | None = None, description: str | None = None) -> dict[str, Any]:
def run():
item = CardAttachment.objects.get(pk=UUID(attachment_id))
_card(_actor('projects:write'), str(item.card_id), write=True)
if title is not None: item.title = title.strip()
if description is not None: item.description = description
item.full_clean(); item.save(update_fields=['title', 'description'])
return attachments.attachment_data(item)
return await sync_to_async(lambda: _safe(run))()
@server.tool(structured_output=True, description='Delete a card or progress-note attachment and its stored bytes after checking card write access.')
async def attachments_delete(attachment_id: str) -> dict[str, Any]:
def run():
item = CardAttachment.objects.select_related('card__project').get(pk=UUID(attachment_id))
user = _actor('projects:write'); _card(user, str(item.card_id), write=True)
identifier = str(item.pk)
attachments.delete_attachment(user, item, source='mcp')
return {'id': identifier, 'deleted': True}
return await sync_to_async(lambda: _safe(run))()
@server.tool(structured_output=True, description='List card activity and revision numbers.')
async def cards_history(card_id: str, limit: int = 50) -> dict[str, Any]:
def run():