moodle-cli

module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2026 License: MIT

README

Moodle CLI

An independent Moodle command-line client for learners, educators, and administrators.
Readable terminal output for people, and a versioned contract for scripts, CI, and agents.

Verified with Moodle 4.5.12, 5.1.7, and 5.2.3 Linux, macOS, and Windows JSON contract version 1

English · 繁體中文

Getting started · Handbook · Verification dashboard · Test lab · Architecture

moodle course list
moodle calendar upcoming
moodle participant list --param courseid=42
moodle assignment submissions --param 'assignmentids=[17]'
moodle ws describe core_course_get_contents

Moodle CLI talks to the Moodle site you configure, preferring its official Web Service API and falling back to read-only AJAX or HTML adapters when a site does not expose the required function. It handles courses, participants, groups, assignments, quizzes, calendars, grades, forums, completion, academic workload, and files without pretending that every role or Moodle installation has the same capabilities.

One binary serves people and programs. Human output stays readable; --json emits a stable schema_version: 1 envelope, commands expose JSON Schema, and failures have fixed exit codes. The same use cases also back an MCP server whose write tools are absent unless explicitly enabled.

What makes it different

Sign in the way the site allows

Moodle CLI supports an existing token, Moodle username/password, login QR data, a browser session, and Moodle's mobile launch flow. On macOS and Linux desktops, press Enter to open your normal browser; the CLI receives the sign-in result automatically. macOS installs a per-user Apple Event handler on first sign-in; Linux uses a registered D-Bus handler. Institutional SSO, passkeys, and MFA remain inside the browser. Windows currently uses the manual callback method.

Browser-session import is explicit: moodle auth import-browser looks for the requested site's session in Safari on macOS, Firefox, or a Chromium-family profile. It never runs as a hidden side effect of login. Safari's cookie store is undocumented and access may be denied by macOS; it is a best-effort alternative to the manual callback, not a reason to install another browser. Firefox session snapshots and Chromium's Linux fallback encryption are supported; Chromium cookies whose keys are held by macOS Keychain, Windows DPAPI, a Linux secret service (v11), or app-bound encryption (v20) are refused with an actionable error rather than worked around.

Submit work, not merely upload it

Assignment submission follows Moodle's complete student workflow: upload files, save the submission, submit it for grading when the assignment requires that extra step, then read the state back from Moodle. A successful HTTP response is not treated as proof that the work was handed in. If the response to a write is lost and the result cannot be reconciled, the command exits 12 with an ambiguous outcome instead of guessing or sending the write again.

A contract fit for automation

moodle version --json
moodle commands --json
moodle schema assignment.submit
moodle schema assignment submit --json
moodle course list --json
moodle assignment list --current --json --fields name,due_date --no-input
moodle assignment overview --current --json  # includes each submission state
moodle quiz list --current --json              # quizzes are not inferred from calendar events
moodle ws list --version v52 --effect write --json
moodle ws describe core_course_update_courses --json
moodle ws call core_course_get_contents --params-json '{"courseid":42}'

Every JSON response uses the same versioned envelope. Stable error classes map to distinct process exit codes: success 0, internal 1, usage 2, configuration 3, authentication 4, permission 5, not found 6, validation 7, conflict 8, unavailable 9, network 10, upstream 11, and ambiguous write outcome 12. A caller's own Ctrl-C is 130, outside the table, because stopping a command is a decision rather than a way it failed. Programs branch on structured codes, never English messages.

For unattended callers, --fields keeps the payload to what is read, --no-input turns every prompt into an error instead of a hung process, and moodle schema <command> reports each command's safety (read, local or write) and idempotency with its input and output JSON Schema — what an agent needs to decide whether it may run a command. The wiki's automation recipes include rules to hand an agent.

An agent harness should reuse a working credential before attempting login. Query moodle auth methods --site school --json --no-input for site support, then choose an explicit method based on the credentials and browser access it actually has: available does not mean unattended. See choosing authentication for a harness.

The typed ws registry is generated from disposable installations of Moodle 4.5.12, 5.1.7, and 5.2.3. It currently describes a 780-function union (759/761/755 functions respectively), retaining each version's parameter and return JSON Schema, transport, effect, capability, deprecation, and external-dependency metadata. A token's actual service exposure is checked again at runtime.

Roles are capabilities, not personas

The CLI is not student-only. Moodle decides what an account may do from its system, category, course, activity, group, and override context. The same binary therefore serves site administrators, managers, course creators, editing and non-editing teachers, students, ordinary authenticated users, and custom roles. Commands do not infer authority from a role name: they inspect the functions exposed to the active credential and let Moodle enforce the relevant capability in its real context.

Read commands remain useful across roles. Reviewed high-level write commands are identified as writes in moodle commands --json, require --yes (or support --dry-run), never retry a generic write, and honor the process-wide --read-only guard. Third-party plugin functions remain available through the explicitly untyped api call escape hatch.

Deliberately conservative writes

  • api call classifies functions with a manually reviewed safety registry. A function that is not on it is treated as a write and is never retried automatically.
  • ws call, ws_read and ws_write use the effect in the generated registry instead: the type Moodle declares, a rule that makes credential-issuing functions writes, and an explicit list of functions Moodle declares read but that log a view or run plugin code (tool_mobile_get_content, core_competency_*_viewed, core_blog_view_entries, mod_lti_view_lti). --read-only and a read-only MCP session refuse those.
  • --dry-run validates typed and high-level writes and describes the plan without sending it.
  • --read-only removes write commands from the command tree.
  • moodle mcp serve and moodle mcp host are read-only by default; --allow-write must be explicit.
  • HTML fallback is read-only. If Moodle cannot prove a submission's semantics, the CLI refuses it.

Getting started

Install

# macOS or Linux, any shell — verifies the download against checksums.txt
curl -fsSL https://raw.githubusercontent.com/KoukeNeko/Moodle-CLI/main/scripts/install.sh | sh

# Windows (PowerShell)
irm https://raw.githubusercontent.com/KoukeNeko/Moodle-CLI/main/scripts/install.ps1 | iex

Or with a package manager:

# macOS or Linux (Homebrew)
brew tap KoukeNeko/tap
brew install koukeneko/tap/moodle-cli

# Windows (Scoop)
scoop bucket add koukeneko https://github.com/KoukeNeko/scoop-bucket
scoop install koukeneko/moodle-cli

# Debian, Ubuntu, Fedora, RHEL, Alpine — .deb, .rpm and .apk on the Releases page
sudo dpkg -i moodle-cli_<version>_linux_amd64.deb
moodle version
moodle shell-completion zsh > "${fpath[1]}/_moodle"   # bash, zsh, fish, powershell

The Releases page also has direct Linux, macOS and Windows archives for amd64 and arm64. The install scripts check the archive against checksums.txt and refuse a digest that does not match; if you download by hand, match it yourself. Homebrew and Scoop are updated after a stable release passes its macOS signature and notarization checks, so a newly published tag can take a few minutes to appear there. scripts/uninstall.sh and scripts/uninstall.ps1 remove what was installed, and --purge also drops configuration and stored credentials. See installation details.

Build from source

Go 1.26 or newer:

git clone https://github.com/KoukeNeko/Moodle-CLI.git
cd Moodle-CLI
make build
./bin/moodle version

Install it to ~/.local/bin:

make install

Sign in

The quickest start asks the site what it supports and lets you choose:

moodle setup https://moodle.example.edu

Or do it in steps — register a site and inspect its available login methods:

moodle site add school https://moodle.example.edu
moodle auth methods --site school
Browser sign-in (institutional SSO)

For institutional OAuth/SSO, you do not need to obtain a token first. The browser signs in to Moodle, then Moodle's mobile launch flow issues a Web Service token that the CLI stores and reuses. This is not the OAuth access token, and the CLI has no OAuth refresh token. Moodle controls its lifetime: in Moodle 5.2 a newly issued token defaults to 12 weeks (84 days), but administrators can change this. Moodle may return an existing token on sign-in, so neither signing in again nor calling the API resets its expiry. The CLI does not currently report an expiry date; eCourse2's actual token expiry was not returned by the APIs checked. Sign in again if it expires or is revoked. See token lifetime and signing in again. If the site disables mobile web services, OAuth cannot yield a Web Service token; import a browser session for the supported read-only features instead.

On macOS, browser sign-in installs its callback handler automatically. Press Enter, complete SSO in your browser, and the CLI verifies and stores the returned token:

moodle auth login --site school --method mobilelaunch

For a Linux desktop, install the callback handler once and let the normal browser complete SSO:

