Moodle and WebUntis MCP
by Malte2009
README.md
# Moodle and WebUntis MCP
A single-student, read-only MCP server for Moodle. It reads the signed-in website with Chromium and exposes course material through Streamable HTTP. Moodle web services and administrator access are unnecessary.
The same endpoint reads your personal WebUntis timetable, exams, homework, inbox and student-visible class-register teaching content. The server signs in to WebUntis using its own configured credentials. WebUntis has its own session. The separate MCP password protects ChatGPT's connection to this server.
To use this server from ChatGPT, follow the [Cloudflare Tunnel deployment guide](docs/cloudflare-tunnel.md).
Moodle may record an activity view or mark a page viewed when you read it through the server, just as it does when you open it yourself. [Moodle's page view implementation](https://github.com/moodle/moodle/blob/MOODLE_405_STABLE/mod/page/lib.php#L455-L480)
## Install on an always-on Linux host
Use Python 3.12 and run the application under a dedicated unprivileged account. From the project directory:
```sh
python3.12 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
sudo .venv/bin/python -m playwright install-deps chromium
.venv/bin/python -m playwright install chromium
umask 077
cp .env.example .env
chmod 600 .env
```
Edit the private `.env` as the service account. Enter your school's Moodle origin, username and password, then set a separate `MCP_LOGIN_PASSWORD` with at least 16 characters. Set `MCP_PUBLIC_URL` to your public HTTPS URL ending in `/mcp`, and set `MOODLE_STATE_DIR` to a private persistent directory owned by that account. Anyone with access to saved session cookies can use the session. Keep this directory and the real `.env` out of source control, public web roots, images, and shared backups. The Moodle and WebUntis school credentials and the dedicated MCP password are independent.
### First login and expiry
The first course or file request opens a Moodle session. For a standard Moodle password form, leave `MOODLE_SSO_ISSUER` unset. If your school uses an external sign-in issuer, configure it only after verifying the destination on your school's real Moodle login page.
The service reuses its saved session across requests and restarts. When access expires, it attempts one automatic sign-in with the configured credentials and retries the read. A rejected password or interactive challenge returns `moodle_login_required` and suspends further automatic attempts for that process. After correcting credentials, restart the service.
For MFA or another interactive step, stop the service and run the following from its working directory as its service account, with the same environment and state directory, in a private graphical session on the host:
```sh
.venv/bin/python session.py login
```
Complete the school login in the Chromium window, wait for the session-saved message, then start the service again. On a headless host this requires a private graphical connection such as SSH with X forwarding. The public MCP endpoint never exposes a remote browser or password-entry tool.
## Set up OAuth for ChatGPT
The server includes its own single-user OAuth login. You set a dedicated MCP password in `.env`. ChatGPT signs in on a login page hosted by this server, and the server issues short-lived access tokens with refresh tokens. The Moodle and WebUntis passwords remain on the server and are used only by their respective school sessions.
### Configure the built-in login
Set these values in the private `.env`:
~~~dotenv
MCP_PUBLIC_URL=https://school-mcp.example.org/mcp
MCP_LOGIN_PASSWORD=
MCP_OAUTH_REDIRECT_URI=https://chatgpt.com/connector_platform_oauth_redirect
# Optional. If set, enter the same secret in ChatGPT's client settings.
# MCP_OAUTH_CLIENT_SECRET=replace-with-a-random-secret-of-at-least-32-characters
# Optional. Defaults to $MOODLE_STATE_DIR/.oauth
# MCP_OAUTH_STATE_DIR=/var/lib/moodle-mcp/.oauth
~~~
Choose an MCP password with at least 16 characters. Keep `.env` private with permissions such as `0600`. Do not reuse your school password. For `MCP_OAUTH_REDIRECT_URI`, the stable ChatGPT callback `https://chatgpt.com/connector_platform_oauth_redirect` is supported because the server uses RFC 9207 issuer identification. Match the exact production callback in ChatGPT's connection management page if it shows a different value. If you configure `MCP_OAUTH_CLIENT_SECRET`, use at least 32 random characters and enter the same value in ChatGPT. The server uses the fixed OAuth client ID `chatgpt`.
The OAuth store is kept under `MCP_OAUTH_STATE_DIR`, or under `$MOODLE_STATE_DIR/.oauth` by default. Keep that directory persistent and private, with permissions restricted to the service account. Back it up only as carefully as the `.env`, since it contains the OAuth database and stored token hashes. Changing `MCP_LOGIN_PASSWORD` and restarting the service invalidates existing OAuth tokens and grants. The next ChatGPT request will ask you to sign in again.
### Connect ChatGPT
1. Run the service behind Cloudflare Tunnel or another HTTPS proxy. Use the complete public MCP address, including `/mcp`, in `MCP_PUBLIC_URL`.
2. In a ChatGPT workspace with custom MCP servers enabled, add the full `MCP_PUBLIC_URL` as a custom MCP server and choose OAuth. Select manual client credentials and enter client ID `chatgpt`. If you configured `MCP_OAUTH_CLIENT_SECRET`, enter the same value there. The configured redirect URI must exactly match the production callback shown in ChatGPT's connection management page. If you changed `MCP_OAUTH_REDIRECT_URI`, restart the service before completing sign-in.
3. Complete the sign-in on the server's `/login` page using `MCP_LOGIN_PASSWORD`. Approve access to the requested read scopes. The server returns you to ChatGPT.
4. Select the connection in a chat and try “List my Moodle courses” or “What WebUntis homework is due this week?”
The server publishes authorization-server metadata at `/.well-known/oauth-authorization-server` and protected-resource metadata at `/.well-known/oauth-protected-resource/mcp`. The OAuth authorization and token endpoints are `/authorize` and `/token`. Route the whole hostname through to the app so these paths and `/mcp` all reach the server. Do not put a Cloudflare Access login page or browser challenge in front of the hostname.
### Use an external OAuth provider instead
An existing deployment can continue using an external OAuth issuer. This mode requires an issuer that supports authorization code with PKCE, publishes discovery metadata and JWKS, and issues RS256-signed JWT access tokens. Set `MCP_PUBLIC_URL`, `MCP_AUTH_ISSUER`, `MCP_AUTH_JWKS_URL`, and `MCP_AUTH_OWNER_SUBJECT`. Configure the token audience as the full MCP URL, including `/mcp`. The token must contain the relevant `moodle:read` and/or `webuntis:read` scope and the configured owner subject. Use this mode only when an external issuer is intended. Remove or comment out `MCP_LOGIN_PASSWORD`, `MCP_OAUTH_REDIRECT_URI`, and `MCP_OAUTH_CLIENT_SECRET` before configuring `MCP_AUTH_ISSUER`, `MCP_AUTH_JWKS_URL`, and `MCP_AUTH_OWNER_SUBJECT`.
OpenAI documents the stable callback and OAuth requirements in its [authentication guide](https://developers.openai.com/plugins/build/auth), with setup steps in the [ChatGPT connection guide](https://developers.openai.com/plugins/deploy/connect-chatgpt).
## Run behind HTTPS
```sh
.venv/bin/python server.py
```
For a locally terminated HTTPS deployment, a proxy must forward MCP requests and all root-level OAuth and metadata routes to the same process:
```caddyfile
moodle-mcp.example.org {
reverse_proxy 127.0.0.1:8000
}
```
Run a single server process so concurrent tools share a single Moodle login. For a persistent deployment, use a service manager with the project as the working directory. For example, on a Linux host with the project under `/opt/moodle-mcp`, an existing `moodle-mcp` service account, Chromium installed for that account, and `MOODLE_STATE_DIR=/var/lib/moodle-mcp`, this systemd unit starts the server after reboot:
```ini
[Unit]
Description=Student Moodle MCP server
After=network-online.target
[Service]
User=moodle-mcp
WorkingDirectory=/opt/moodle-mcp
ExecStart=/opt/moodle-mcp/.venv/bin/python /opt/moodle-mcp/server.py
StateDirectory=moodle-mcp
StateDirectoryMode=0700
UMask=0077
Restart=on-failure
RestartSec=10
[Install]
WantedBy=multi-user.target
```
Install the unit as `/etc/systemd/system/moodle-mcp.service`, then run `sudo systemctl daemon-reload` and `sudo systemctl enable --now moodle-mcp`. Configure DNS and the proxy for your own domain. Only the proxy needs to accept public connections.
## Reading Moodle
| Tool | Result |
| --- | --- |
| `list_courses` | Enrolled courses and their IDs |
| `read_course` | A compact outline of selectable sections |
| `read_section` | Inline headings, instructions, math, and references to activities and files |
| `read_page` | The body of a Moodle page as Markdown, including links to embedded media |
| `list_assignments` | Assignment summaries for one course or all courses |
| `read_assignment` | Instructions, visible dates, submission status and available submission details |
| `download_file` | A Moodle sign-in link for opening or saving the original file |
| `read_pdf` | One PDF page (starting at 1). Returns up to 6,000 text characters with a continuation offset, or one native image for scans. Set `render=true` to inspect diagrams and handwriting on mixed pages. |
Open a course, pass one of its section references to `read_section`, then use a returned file or activity reference to open that item. The server caps each serialized tool result at 16 KiB, including errors and encoded images. Long text includes an offset for continuing the same request. For fine detail on a PDF image, use `region` to select a quadrant (1 upper left, 2 upper right, 3 lower left, 4 lower right). Append a digit to zoom further, up to four digits. Downloading the original uses the student's Moodle browser session.
## Reading WebUntis
In your private `.env`, set `WEBUNTIS_HOST` to your school's WebUntis hostname (without a scheme or path) and `WEBUNTIS_SCHOOL` to the school identifier in the WebUntis sign-in URL. Set both `WEBUNTIS_USERNAME` and `WEBUNTIS_PASSWORD` using your WebUntis credentials. Moodle credentials are not reused automatically. The Python client uses the JSON-RPC and web endpoints documented in the [SchoolUtils client implementation](https://github.com/SchoolUtils/WebUntis/blob/51576aaeda7af7ec47c818ab22a0e434b6fcb148/src/base.ts).
| Tool | Result |
| --- | --- |
| `read_timetable` | Personal lessons in school time, with subjects, teachers, rooms and reported changes. Use `changes_only` for cancellations and other flagged changes. |
| `list_exams` | Personal exams in the requested period, with subject, time, room and available notes. |
| `list_homework` | Homework due in the requested period, with assigned date, due date, task and completion status. Set `open_only` to filter completed work. |
| `list_messages` | Private WebUntis inbox subjects and previews by sent date. Defaults to the last seven days including today. Use the returned ID to read a message. |
| `read_message` | The body of a message in the signed-in student's inbox. |
| `read_class_register` | Teaching content (*Lehrstoff*) recorded for the student's lessons. Defaults to the current Monday–Sunday week and accepts up to 31 days per request. |
Teachers can assign work in private messages, timetable notes on individual lessons (including cancellations), and class-register entries. For a general task search, check these alongside formal homework. A message date or lesson date indicates when the instructions appeared; the deadline may be different.
When a lesson omits its teacher, the server checks the signed-in student's weekly timetable. It matches the lesson number, date, and start and end times. Teacher labels follow the school's display settings and may be abbreviations.
Pass inclusive `start_date` and `end_date` values as `YYYY-MM-DD`. Timetable defaults to the next seven days including today, exams to the next 30 days including today, and homework to the current Monday–Sunday week in Europe/Berlin. The homework reader also queries the preceding seven days, removes duplicates and selects tasks whose due date falls in the requested period. WebUntis homework completion and Moodle submission status are independent.
## Verify
```sh
.venv/bin/python -m unittest discover -s tests -v
```
## License
[MIT](LICENSE)
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues