Перейти к содержанию

hse-lms-mcp for AI agents

One page holding everything a coding assistant needs to use hse-lms-mcp correctly, plus a map of where the rest of the documentation keeps the details it leaves out. Give an agent this page rather than the whole site.

Package hse-lms-mcp on PyPI, import root hse_lms
Requires Python 3.10+
Install pip install hse-lms-mcp (or uv tool install hse-lms-mcp for the CLI)
Console scripts hse-lms (CLI), hse-lms-mcp (MCP server)
Source https://github.com/AlexeyShalaev/hse-lms-mcp

How to read this page

Every page of this site is also served as raw Markdown at its own URL with .md in place of the trailing slash — this page is /agents.md, the quick start is /guide/quickstart.md. The API reference is the exception: read it as HTML or read the docstrings in the source.

Rules that hold or break the code is where correctness lives. Every name below is in the public API; do not guess methods that sound plausible.

Scope

It does read one user's own account in HSE SmartLMS (https://edu.hse.ru, a Moodle 4 instance behind HSE's Keycloak SSO): enrolled courses, course sections and modules, calendar deadlines across all courses, activity details (assignment status and feedback, page text, url targets, quiz info, folder files), the user's grade report, forum posts, file downloads. It can submit files to an assignment when writes are explicitly enabled. It ships as a Python SDK, a CLI and an MCP server (stdio or streamable HTTP with a bearer token).

It does not work with other Moodle sites, other universities or other people's accounts; it has no teacher or admin features (grading, editing courses, enrolment); it does not start quiz attempts, post to forums, send messages, replace or delete an existing submission, or press a separate "Submit for grading" button; it does not use the Moodle REST/mobile web-service token (HSE does not issue one). There is no async API. It is unofficial and not affiliated with HSE.

Mental model

  • Lms is a client bound to one account. It holds an httpx.Client, a cookie jar and the Moodle sesskey. Calls are serialized by a lock and rate-limited (min_interval, 0.7 s by default).
  • Login is lazy: the first call makes sure there is a live session. Order: saved or given cookie, then silent SSO renewal through Keycloak, then the password, once. login() does the same explicitly.
  • Ids: course_id (from courses()), cmid = course module id, the id= of /mod/<type>/view.php. module() needs the module type, which course() and deadlines() return.
  • Everything returns pydantic models from hse_lms.models (re-exported at the root).

Wiring

from hse_lms import Lms

with Lms() as lms:  # credentials from env, keyring or ~/.config/hse-lms
    for d in lms.deadlines(days_ahead=14):
        print(d.due.isoformat(), d.course, d.name, d.cmid, d.type)

    contents = lms.course(12345)
    for section in contents.sections:
        for m in section.modules:
            if m.type == "assign":
                detail = lms.module(m.cmid, m.type)
                if detail.submission:
                    print(detail.title, detail.submission.submitted, detail.submission.rows)

API

Lms(*, cookie=None, username=None, password=None, session_file=True, allow_password=True, allow_write=False, use_keyring=True, min_interval=0.7, timeout=30.0, timezone="Europe/Moscow", transport=None)

Argument Meaning
cookie MoodleSession value or a name=value; ... header from the browser
username, password override env, keyring and credentials.json
session_file True = <config dir>/session.json, a path, or None/False = memory only
allow_password False = only a live session or SSO renewal, never the password
allow_write must be True for submit_assignment
timezone IANA zone of every returned datetime
transport an httpx.BaseTransport, e.g. httpx.MockTransport in tests
Method Arguments Returns
login password_prompt: Callable[[str], str \| None] \| None = None SessionInfo(userid, login_path); login_path is session, sso or password
whoami SessionInfo
courses classification="inprogress" (all, future, past, favourites, hidden) list[Course]
course course_id: int, include_text=False CourseContents(course_id, sections: list[Section]); Section.modules: list[Module]
deadlines days_back=0, days_ahead=60, limit=50 list[Deadline] (due, course, cmid, type, actionable, overdue)
module cmid: int, type: str \| None = None ModuleDetail (title, dates, description, files, submission, text, target_url, quiz_info)
assignment cmid: int ModuleDetail with submission: SubmissionStatus
grades course_id: int list[GradeItem] (name, type, cmid, grade, range, percentage, feedback)
forum cmid: int, limit=10, posts_per_discussion=20 list[Discussion] with posts: list[Post]
read_file target: str \| int (pluginfile URL or resource cmid) tuple[str, bytes] (name, content)
download target: str \| int, dest_dir: Path \| str = "." Path of the saved file
submit_assignment cmid: int, files: Iterable[Path \| str \| tuple[str, bytes]] SubmitResult(cmid, uploaded, verified, status)
course_state course_id: int raw core_courseformat_get_state dict
ajax method: str, args: dict raw data of a Moodle AJAX call
get path: str httpx.Response of an edu.hse.ru page
close closes the HTTP pool; Lms is also a context manager