moodle auth register-handler
moodle auth login --site school --method mobilelaunch

On Windows, use the manual callback method below for the same browser OAuth/SSO flow. If the browser does not expose the callback URL, explicitly import its session with moodle auth import-browser --site school --store; that session is not converted into a Web Service token.

If the browser exposes the callback URL to copy, the manual flow needs no registered desktop handler:

moodle auth login --site school --method manual
Other login methods

Choose --method token only when you already have a Web Service token. In a terminal, it prompts with hidden input so the token need not appear in argv. Examples of the explicit methods:

printf '%s' "$TOKEN" | moodle auth login --site school --token-stdin
printf '%s' "$PASSWORD" | moodle auth login --site school \
  --method password --username student --password-stdin
moodle auth import-browser --site school --list-profiles
moodle auth import-browser --site school --store
# On macOS, first try Safari's saved cookie store:
moodle auth import-browser --site school --browser safari --store
# If Safari is signed in but its session is absent from that file, use the
# hidden-input prompt after copying MoodleSession's value in Web Inspector:
moodle auth import-session --site school
Where credentials are kept

Credentials are kept in the operating-system keychain. Configuration stores site and account metadata, never tokens or browser sessions. For an ephemeral CI run, use MOODLE_WS_TOKEN or MOODLE_SESSION instead of persisting a credential. Where there is no keychain at all, opt into a 0600 file with --credential-store file:

moodle --credential-store file auth login --site school --token-stdin

Everyday commands

moodle doctor                         # explain what this account can do
moodle course list                    # enrolled courses
moodle calendar upcoming              # overdue and upcoming work
moodle grade overview                 # course totals
moodle grade list --course 2          # one course's gradebook

moodle assignment list
moodle assignment overview             # all assignments and your submission states
moodle assignment show 42             # IDs and pasted Moodle URLs both work
moodle assignment status 42
moodle quiz list                       # visible quizzes, even without calendar events
moodle quiz show 31                    # settings and attempts visible to this account
moodle assignment submit 42 report.pdf --dry-run
moodle assignment submit 42 report.pdf --yes
moodle assignment submit 42 report.pdf --draft --yes

moodle forum list
moodle forum discussions 7
moodle forum read 19
moodle file download 'https://moodle.example.edu/pluginfile.php/...'
moodle resolve 'https://moodle.example.edu/mod/assign/view.php?id=42'

moodle participant list --param courseid=2
moodle enrolment methods --param courseid=2
moodle enrolment add --params-json '{"enrolments":[{"roleid":5,"userid":7,"courseid":2}]}' --dry-run
moodle group create --params-json '{"groups":[{"courseid":2,"name":"Lab A"}]}' --dry-run
moodle assignment submissions --param 'assignmentids=[42]'
moodle workload validate --require-minimum

moodle ws list --version v52 --component mod_assign
moodle ws describe mod_assign_save_grade
moodle ws call core_enrol_get_users_courses --param userid=4
moodle api call local_example_function --params-json '{}'  # third-party/unregistered
moodle mcp serve                      # read-only tools
moodle mcp serve --allow-write        # opt in to write tools
moodle mcp host                       # serve a Claude connector; starts a public Cloudflare quick tunnel
moodle mcp host --public-url https://moodle-mcp.example.com   # ...or at an address of your own

Run moodle <command> --help, use the generated complete command reference, or inspect all 780 core functions in feature coverage.

Claude without the CLI on your machine

moodle mcp serve needs Claude to start a program on the same machine. Claude on the web, on a phone, and in Cowork reaches tools through connectors added by URL instead, so moodle mcp host serves the same tools over HTTPS. In Claude it is a custom connector: a remote MCP server that Claude reaches from Anthropic's servers. With cloudflared installed, moodle mcp host starts a Cloudflare quick tunnel itself and prints a connector URL to add under Customize > Connectors; for an address that stays, put the host behind a tunnel or proxy with HTTPS and pass it as --public-url. The host serves the sign-in page and asks for a passphrase only you know. See Claude connector.

Security boundary

