Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ description = "MCP server for listing ILIAS courses"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"mcp>=1.9.0",
"mcp>=1.9.0,<2.0.0",
"requests>=2.32.0",
"beautifulsoup4>=4.12.0",
"python-dotenv>=1.0.0",
Expand Down
2 changes: 1 addition & 1 deletion src/core/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from dataclasses import dataclass
import os
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import urlencode

Expand Down
17 changes: 14 additions & 3 deletions src/mcp_app/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import logging
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from datetime import date
from datetime import date, datetime

import requests
from mcp.server.fastmcp import Context, FastMCP
Expand All @@ -13,8 +13,8 @@
from services.auth_service import AuthService, IliasAuthError
from services.calendar_service import CalendarService, IliasCalendarError
from services.course_service import CourseService, IliasCourseError
from services.news_service import IliasNewsError, NewsService
from services.exercise_service import ExerciseService, IliasExerciseError
from services.news_service import IliasNewsError, NewsService
from services.repository_service import IliasRepositoryError, RepositoryService

logging.basicConfig(level=logging.INFO)
Expand Down Expand Up @@ -144,7 +144,18 @@ async def list_calendar_events(
) -> dict[str, object]:
"""List calendar agenda events for a given day (`YYYY-MM-DD`)."""
app = _app(ctx)
day = seed.strip() or date.today().isoformat()
day = seed.strip() or datetime.now().astimezone().date().isoformat()
try:
# ILIAS silently falls back to today for an unparsable seed, which
# would return events for the wrong day without any error.
date.fromisoformat(day)
except ValueError:
return {
"status": "error",
"message": f"seed must be a date in YYYY-MM-DD format, got {day!r}",
"seed": day,
"events": [],
}
try:
events = app.calendar_service.list_events(day)
except (IliasAuthError, IliasCalendarError) as exc:
Expand Down
10 changes: 5 additions & 5 deletions src/services/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@

__all__ = [
"AuthService",
"IliasAuthError",
"CourseService",
"IliasCourseError",
"CalendarService",
"CourseService",
"IliasAuthError",
"IliasCalendarError",
"NewsService",
"IliasCourseError",
"IliasNewsError",
"RepositoryService",
"IliasRepositoryError",
"NewsService",
"RepositoryService",
]
30 changes: 30 additions & 0 deletions src/services/auth_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,36 @@ def ensure_logged_in(self) -> None:
if not self._logged_in:
self.login()

def relogin(self) -> str:
"""Force a fresh authentication, discarding the cached login state."""
self._logged_in = False
return self.login()

def get(self, url: str, **kwargs: Any) -> requests.Response:
"""GET a page, transparently re-authenticating once if the session died.

ILIAS answers requests on an expired session with HTTP 200 and the
login page, so callers would otherwise silently parse the wrong HTML.
"""
self.ensure_logged_in()
kwargs.setdefault("timeout", self.settings.timeout_seconds)
resp = self.session.get(url, **kwargs)
resp.raise_for_status()

if self._looks_like_login_page(resp):
self.relogin()
resp = self.session.get(url, **kwargs)
resp.raise_for_status()
return resp

@classmethod
def _looks_like_login_page(cls, resp: requests.Response) -> bool:
if "html" not in (resp.headers.get("Content-Type") or "").lower():
return False
text = resp.text
has_login_form = "doStandardAuthentication" in text or "cmd=force_login" in text
return has_login_form and not cls._is_logged_in(text)

@staticmethod
def _inject_credentials(
form: Any, payload: dict[str, Any], user: str, password: str
Expand Down
4 changes: 1 addition & 3 deletions src/services/calendar_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,10 @@ def __init__(
self.auth_service = auth_service

def list_events(self, seed: str) -> list[CalendarEvent]:
self.auth_service.ensure_logged_in()
url = self.settings.calendar_url(seed)

try:
resp = self.session.get(url, timeout=self.settings.timeout_seconds)
resp.raise_for_status()
resp = self.auth_service.get(url)
except requests.RequestException as exc:
raise IliasCalendarError(f"Failed to fetch calendar page: {exc}") from exc

Expand Down
6 changes: 1 addition & 5 deletions src/services/course_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,8 @@ def __init__(
self.auth_service = auth_service

def list_courses(self) -> list[Course]:
self.auth_service.ensure_logged_in()
try:
resp = self.session.get(
self.settings.memberships_url, timeout=self.settings.timeout_seconds
)
resp.raise_for_status()
resp = self.auth_service.get(self.settings.memberships_url)
except requests.RequestException as exc:
raise IliasCourseError(f"Failed to fetch memberships page: {exc}") from exc
return self._extract_courses(resp.text)
Expand Down
Loading
Loading