SubmissionStatus fields: submitted, graded, rows: dict[str, str] (the status table as shown, language varies), files: list[FileRef], feedback, can_edit, needs_final_submit.

MCP tools (server hse-lms-mcp): whoami, list_courses, get_course, get_deadlines, get_module, get_grades, get_forum, download_file and, only with HSE_LMS_ALLOW_SUBMIT=1 or --allow-submit, submit_assignment(cmid, file_paths?, files?) where files items are {name, content_base64}.

Rules that hold or break the code

  1. One account per Lms and per MCP server process. Do not build a shared service that collects other people's HSE passwords.
  2. The password is tried once per process. After a LoginError from a rejected password the client refuses to try again (Keycloak locks accounts). Fix the credentials and start a new process; do not loop on login().
  3. module(cmid) without type works only for modules this client already saw in course(). From a fresh client pass type, which course() and deadlines() give.
  4. Writes are opt-in: Lms(allow_write=True). submit_assignment refuses an assignment that already has submitted files and raises if a file does not come back with the same SHA-256. Confirm with the user before calling it.
  5. If submission.needs_final_submit is True after submitting, the assignment wants a separate "Submit for grading" press; the library does not do it.
  6. rows, dates and titles are the LMS's own text, in Russian or English depending on the course. Use the boolean fields (submitted, graded, can_edit) for logic.
  7. download and read_file accept only https://edu.hse.ru URLs; any redirect to another host, http or another port raises UnsafeRedirectError.
  8. Do not lower min_interval to scrape faster; the LMS is shared infrastructure.

Common mistakes

# WRONG: the module type is not optional on a fresh client
Lms().module(67890)          # ValueError: module type unknown

# RIGHT: take the type from deadlines() or course()
lms = Lms()
d = lms.deadlines()[0]
lms.module(d.cmid, d.type)
# WRONG: submitting with a read-only client
Lms().submit_assignment(cmid, ["report.pdf"])        # WriteNotAllowedError

# RIGHT
with Lms(allow_write=True) as lms:
    result = lms.submit_assignment(cmid, ["report.pdf"])
    assert result.verified == ["report.pdf"]
# WRONG: parsing status text
if detail.submission.rows["Submission status"] == "Submitted for grading": ...

# RIGHT
if detail.submission and detail.submission.submitted: ...

Errors

All inherit from hse_lms.LmsError.

Exception Meaning What to do
SessionExpiredError session dead and no way to log in (no credentials, or allow_password=False) pass a fresh cookie or credentials
LoginError password rejected, second factor or captcha, unknown login page stop and tell the user; do not retry
UnsafeRedirectError a URL or redirect left edu.hse.ru / saml.hse.ru do not follow it; report
MethodNotAvailableError the AJAX method is not exposed to browser sessions use another method or an HTML page
WriteNotAllowedError write called on a read-only client create the client with allow_write=True
SubmissionError Moodle refused the upload or form, or verification failed show the message to the user

ValueError is raised for bad arguments: unknown module type, a page with several files, no files to submit.

Documentation map

Page Read it when
Quick start first install, login, CLI and MCP connection
Client setup MCP config for Claude Code, Claude Desktop, Codex, OpenCode, oh-my-pi, Cursor, VS Code, Zed, Gemini CLI
Configuration credentials order, environment variables, files on disk
Advanced running the MCP server on your own host, submissions, the login chain
API reference an exact signature or docstring — HTML only
Changelog what changed between versions