This program reads credentials and connects to a server, so its boundary should be explicit:

  • It contacts only the Moodle site configured for the active profile. The exceptions are mcp host without --public-url, which also runs cloudflared, and that talks to Cloudflare, and the release check below.
  • It accesses only credentials stored under Moodle CLI's own keychain entries. A machine with no keychain — headless Linux, SSH, WSL, a container — can opt into a 0600 file with --credential-store file; nothing falls back to a file on its own.
  • Browser import reads the selected browser profile only after an explicit command, returns or stores only the named site's cookie, and never logs it.
  • auth logout removes the local credential but does not revoke the Moodle token, because the same token may also belong to Moodle's mobile app.
  • Only mcp host accepts network connections. It listens on loopback unless --listen says otherwise (a quick tunnel requires loopback), admits a client only after you enter its passphrase, and keeps sign-ins in memory until it stops. Without --public-url it starts a cloudflared quick tunnel, and anyone who has the address can reach the sign-in page until it stops; Cloudflare relays the traffic.
  • At an interactive terminal it asks github.com, at most once a day, whether a newer release exists, and says so on stderr. It downloads and installs nothing. The request is a HEAD for the repository's "latest release" link and carries the program's name and version; GitHub sees that and the address it came from. It never runs with --json, --no-input, or mcp, when stderr is not a terminal, when CI is set, or in a development build, and MOODLE_CLI_NO_UPDATE_CHECK=1 turns it off.
  • It has no telemetry, self-update, privilege escalation, process injection, or credential export.

See the security model for the full threat boundary and callback design.

Compatibility

COMPATIBILITY.md is the full matrix: which Moodle versions, platforms, login methods and credential stores are verified, which are expected to work, and which are untested — each with its evidence. The summary:

The full Docker-backed suite is verified against exactly these versions:

Moodle Verified version Scenario
4.5 LTS 4.5.12 standard site, restricted Web Service site, ten academic years
5.1 5.1.7 standard site, restricted Web Service site, ten academic years
5.2 5.2.3 standard site, restricted Web Service site, ten academic years

The small decade scenario creates 10 yearly cohorts, 30 students, 20 assignments, 60 submissions, eight archived courses, two active courses, calendar events, missing grades, zero grades, drafts, submitted work, overdue work, and cross-year convergence. It is intended to catch assumptions that only work on a fresh demonstration site.

The separate PostgreSQL scale profile creates 50,000 synthetic students, 1,000 academic course instances across 20 terms, a 50,000-participant orientation course, and 2.37 million enrolment facts. SQL control-plane assertions independently verify 21 undergraduate credits and 6 graduate credits per term; the CLI then reads representative workloads and all 50 participant pages while recording latency, peak RSS, HTTP requests, and disk use. The scale container has no public egress after its image bootstrap completes. Moodle 5.2.3 requires PostgreSQL 16, so the profile uses that minimum instead of bypassing Moodle's environment check.

Release builds target Linux, macOS, and Windows on amd64 and arm64. macOS and Linux have an automatic browser callback handler; Windows uses the manual callback method. The CLI and manual authentication paths build and test on all three operating systems.

Development

make test
make test-race
make lint
make verify

make moodle-up V=v52
make moodle-decade V=v52
make moodle-matrix V=v52
make moodle-scale V=v52
make moodle-down V=v52

The package boundaries are enforced by architecture tests. Feature packages own their interfaces; the moodle and webread packages are adapters; bootstrap is only the composition root; CLI and MCP never reach into HTTP directly. See docs/architecture.md and the development handbook.

Project status

The project is under active development. The release workflow is configured to produce checksummed archives and SBOMs, sign and notarize both macOS binaries with Developer ID, verify them on a real macOS runner before publication, sign the checksums with a keyless workflow signature, and update the public Homebrew tap and Scoop bucket. Check the release history for the latest published version. Windows Authenticode signing is not configured, so Windows may display a SmartScreen warning.

CI status Go 1.26 or newer MIT license

License and trademarks

MIT © 2026 KoukeNeko.

Moodle CLI is an independent project. It is not affiliated with, endorsed by, or sponsored by Moodle or Moodle HQ. “Moodle” is a trademark of Moodle Pty Ltd. No Moodle source code is included.

Directories

Path Synopsis
cmd
moodle command
Command moodle is the Moodle client for students, scripts and agents.
Command moodle is the Moodle client for students, scripts and agents.
internal
api
Package api is the escape hatch: calling a web service function directly.
Package api is the escape hatch: calling a web service function directly.
assignment
Package assignment covers reading assignments and handing work in.
Package assignment covers reading assignments and handing work in.
auth
Package auth turns a configured account into a usable session.
Package auth turns a configured account into a usable session.
authmethod/browsersession
Package browsersession signs in with a session a browser already holds.
Package browsersession signs in with a session a browser already holds.
authmethod/manual
Package manual signs in by having the user complete the browser login and paste the callback URL back.
Package manual signs in by having the user complete the browser login and paste the callback URL back.
authmethod/mobilelaunch
Package mobilelaunch signs in through the browser the user already uses.
Package mobilelaunch signs in through the browser the user already uses.
authmethod/password
Package password signs in with a Moodle username and password.
Package password signs in with a Moodle username and password.
authmethod/qrlogin
Package qrlogin signs in with the QR code Moodle shows in a user's profile.
Package qrlogin signs in with the QR code Moodle shows in a user's profile.
authmethod/token
Package token signs in with a web service token the user already holds.
Package token signs in with a web service token the user already holds.
bootstrap
Package bootstrap is the composition root: it builds every concrete dependency and wires them together.
Package bootstrap is the composition root: it builds every concrete dependency and wires them together.
browser
Package browser reads a Moodle session out of a browser's own storage.
Package browser reads a Moodle session out of a browser's own storage.
calendar
Package calendar is the deadline and to-do use cases.
Package calendar is the deadline and to-do use cases.
callback
Package callback holds the state of a browser login while it is happening.
Package callback holds the state of a browser login while it is happening.
cli
Package cli is the Cobra presentation layer: it turns arguments into use case input, and use case results into output.
Package cli is the Cobra presentation layer: it turns arguments into use case input, and use case results into output.
config
Package config reads and writes the on-disk configuration.
Package config reads and writes the on-disk configuration.
contract/v1
Package v1 is the only public machine-readable representation of this tool.
Package v1 is the only public machine-readable representation of this tool.
course
Package course is the course use cases and their model.
Package course is the course use cases and their model.
doctor
Package doctor diagnoses a site and account.
Package doctor diagnoses a site and account.
errs
Package errs holds the error vocabulary shared by every layer: the stable error Code, the open-ended Reason, and the execution Outcome.
Package errs holds the error vocabulary shared by every layer: the stable error Code, the open-ended Reason, and the execution Outcome.
file
Package file covers the files Moodle hands out and getting them onto disk.
Package file covers the files Moodle hands out and getting them onto disk.
forum
Package forum reads course discussions.
Package forum reads course discussions.
grade
Package grade is the grade use cases and their model.
Package grade is the grade use cases and their model.
mcp
Package mcp serves the use cases to an AI agent over the Model Context Protocol.
Package mcp serves the use cases to an AI agent over the Model Context Protocol.
mcphost
Package mcphost lets a client that is not on this machine use the MCP server.
Package mcphost lets a client that is not on this machine use the MCP server.
moodle
Package moodle speaks Moodle's web service protocol.
Package moodle speaks Moodle's web service protocol.
quiz
Package quiz reads quizzes and the caller's attempts at them.
Package quiz reads quizzes and the caller's attempts at them.
safety
Package safety decides what a call may do and whether it may be repeated.
Package safety decides what a call may do and whether it may be repeated.
secret
Package secret stores credentials in the operating system's keychain.
Package secret stores credentials in the operating system's keychain.
site
Package site holds the core vocabulary: which Moodle we are talking to, as whom, and what that combination can actually do.
Package site holds the core vocabulary: which Moodle we are talking to, as whom, and what that combination can actually do.
tunnel
Package tunnel gives a local address a public HTTPS one by running cloudflared's account-less quick tunnel.
Package tunnel gives a local address a public HTTPS one by running cloudflared's account-less quick tunnel.
update
Package update tells a person when a newer release exists.
Package update tells a person when a newer release exists.
webread
Package webread reads Moodle's own pages.
Package webread reads Moodle's own pages.
workload
Package workload calculates academic credits from institution-mapped Moodle course custom fields.
Package workload calculates academic credits from institution-mapped Moodle course custom fields.
wsregistry
Package wsregistry owns the typed contract for Moodle core external functions across the supported Moodle releases.
Package wsregistry owns the typed contract for Moodle core external functions across the supported Moodle releases.
tests
testmoodle
Package testmoodle is a programmable stand-in for a Moodle site.
Package testmoodle is a programmable stand-in for a Moodle site.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL