fit-lms-mcp 2.0.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -2
- package/dist/config/env.js +11 -0
- package/dist/mcp/server.js +6 -0
- package/dist/mcp/tools/get-my-courses.js +7 -8
- package/dist/moodle/api/assignment-detail.js +103 -0
- package/dist/moodle/api/course-announcements.js +84 -0
- package/dist/moodle/api/material-detail.js +105 -0
- package/dist/moodle/assignment-url.js +2 -1
- package/dist/moodle/client.js +31 -9
- package/dist/moodle/html.js +14 -1
- package/dist/services/assignment.service.js +8 -0
- package/dist/services/course-content.service.js +32 -0
- package/dist/services/course-metadata-cache.js +77 -0
- package/dist/tools/GetAssignmentDetailTool.js +20 -0
- package/dist/tools/GetCourseAnnouncementsTool.js +21 -0
- package/dist/tools/GetCourseContentsTool.js +9 -3
- package/dist/tools/GetMaterialDetailTool.js +21 -0
- package/package.json +1 -1
- package/scripts/setup.mjs +23 -5
package/README.md
CHANGED
|
@@ -51,6 +51,7 @@ For use via `npx`, create `~/.fit-lms-mcp/.env` with the settings below and rest
|
|
|
51
51
|
| `LMS_USERNAME` | Student ID / username for automatic login (Option 1 - Recommended) |
|
|
52
52
|
| `LMS_PASSWORD` | Password for automatic login (Option 1; automatically logs in and refreshes expired sessions) |
|
|
53
53
|
| `TIMEOUT_MS` | Optional request timeout in milliseconds (default: `5000`, maximum: `2147483647`) |
|
|
54
|
+
| `LMS_CACHE_TTL_MS` | Optional course metadata cache lifetime in milliseconds (default `900000`, maximum `2147483647`, `0` disables caching) |
|
|
54
55
|
| `LMS_MOODLE_SESSION` | MoodleSession cookie value (Option 2 - Manual legacy session) |
|
|
55
56
|
| `LMS_MOODLE_SESSKEY` | sesskey query parameter from the same session (Option 2 - Manual legacy session) |
|
|
56
57
|
|
|
@@ -190,10 +191,17 @@ For OpenCode, use these values as a single command array. For Codex, use them as
|
|
|
190
191
|
|
|
191
192
|
| Tool | Input | Output |
|
|
192
193
|
| :--- | :--- | :--- |
|
|
193
|
-
| `get_my_courses` | Optional `classification
|
|
194
|
+
| `get_my_courses` | Optional `classification` (`all` by default, `inprogress`, `future`, `past`) and optional boolean `bypassCache` | Enrolled courses with ID, course name, short name, start/end dates, progress percentage, and LMS URL |
|
|
194
195
|
| `get_course_assignments` | Required positive integer `courseId` | List of visible assignments in the course with module ID, name, course ID, course name, and view link |
|
|
196
|
+
| `get_assignment_detail` | Required positive integer `courseModuleId` | Detailed assignment information: prompt instructions, submission status (*Submitted for grading*, *Draft*, *No submission*), grading status, due date, time remaining, last modified, and cutoff date |
|
|
195
197
|
| `get_upcoming_deadlines` | Optional `daysAhead` (1–365, default **7**), `includePast` (default false), `from`, `to`, `courseId` | Due events sorted in ascending order by due date, with verified course module ID and direct submission link |
|
|
196
|
-
| `get_course_contents` | Required positive integer `courseId` | Course sections, module structure, activity titles, and resource metadata (excludes hidden/restricted items) |
|
|
198
|
+
| `get_course_contents` | Required positive integer `courseId` and optional boolean `bypassCache` | Course sections, module structure, activity titles, and resource metadata (excludes hidden/restricted items) |
|
|
199
|
+
| `get_course_announcements` | Required positive integer `courseId`, optional zero-based `page` (default **0**) | Up to 10 visible announcements in Moodle forum order, with title, message text, discussion link, and author and timestamp when available |
|
|
200
|
+
| `get_material_detail` | Required positive integers `courseId` and `courseModuleId` from `get_course_contents` | Name, type, Moodle link, and available details for File, Folder, Page, and URL modules, including file names and links, page text, or the destination URL |
|
|
201
|
+
|
|
202
|
+
Moodle may log the activity view or apply its view-based completion settings when the server reads an announcement forum or material page. Material lookups read metadata and page text without downloading files or opening external destinations.
|
|
203
|
+
|
|
204
|
+
Course lists and course contents are cached in memory for 15 minutes by default. Pass `bypassCache: true` to refresh from Moodle immediately after an enrollment or material change. Deadlines, submission status, announcements, and material details are fetched live.
|
|
197
205
|
|
|
198
206
|
### Tool Argument Examples
|
|
199
207
|
|
|
@@ -205,6 +213,10 @@ For OpenCode, use these values as a single command array. For Codex, use them as
|
|
|
205
213
|
```json
|
|
206
214
|
{}
|
|
207
215
|
```
|
|
216
|
+
- Get detailed submission status and instructions for an assignment:
|
|
217
|
+
```json
|
|
218
|
+
{ "courseModuleId": 42 }
|
|
219
|
+
```
|
|
208
220
|
- Deadlines for the next 14 days for a specific course:
|
|
209
221
|
```json
|
|
210
222
|
{ "courseId": 660, "daysAhead": 14 }
|
|
@@ -225,6 +237,8 @@ Once connected to your AI assistant, you can ask:
|
|
|
225
237
|
- "List my enrolled courses on HANU FIT LMS."
|
|
226
238
|
- "Show all assignments and upcoming deadlines for the next 7 days."
|
|
227
239
|
- "What topics and materials are in course 660?"
|
|
240
|
+
- "Show the announcements for course 660."
|
|
241
|
+
- "Open the details of the exam guide listed in course 660."
|
|
228
242
|
|
|
229
243
|
---
|
|
230
244
|
|
|
@@ -277,6 +291,8 @@ Version 2.0.0 requires Node.js 22 or later; Node.js 18 and 20 are no longer supp
|
|
|
277
291
|
|
|
278
292
|
The `publish.yml` workflow publishes on a `v*` Git tag push or a manual workflow run. Creating a GitHub Release does not trigger a second publish. Update `package.json` and `package-lock.json` before tagging a release, and make the tag match the package version (for example, `v2.0.0`). Published npm versions cannot be reused, even after unpublishing.
|
|
279
293
|
|
|
294
|
+
For manual runs, the `tag` input selects the npm distribution channel: `latest`, `beta`, or `next`. To publish the stable version `2.0.0` from `package.json`, select `latest`. The package version (`2.0.0`), Git tag (`v2.0.0`), and npm channel (`latest`) are separate values.
|
|
295
|
+
|
|
280
296
|
Publishing uses npm trusted publishing (OIDC) from a GitHub-hosted runner with Node.js 24 and npm 11. No `NPM_TOKEN` secret is required. Configure the package's Trusted Publisher on npm with:
|
|
281
297
|
|
|
282
298
|
- **Organization or user:** `DwaftPainter`
|
package/dist/config/env.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { isSafeCookieValue, isSafeSesskey } from "../moodle/auth/credentials.js";
|
|
2
|
+
export const DEFAULT_COURSE_CACHE_TTL_MS = 15 * 60 * 1000;
|
|
2
3
|
export function loadConfig(env = process.env) {
|
|
3
4
|
const errors = [];
|
|
4
5
|
const rawBaseUrl = env.LMS_BASE_URL?.trim();
|
|
@@ -71,10 +72,20 @@ export function loadConfig(env = process.env) {
|
|
|
71
72
|
if (!/^\d+$/.test(rawTimeout) || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) {
|
|
72
73
|
errors.push("TIMEOUT_MS must be a positive integer in milliseconds, at most 2147483647");
|
|
73
74
|
}
|
|
75
|
+
const rawCacheTtl = env.LMS_CACHE_TTL_MS?.trim();
|
|
76
|
+
let cacheTtlMs;
|
|
77
|
+
if (rawCacheTtl) {
|
|
78
|
+
cacheTtlMs = Number(rawCacheTtl);
|
|
79
|
+
if (!/^\d+$/.test(rawCacheTtl) || !Number.isSafeInteger(cacheTtlMs) || cacheTtlMs > 2147483647) {
|
|
80
|
+
errors.push("LMS_CACHE_TTL_MS must be an integer in milliseconds between 0 and 2147483647");
|
|
81
|
+
}
|
|
82
|
+
}
|
|
74
83
|
if (errors.length) {
|
|
75
84
|
throw new Error(`Invalid LMS configuration:\n- ${errors.join("\n- ")}`);
|
|
76
85
|
}
|
|
77
86
|
const config = { baseUrl, timeoutMs };
|
|
87
|
+
if (cacheTtlMs !== undefined)
|
|
88
|
+
config.cacheTtlMs = cacheTtlMs;
|
|
78
89
|
if (moodleSession !== undefined)
|
|
79
90
|
config.moodleSession = moodleSession;
|
|
80
91
|
if (moodleSesskey !== undefined)
|
package/dist/mcp/server.js
CHANGED
|
@@ -5,6 +5,9 @@ import AssignmentsTool from "../tools/AssignmentsTool.js";
|
|
|
5
5
|
import GetCourseAssignmentsTool from "../tools/GetCourseAssignmentsTool.js";
|
|
6
6
|
import GetUpcomingDeadlinesTool from "../tools/GetUpcomingDeadlinesTool.js";
|
|
7
7
|
import GetCourseContentsTool from "../tools/GetCourseContentsTool.js";
|
|
8
|
+
import GetAssignmentDetailTool from "../tools/GetAssignmentDetailTool.js";
|
|
9
|
+
import GetCourseAnnouncementsTool from "../tools/GetCourseAnnouncementsTool.js";
|
|
10
|
+
import GetMaterialDetailTool from "../tools/GetMaterialDetailTool.js";
|
|
8
11
|
export function createServer(config) {
|
|
9
12
|
const server = new MCPServer({
|
|
10
13
|
name: "hanu-lms-mcp",
|
|
@@ -17,6 +20,9 @@ export function createServer(config) {
|
|
|
17
20
|
server.addTool(GetCourseAssignmentsTool);
|
|
18
21
|
server.addTool(GetUpcomingDeadlinesTool);
|
|
19
22
|
server.addTool(GetCourseContentsTool);
|
|
23
|
+
server.addTool(GetAssignmentDetailTool);
|
|
24
|
+
server.addTool(GetCourseAnnouncementsTool);
|
|
25
|
+
server.addTool(GetMaterialDetailTool);
|
|
20
26
|
return server;
|
|
21
27
|
}
|
|
22
28
|
export default createServer;
|
|
@@ -3,6 +3,7 @@ import { z } from "zod";
|
|
|
3
3
|
import { loadConfig } from "../../config/env.js";
|
|
4
4
|
import { getAuthProvider } from "../../moodle/auth/provider-factory.js";
|
|
5
5
|
import { MoodleClient } from "../../moodle/client.js";
|
|
6
|
+
import { getCourseMetadataCache } from "../../services/course-metadata-cache.js";
|
|
6
7
|
import { CourseService } from "../../services/course.service.js";
|
|
7
8
|
const schema = z.object({
|
|
8
9
|
classification: z
|
|
@@ -10,6 +11,7 @@ const schema = z.object({
|
|
|
10
11
|
.optional()
|
|
11
12
|
.default("all")
|
|
12
13
|
.describe("Filter courses by timeline classification (default: 'all')"),
|
|
14
|
+
bypassCache: z.boolean().optional().describe("Fetch a fresh course list from Moodle"),
|
|
13
15
|
});
|
|
14
16
|
export class GetMyCoursesTool extends MCPTool {
|
|
15
17
|
name = "get_my_courses";
|
|
@@ -18,14 +20,11 @@ export class GetMyCoursesTool extends MCPTool {
|
|
|
18
20
|
schema = schema;
|
|
19
21
|
async execute(input) {
|
|
20
22
|
const config = loadConfig();
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
baseUrl: config.baseUrl,
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
});
|
|
27
|
-
const courseService = new CourseService(client);
|
|
28
|
-
return await courseService.getMyCourses(input.classification ?? "all");
|
|
23
|
+
const classification = input.classification ?? "all";
|
|
24
|
+
return getCourseMetadataCache(config).courses.getOrLoad(classification, () => {
|
|
25
|
+
const client = new MoodleClient({ baseUrl: config.baseUrl, authProvider: getAuthProvider(config), timeoutMs: config.timeoutMs });
|
|
26
|
+
return new CourseService(client).getMyCourses(classification);
|
|
27
|
+
}, input.bypassCache);
|
|
29
28
|
}
|
|
30
29
|
}
|
|
31
30
|
export default GetMyCoursesTool;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { parse } from "parse5";
|
|
2
|
+
import { MoodleAuthError, MoodleError } from "../errors.js";
|
|
3
|
+
import { attr, elements, hasClass, isHidden, textContent } from "../html.js";
|
|
4
|
+
const HANU_MOODLE_OFFSET = "+07:00";
|
|
5
|
+
const ISO_LOCAL_DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/i;
|
|
6
|
+
const MOODLE_LOCAL_DATE_TIME = /^(?:[a-z]+,\s+)?\d{1,2}\s+[a-z]+\s+\d{4},?\s+\d{1,2}:\d{2}(?::\d{2})?(?:\s*[ap]m)?$/i;
|
|
7
|
+
function normalizeDate(raw) {
|
|
8
|
+
// Interpret timezone-less Moodle dates in the observed HANU LMS timezone.
|
|
9
|
+
let date = raw;
|
|
10
|
+
if (ISO_LOCAL_DATE_TIME.test(raw)) {
|
|
11
|
+
date = `${raw}${HANU_MOODLE_OFFSET}`;
|
|
12
|
+
}
|
|
13
|
+
else if (MOODLE_LOCAL_DATE_TIME.test(raw)) {
|
|
14
|
+
date = `${raw} GMT${HANU_MOODLE_OFFSET}`;
|
|
15
|
+
}
|
|
16
|
+
const timestamp = Date.parse(date);
|
|
17
|
+
return Number.isNaN(timestamp) ? raw : new Date(timestamp).toISOString();
|
|
18
|
+
}
|
|
19
|
+
export function parseAssignmentDetail(html, baseUrl, courseModuleId) {
|
|
20
|
+
const all = elements(parse(html));
|
|
21
|
+
const body = all.find(element => element.tagName === "body");
|
|
22
|
+
if (body && attr(body, "id") === "page-login-index") {
|
|
23
|
+
throw new MoodleAuthError("Moodle returned the login page; refresh the session credentials");
|
|
24
|
+
}
|
|
25
|
+
const main = all.find(element => attr(element, "id") === "region-main") ??
|
|
26
|
+
all.find(element => attr(element, "role") === "main");
|
|
27
|
+
if (!body || !/^page-mod-assign-view(?:-[a-z0-9_-]+)?$/.test(attr(body, "id") ?? "") || !main) {
|
|
28
|
+
throw new MoodleError("Unrecognized Moodle assignment page", "MOODLE_RESPONSE_ERROR");
|
|
29
|
+
}
|
|
30
|
+
const content = elements(main);
|
|
31
|
+
if (content.some(element => hasClass(element, "errorbox") || hasClass(element, "errorcode"))) {
|
|
32
|
+
throw new MoodleError("Unexpected Moodle assignment page error", "MOODLE_RESPONSE_ERROR");
|
|
33
|
+
}
|
|
34
|
+
// 1. Extract assignment title / name
|
|
35
|
+
const titleElement = content.find(element => (element.tagName === "h2" || element.tagName === "h1") &&
|
|
36
|
+
!hasClass(element, "accesshide") &&
|
|
37
|
+
!isHidden(element));
|
|
38
|
+
let name = "";
|
|
39
|
+
if (titleElement) {
|
|
40
|
+
const small = elements(titleElement).find(e => e.tagName === "small" && !isHidden(e));
|
|
41
|
+
if (small) {
|
|
42
|
+
name = textContent(small);
|
|
43
|
+
}
|
|
44
|
+
if (!name) {
|
|
45
|
+
name = textContent(titleElement);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (!name) {
|
|
49
|
+
throw new MoodleError("Moodle assignment page has no recognizable title", "MOODLE_RESPONSE_ERROR");
|
|
50
|
+
}
|
|
51
|
+
const url = `${baseUrl.replace(/\/$/, "")}/mod/assign/view.php?id=${courseModuleId}`;
|
|
52
|
+
const detail = {
|
|
53
|
+
id: courseModuleId,
|
|
54
|
+
idType: "courseModule",
|
|
55
|
+
name,
|
|
56
|
+
url,
|
|
57
|
+
};
|
|
58
|
+
// 2. Extract intro / description instructions text
|
|
59
|
+
const introElement = content.find(element => (attr(element, "id") === "intro" || hasClass(element, "activity-description") || hasClass(element, "intro")) &&
|
|
60
|
+
!isHidden(element));
|
|
61
|
+
if (introElement) {
|
|
62
|
+
const text = textContent(introElement);
|
|
63
|
+
if (text)
|
|
64
|
+
detail.introText = text;
|
|
65
|
+
}
|
|
66
|
+
// 3. Extract submission status table
|
|
67
|
+
const tables = content.filter(element => element.tagName === "table" &&
|
|
68
|
+
(hasClass(element, "generaltable") || hasClass(element, "submissionstatustable") || hasClass(element, "submissionsummarytable")) &&
|
|
69
|
+
!isHidden(element));
|
|
70
|
+
for (const table of tables) {
|
|
71
|
+
const rows = elements(table).filter(element => element.tagName === "tr" && !isHidden(element));
|
|
72
|
+
for (const row of rows) {
|
|
73
|
+
const cells = elements(row).filter(element => (element.tagName === "th" || element.tagName === "td") && !isHidden(element));
|
|
74
|
+
if (cells.length < 2)
|
|
75
|
+
continue;
|
|
76
|
+
const headerCell = cells[0];
|
|
77
|
+
const valueCell = cells[1];
|
|
78
|
+
const label = textContent(headerCell).toLowerCase().replace(/[\s\u00A0]+/g, " ").trim();
|
|
79
|
+
const value = textContent(valueCell);
|
|
80
|
+
if (!value)
|
|
81
|
+
continue;
|
|
82
|
+
if (label.includes("submission status")) {
|
|
83
|
+
detail.submissionStatus = value;
|
|
84
|
+
}
|
|
85
|
+
else if (label.includes("grading status")) {
|
|
86
|
+
detail.gradingStatus = value;
|
|
87
|
+
}
|
|
88
|
+
else if (label.includes("due date")) {
|
|
89
|
+
detail.dueDate = normalizeDate(value);
|
|
90
|
+
}
|
|
91
|
+
else if (label.includes("time remaining")) {
|
|
92
|
+
detail.timeRemaining = value;
|
|
93
|
+
}
|
|
94
|
+
else if (label.includes("last modified")) {
|
|
95
|
+
detail.lastModified = normalizeDate(value);
|
|
96
|
+
}
|
|
97
|
+
else if (label.includes("cut-off date") || label.includes("cutoff date")) {
|
|
98
|
+
detail.cutoffDate = normalizeDate(value);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return detail;
|
|
103
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { parse, parseFragment } from "parse5";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { ANNOUNCEMENTS_PAGE_SIZE } from "../client.js";
|
|
4
|
+
import { MoodleError } from "../errors.js";
|
|
5
|
+
import { attr, hasClass, readableText, visibleElements } from "../html.js";
|
|
6
|
+
const discussionPostsSchema = z.object({
|
|
7
|
+
courseid: z.number(),
|
|
8
|
+
forumid: z.number(),
|
|
9
|
+
posts: z.array(z.object({
|
|
10
|
+
discussionid: z.number(),
|
|
11
|
+
hasparent: z.boolean(),
|
|
12
|
+
isdeleted: z.boolean(),
|
|
13
|
+
capabilities: z.object({ view: z.boolean().nullable() }),
|
|
14
|
+
subject: z.string(),
|
|
15
|
+
message: z.string(),
|
|
16
|
+
author: z.object({ fullname: z.string() }).nullish(),
|
|
17
|
+
timecreated: z.number().int().min(0).max(253402300799).nullish(),
|
|
18
|
+
})),
|
|
19
|
+
});
|
|
20
|
+
const responseError = () => new MoodleError("Unrecognized Moodle forum response", "MOODLE_RESPONSE_ERROR");
|
|
21
|
+
export function parseAnnouncementsForum(html, baseUrl) {
|
|
22
|
+
const document = visibleElements(parse(html));
|
|
23
|
+
const body = document.find(element => element.tagName === "body");
|
|
24
|
+
const main = document.find(element => attr(element, "id") === "region-main");
|
|
25
|
+
if (!body || attr(body, "id") !== "page-mod-forum-view" || !main)
|
|
26
|
+
throw responseError();
|
|
27
|
+
if (!hasClass(body, "forumtype-news"))
|
|
28
|
+
return null;
|
|
29
|
+
const discussions = new Map();
|
|
30
|
+
const forumUrl = new URL(`${baseUrl}/mod/forum/view.php`);
|
|
31
|
+
const discussionPath = new URL("discuss.php", forumUrl).pathname;
|
|
32
|
+
const table = visibleElements(main).find(element => element.tagName === "table" && hasClass(element, "discussion-list"));
|
|
33
|
+
if (!table)
|
|
34
|
+
return [];
|
|
35
|
+
for (const row of visibleElements(table)) {
|
|
36
|
+
if (attr(row, "data-region") !== "discussion-list-item")
|
|
37
|
+
continue;
|
|
38
|
+
const id = Number(attr(row, "data-discussionid"));
|
|
39
|
+
const forumId = Number(attr(row, "data-forumid"));
|
|
40
|
+
if (!Number.isSafeInteger(id) || id <= 0 || !Number.isSafeInteger(forumId) || forumId <= 0)
|
|
41
|
+
continue;
|
|
42
|
+
const topic = visibleElements(row).find(element => hasClass(element, "topic"));
|
|
43
|
+
const hasDiscussionLink = topic && visibleElements(topic).some(element => {
|
|
44
|
+
const href = attr(element, "href");
|
|
45
|
+
if (element.tagName !== "a" || !href)
|
|
46
|
+
return false;
|
|
47
|
+
try {
|
|
48
|
+
const url = new URL(href, forumUrl);
|
|
49
|
+
return url.origin === forumUrl.origin && !url.username && !url.password &&
|
|
50
|
+
url.pathname === discussionPath && url.search === `?d=${id}`;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
if (hasDiscussionLink)
|
|
57
|
+
discussions.set(id, { id, forumId });
|
|
58
|
+
}
|
|
59
|
+
return [...discussions.values()].slice(0, ANNOUNCEMENTS_PAGE_SIZE);
|
|
60
|
+
}
|
|
61
|
+
export async function fetchCourseAnnouncements(client, courseId, discussions, baseUrl) {
|
|
62
|
+
if (!discussions.length)
|
|
63
|
+
return [];
|
|
64
|
+
const responses = await client.callBatch(discussions.map(({ id }) => ({
|
|
65
|
+
method: "mod_forum_get_discussion_posts",
|
|
66
|
+
args: { discussionid: id },
|
|
67
|
+
})));
|
|
68
|
+
return discussions.flatMap(({ id, forumId }, index) => {
|
|
69
|
+
const result = discussionPostsSchema.safeParse(responses[index]);
|
|
70
|
+
if (!result.success || result.data.courseid !== courseId || result.data.forumid !== forumId)
|
|
71
|
+
throw responseError();
|
|
72
|
+
const post = result.data.posts.find(item => item.discussionid === id && !item.hasparent && !item.isdeleted && item.capabilities.view === true);
|
|
73
|
+
if (!post)
|
|
74
|
+
return [];
|
|
75
|
+
return [{
|
|
76
|
+
id,
|
|
77
|
+
title: post.subject,
|
|
78
|
+
messageText: readableText(parseFragment(post.message)),
|
|
79
|
+
author: post.author?.fullname || undefined,
|
|
80
|
+
postedAt: post.timecreated ? new Date(post.timecreated * 1000).toISOString() : undefined,
|
|
81
|
+
url: `${baseUrl}/mod/forum/discuss.php?d=${id}`,
|
|
82
|
+
}];
|
|
83
|
+
});
|
|
84
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { parse } from "parse5";
|
|
2
|
+
import { MoodleError } from "../errors.js";
|
|
3
|
+
import { attr, hasClass, readableText, visibleElements } from "../html.js";
|
|
4
|
+
function httpUrl(value, pageUrl) {
|
|
5
|
+
if (!value?.trim())
|
|
6
|
+
return;
|
|
7
|
+
try {
|
|
8
|
+
const url = new URL(value, pageUrl);
|
|
9
|
+
if (["https:", "http:"].includes(url.protocol) && !url.username && !url.password)
|
|
10
|
+
return url;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function linkedUrl(element, pageUrl) {
|
|
17
|
+
if (element.tagName === "a")
|
|
18
|
+
return httpUrl(attr(element, "href"), pageUrl);
|
|
19
|
+
if (element.tagName === "object")
|
|
20
|
+
return httpUrl(attr(element, "data"), pageUrl);
|
|
21
|
+
if (["img", "source", "iframe", "frame", "video", "audio", "embed"].includes(element.tagName)) {
|
|
22
|
+
return httpUrl(attr(element, "src"), pageUrl);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function materialFiles(links, pageUrl, baseUrl, type) {
|
|
26
|
+
const files = new Map();
|
|
27
|
+
const pluginfile = new URL(`${baseUrl}/pluginfile.php`).pathname;
|
|
28
|
+
const contentPath = new RegExp(`^/[1-9]\\d*/mod_${type}/content/\\d+/(?:[^/]+/)*([^/]+)$`);
|
|
29
|
+
for (const url of links) {
|
|
30
|
+
if (url.origin !== pageUrl.origin)
|
|
31
|
+
continue;
|
|
32
|
+
const path = url.pathname === pluginfile ? url.searchParams.get("file") :
|
|
33
|
+
url.pathname.startsWith(`${pluginfile}/`) ? url.pathname.slice(pluginfile.length) : null;
|
|
34
|
+
const filename = path?.match(contentPath)?.[1];
|
|
35
|
+
if (!filename || !path)
|
|
36
|
+
continue;
|
|
37
|
+
const safeUrl = new URL(url.pathname, url.origin);
|
|
38
|
+
if (url.pathname === pluginfile)
|
|
39
|
+
safeUrl.searchParams.set("file", path);
|
|
40
|
+
if (url.searchParams.get("forcedownload") === "1")
|
|
41
|
+
safeUrl.searchParams.set("forcedownload", "1");
|
|
42
|
+
let name = filename;
|
|
43
|
+
if (url.pathname !== pluginfile) {
|
|
44
|
+
try {
|
|
45
|
+
name = decodeURIComponent(filename);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (!files.has(path))
|
|
52
|
+
files.set(path, { name, url: safeUrl.toString() });
|
|
53
|
+
}
|
|
54
|
+
return [...files.values()];
|
|
55
|
+
}
|
|
56
|
+
function safeTargetUrl(url) {
|
|
57
|
+
for (const key of [...url.searchParams.keys()]) {
|
|
58
|
+
if (/^(sesskey|moodlesession|token|wstoken|access_token)$/i.test(key))
|
|
59
|
+
url.searchParams.delete(key);
|
|
60
|
+
}
|
|
61
|
+
return url.toString();
|
|
62
|
+
}
|
|
63
|
+
export function parseMaterialDetail(html, type, baseUrl) {
|
|
64
|
+
const pageUrl = new URL(`${baseUrl}/mod/${type}/view.php`);
|
|
65
|
+
const document = visibleElements(parse(html));
|
|
66
|
+
const body = document.find(element => element.tagName === "body");
|
|
67
|
+
const main = document.find(element => attr(element, "id") === "region-main");
|
|
68
|
+
if (!main || !body || attr(body, "id") !== `page-mod-${type}-view`) {
|
|
69
|
+
// Moodle's legacy framed display has no body or region-main. Only read the
|
|
70
|
+
// target when its navigation frame identifies this same Moodle module type.
|
|
71
|
+
if ((type === "resource" || type === "url") && document.some(element => element.tagName === "frameset")) {
|
|
72
|
+
const links = document.filter(element => element.tagName === "frame").flatMap(element => linkedUrl(element, pageUrl) ?? []);
|
|
73
|
+
const [navigation, target] = links;
|
|
74
|
+
if (links.length === 2 && navigation.origin === pageUrl.origin && navigation.pathname === pageUrl.pathname && navigation.searchParams.get("frameset") === "top") {
|
|
75
|
+
return type === "url" ? { targetUrl: safeTargetUrl(target) } : { files: materialFiles([target], pageUrl, baseUrl, type) };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
throw new MoodleError("Unrecognized Moodle material page", "MOODLE_RESPONSE_ERROR");
|
|
79
|
+
}
|
|
80
|
+
const markup = visibleElements(main);
|
|
81
|
+
const intro = markup.find(element => attr(element, "id") === "intro" || hasClass(element, "activity-description"));
|
|
82
|
+
const description = intro ? readableText(intro) : "";
|
|
83
|
+
const details = description ? { description } : {};
|
|
84
|
+
if (type === "page") {
|
|
85
|
+
const content = markup.find(element => hasClass(element, "generalbox") && hasClass(element, "center"));
|
|
86
|
+
if (content)
|
|
87
|
+
details.contentText = readableText(content);
|
|
88
|
+
return details;
|
|
89
|
+
}
|
|
90
|
+
let display = markup.find(element => type === "folder" ? /^folder_tree\d+$/.test(attr(element, "id") ?? "") : hasClass(element, `${type}workaround`));
|
|
91
|
+
if (!display && type !== "folder") {
|
|
92
|
+
const introMarkup = new Set(intro ? visibleElements(intro) : []);
|
|
93
|
+
display = markup.find(element => !introMarkup.has(element) && (hasClass(element, "resourcecontent") ||
|
|
94
|
+
hasClass(element, "mediaplugin") || attr(element, "id") === "resourceobject"));
|
|
95
|
+
}
|
|
96
|
+
const links = display ? visibleElements(display).flatMap(element => linkedUrl(element, pageUrl) ?? []) : [];
|
|
97
|
+
if (type === "url") {
|
|
98
|
+
if (links[0])
|
|
99
|
+
details.targetUrl = safeTargetUrl(links[0]);
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
details.files = materialFiles(links, pageUrl, baseUrl, type);
|
|
103
|
+
}
|
|
104
|
+
return details;
|
|
105
|
+
}
|
|
@@ -14,7 +14,8 @@ export function moduleViewUrl(candidate, baseUrl, expectedType) {
|
|
|
14
14
|
if (url.origin !== base.origin || url.username || url.password ||
|
|
15
15
|
!type || (expectedType !== undefined && type !== expectedType) ||
|
|
16
16
|
!id || !/^[1-9]\d*$/.test(id) || !Number.isSafeInteger(Number(id)) ||
|
|
17
|
-
[...url.searchParams
|
|
17
|
+
[...url.searchParams].some(([key, value]) => key !== "id" && key !== "sesskey" &&
|
|
18
|
+
!((type === "resource" || type === "url") && (key === "redirect" || key === "forceview") && /^[01]$/.test(value))))
|
|
18
19
|
return null;
|
|
19
20
|
// Never expose session keys or fragments received in LMS links.
|
|
20
21
|
return `${baseUrl}/mod/${type}/view.php?id=${id}`;
|
package/dist/moodle/client.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { validateCredentials } from "./auth/credentials.js";
|
|
2
2
|
import { MoodleAuthError, MoodleError, MoodleNetworkError, MoodleSessionKeyError } from "./errors.js";
|
|
3
3
|
import { decodeMoodleResponses } from "./response.js";
|
|
4
|
+
export const ANNOUNCEMENTS_PAGE_SIZE = 10;
|
|
5
|
+
export function isMaterialType(type) {
|
|
6
|
+
return type === "resource" || type === "folder" || type === "page" || type === "url";
|
|
7
|
+
}
|
|
4
8
|
const responseError = () => new MoodleError("Moodle returned an invalid or oversized response", "MOODLE_RESPONSE_ERROR");
|
|
5
9
|
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
6
10
|
export class MoodleClient {
|
|
@@ -60,20 +64,33 @@ export class MoodleClient {
|
|
|
60
64
|
});
|
|
61
65
|
}
|
|
62
66
|
getAssignmentIndex(courseId) {
|
|
63
|
-
return this.getPage("/mod/assign/index.php", courseId);
|
|
67
|
+
return this.getPage("/mod/assign/index.php", courseId, "course ID");
|
|
64
68
|
}
|
|
65
69
|
getCoursePage(courseId) {
|
|
66
|
-
return this.getPage("/course/view.php", courseId);
|
|
70
|
+
return this.getPage("/course/view.php", courseId, "course ID");
|
|
71
|
+
}
|
|
72
|
+
getAssignmentPage(courseModuleId) {
|
|
73
|
+
return this.getPage("/mod/assign/view.php", courseModuleId, "course module ID");
|
|
74
|
+
}
|
|
75
|
+
getForumPage(courseModuleId, page) {
|
|
76
|
+
if (!Number.isSafeInteger(page) || page < 0)
|
|
77
|
+
throw new MoodleError("Invalid forum page", "INVALID_REQUEST");
|
|
78
|
+
return this.getPage("/mod/forum/view.php", courseModuleId, "course module ID", { page: String(page), s: String(ANNOUNCEMENTS_PAGE_SIZE) });
|
|
79
|
+
}
|
|
80
|
+
getMaterialPage(type, courseModuleId) {
|
|
81
|
+
if (!isMaterialType(type))
|
|
82
|
+
throw new MoodleError("Unsupported Moodle material type", "INVALID_REQUEST");
|
|
83
|
+
const options = type === "resource" || type === "url" ? { forceview: "1" } : undefined;
|
|
84
|
+
return this.getPage(`/mod/${type}/view.php`, courseModuleId, "course module ID", options);
|
|
67
85
|
}
|
|
68
|
-
async getPage(path,
|
|
69
|
-
if (!Number.isSafeInteger(
|
|
70
|
-
throw new MoodleError(
|
|
86
|
+
async getPage(path, id, label = "course ID", options) {
|
|
87
|
+
if (!Number.isSafeInteger(id) || id <= 0)
|
|
88
|
+
throw new MoodleError(`Invalid ${label}`, "INVALID_REQUEST");
|
|
71
89
|
return this.withAuthRetry(async (credentials) => {
|
|
72
|
-
const
|
|
90
|
+
const query = new URLSearchParams({ id: String(id), ...options });
|
|
91
|
+
const { response, body } = await this.send(`${path}?${query}`, { headers: { Accept: "text/html" } }, credentials, true);
|
|
73
92
|
if (!response.ok)
|
|
74
93
|
throw this.httpError(response.status);
|
|
75
|
-
if (!response.headers.get("content-type")?.toLowerCase().includes("text/html"))
|
|
76
|
-
throw responseError();
|
|
77
94
|
if (/id=["']page-login-index["']/.test(body))
|
|
78
95
|
throw this.loginError();
|
|
79
96
|
return body;
|
|
@@ -107,7 +124,7 @@ export class MoodleClient {
|
|
|
107
124
|
httpError(status) {
|
|
108
125
|
return new MoodleError(`Moodle HTTP request failed (${status})`, "MOODLE_HTTP_ERROR");
|
|
109
126
|
}
|
|
110
|
-
async send(path, init, credentials) {
|
|
127
|
+
async send(path, init, credentials, expectedHtml = false) {
|
|
111
128
|
const controller = new AbortController();
|
|
112
129
|
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
113
130
|
try {
|
|
@@ -118,6 +135,11 @@ export class MoodleClient {
|
|
|
118
135
|
});
|
|
119
136
|
if ([301, 302, 303, 307, 308, 401].includes(response.status))
|
|
120
137
|
throw this.loginError();
|
|
138
|
+
if (expectedHtml && response.ok && (!response.headers.get("content-type")?.toLowerCase().includes("text/html") ||
|
|
139
|
+
/^attachment\b/i.test(response.headers.get("content-disposition") ?? ""))) {
|
|
140
|
+
controller.abort();
|
|
141
|
+
throw responseError();
|
|
142
|
+
}
|
|
121
143
|
if (Number(response.headers.get("content-length")) > MAX_RESPONSE_BYTES) {
|
|
122
144
|
controller.abort();
|
|
123
145
|
throw responseError();
|
package/dist/moodle/html.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
export const attr = (element, name) => element.attrs.find(attribute => attribute.name === name)?.value;
|
|
2
2
|
export const hasClass = (element, name) => attr(element, "class")?.split(/\s+/).includes(name) ?? false;
|
|
3
|
-
export function* nodes(root, skipAccessHide = false) {
|
|
3
|
+
export function* nodes(root, skipAccessHide = false, visibleOnly = false) {
|
|
4
4
|
const stack = [root];
|
|
5
5
|
while (stack.length) {
|
|
6
6
|
const node = stack.pop();
|
|
7
|
+
if (visibleOnly && "tagName" in node && (isHidden(node) || hasClass(node, "dimmed_text")))
|
|
8
|
+
continue;
|
|
7
9
|
yield node;
|
|
8
10
|
if ("tagName" in node && (["script", "style", "template"].includes(node.tagName) || (skipAccessHide && hasClass(node, "accesshide"))))
|
|
9
11
|
continue;
|
|
@@ -17,6 +19,17 @@ export const elements = (root) => [...nodes(root)].filter((node) => "tagName" in
|
|
|
17
19
|
export const textContent = (root) => [...nodes(root, true)]
|
|
18
20
|
.filter((node) => node.nodeName === "#text")
|
|
19
21
|
.map(node => node.value).join("").replace(/\s+/g, " ").trim();
|
|
22
|
+
export const visibleElements = (root) => [...nodes(root, false, true)].filter((node) => "tagName" in node);
|
|
23
|
+
export function readableText(root) {
|
|
24
|
+
const parts = [];
|
|
25
|
+
for (const node of nodes(root, true, true)) {
|
|
26
|
+
if (node.nodeName === "#text" && "value" in node)
|
|
27
|
+
parts.push(node.value);
|
|
28
|
+
if ("tagName" in node && /^(br|div|h[1-6]|li|p|td|tr)$/.test(node.tagName))
|
|
29
|
+
parts.push(" ");
|
|
30
|
+
}
|
|
31
|
+
return parts.join("").replace(/\s+/g, " ").trim();
|
|
32
|
+
}
|
|
20
33
|
export function isHidden(element) {
|
|
21
34
|
return attr(element, "hidden") !== undefined || attr(element, "aria-hidden") === "true" ||
|
|
22
35
|
["hidden", "hiddenfromstudents", "dimmed", "d-none"].some(name => hasClass(element, name)) ||
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { parseAssignmentIndex } from "../moodle/api/assignments.js";
|
|
2
|
+
import { parseAssignmentDetail } from "../moodle/api/assignment-detail.js";
|
|
2
3
|
import { MoodleError } from "../moodle/errors.js";
|
|
3
4
|
import { CourseService } from "./course.service.js";
|
|
4
5
|
export class AssignmentService {
|
|
@@ -18,6 +19,13 @@ export class AssignmentService {
|
|
|
18
19
|
url: assignment.url,
|
|
19
20
|
}));
|
|
20
21
|
}
|
|
22
|
+
async getAssignmentDetail(courseModuleId) {
|
|
23
|
+
if (!Number.isSafeInteger(courseModuleId) || courseModuleId <= 0) {
|
|
24
|
+
throw new MoodleError("Invalid course module ID", "INVALID_REQUEST");
|
|
25
|
+
}
|
|
26
|
+
const html = await this.client.getAssignmentPage(courseModuleId);
|
|
27
|
+
return parseAssignmentDetail(html, this.baseUrl, courseModuleId);
|
|
28
|
+
}
|
|
21
29
|
async getAssignments(input = {}) {
|
|
22
30
|
const courses = await new CourseService(this.client).getMyCourses();
|
|
23
31
|
if (input.courseId && !courses.some(course => course.id === input.courseId)) {
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { parseCourseContents } from "../moodle/api/course-contents.js";
|
|
2
|
+
import { fetchCourseAnnouncements, parseAnnouncementsForum } from "../moodle/api/course-announcements.js";
|
|
3
|
+
import { parseMaterialDetail } from "../moodle/api/material-detail.js";
|
|
4
|
+
import { isMaterialType } from "../moodle/client.js";
|
|
2
5
|
import { MoodleError } from "../moodle/errors.js";
|
|
3
6
|
import { CourseService } from "./course.service.js";
|
|
4
7
|
export class CourseContentService {
|
|
@@ -17,4 +20,33 @@ export class CourseContentService {
|
|
|
17
20
|
sections: parseCourseContents(await this.client.getCoursePage(courseId), this.baseUrl),
|
|
18
21
|
};
|
|
19
22
|
}
|
|
23
|
+
async getCourseAnnouncements(courseId, page = 0) {
|
|
24
|
+
if (!Number.isSafeInteger(courseId) || courseId <= 0 || !Number.isSafeInteger(page) || page < 0) {
|
|
25
|
+
throw new MoodleError("Invalid course ID or announcements page", "INVALID_REQUEST");
|
|
26
|
+
}
|
|
27
|
+
const { sections } = await this.getCourseContents(courseId);
|
|
28
|
+
for (const module of sections.flatMap(section => section.modules)) {
|
|
29
|
+
if (module.type !== "forum")
|
|
30
|
+
continue;
|
|
31
|
+
const discussions = parseAnnouncementsForum(await this.client.getForumPage(module.id, page), this.baseUrl);
|
|
32
|
+
if (discussions !== null)
|
|
33
|
+
return fetchCourseAnnouncements(this.client, courseId, discussions, this.baseUrl);
|
|
34
|
+
}
|
|
35
|
+
return [];
|
|
36
|
+
}
|
|
37
|
+
async getMaterialDetail(courseId, courseModuleId) {
|
|
38
|
+
if (!Number.isSafeInteger(courseId) || courseId <= 0 || !Number.isSafeInteger(courseModuleId) || courseModuleId <= 0) {
|
|
39
|
+
throw new MoodleError("Invalid course ID or course module ID", "INVALID_REQUEST");
|
|
40
|
+
}
|
|
41
|
+
const { sections } = await this.getCourseContents(courseId);
|
|
42
|
+
const module = sections.flatMap(section => section.modules).find(item => item.id === courseModuleId);
|
|
43
|
+
if (!module?.url || !isMaterialType(module.type)) {
|
|
44
|
+
throw new MoodleError("Requested module is not a visible material in the enrolled course", "MATERIAL_NOT_AVAILABLE");
|
|
45
|
+
}
|
|
46
|
+
const html = await this.client.getMaterialPage(module.type, courseModuleId);
|
|
47
|
+
return {
|
|
48
|
+
id: module.id, courseId, name: module.name, type: module.type, url: module.url,
|
|
49
|
+
...parseMaterialDetail(html, module.type, this.baseUrl),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
20
52
|
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { createHmac, randomBytes } from "node:crypto";
|
|
2
|
+
import { DEFAULT_COURSE_CACHE_TTL_MS } from "../config/env.js";
|
|
3
|
+
const MAX_CACHE_ENTRY_BYTES = 512 * 1024;
|
|
4
|
+
class BoundedTtlCache {
|
|
5
|
+
ttlMs;
|
|
6
|
+
capacity;
|
|
7
|
+
entries = new Map();
|
|
8
|
+
constructor(ttlMs, capacity) {
|
|
9
|
+
this.ttlMs = ttlMs;
|
|
10
|
+
this.capacity = capacity;
|
|
11
|
+
}
|
|
12
|
+
async getOrLoad(key, load, bypassCache = false) {
|
|
13
|
+
if (this.ttlMs === 0)
|
|
14
|
+
return load();
|
|
15
|
+
const current = this.entries.get(key);
|
|
16
|
+
if (current) {
|
|
17
|
+
if (!bypassCache && (current.expiresAt === undefined || current.expiresAt > performance.now())) {
|
|
18
|
+
this.entries.delete(key);
|
|
19
|
+
this.entries.set(key, current);
|
|
20
|
+
return current.value;
|
|
21
|
+
}
|
|
22
|
+
this.remove(key, current);
|
|
23
|
+
}
|
|
24
|
+
if (this.entries.size >= this.capacity) {
|
|
25
|
+
const oldest = this.entries.entries().next();
|
|
26
|
+
if (!oldest.done)
|
|
27
|
+
this.remove(...oldest.value);
|
|
28
|
+
}
|
|
29
|
+
const entry = {
|
|
30
|
+
value: Promise.resolve().then(load).then(value => {
|
|
31
|
+
if (this.entries.get(key) === entry) {
|
|
32
|
+
if (Buffer.byteLength(JSON.stringify(value)) <= MAX_CACHE_ENTRY_BYTES) {
|
|
33
|
+
entry.expiresAt = performance.now() + this.ttlMs;
|
|
34
|
+
entry.timer = setTimeout(() => this.remove(key, entry), this.ttlMs).unref();
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
this.remove(key, entry);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return value;
|
|
41
|
+
}).catch(error => {
|
|
42
|
+
this.remove(key, entry);
|
|
43
|
+
throw error;
|
|
44
|
+
}),
|
|
45
|
+
};
|
|
46
|
+
this.entries.set(key, entry);
|
|
47
|
+
return entry.value;
|
|
48
|
+
}
|
|
49
|
+
clear() {
|
|
50
|
+
for (const [key, entry] of this.entries)
|
|
51
|
+
this.remove(key, entry);
|
|
52
|
+
}
|
|
53
|
+
remove(key, entry) {
|
|
54
|
+
if (entry.timer)
|
|
55
|
+
clearTimeout(entry.timer);
|
|
56
|
+
if (this.entries.get(key) === entry)
|
|
57
|
+
this.entries.delete(key);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const scopeSecret = randomBytes(32);
|
|
61
|
+
let current;
|
|
62
|
+
export function getCourseMetadataCache(config) {
|
|
63
|
+
const ttlMs = config.cacheTtlMs ?? DEFAULT_COURSE_CACHE_TTL_MS;
|
|
64
|
+
const scope = createHmac("sha256", scopeSecret).update(JSON.stringify([
|
|
65
|
+
config.baseUrl, config.username, config.password, config.moodleSession, config.moodleSesskey, ttlMs,
|
|
66
|
+
])).digest("hex");
|
|
67
|
+
if (current?.scope !== scope) {
|
|
68
|
+
current?.courses.clear();
|
|
69
|
+
current?.contents.clear();
|
|
70
|
+
current = {
|
|
71
|
+
scope,
|
|
72
|
+
courses: new BoundedTtlCache(ttlMs, 4),
|
|
73
|
+
contents: new BoundedTtlCache(ttlMs, 64),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
return current;
|
|
77
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { MCPTool } from "mcp-framework";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { loadConfig } from "../config/env.js";
|
|
4
|
+
import { getAuthProvider } from "../moodle/auth/provider-factory.js";
|
|
5
|
+
import { MoodleClient } from "../moodle/client.js";
|
|
6
|
+
import { AssignmentService } from "../services/assignment.service.js";
|
|
7
|
+
class GetAssignmentDetailTool extends MCPTool {
|
|
8
|
+
name = "get_assignment_detail";
|
|
9
|
+
description = "Get detailed information about an assignment, including submission status, grading status, due date, time remaining, and instructions.";
|
|
10
|
+
annotations = { readOnlyHint: true, destructiveHint: false };
|
|
11
|
+
schema = z.object({
|
|
12
|
+
courseModuleId: z.number().int().positive().safe().describe("Course module ID of the assignment (from get_course_assignments or get_upcoming_deadlines)"),
|
|
13
|
+
});
|
|
14
|
+
async execute(input) {
|
|
15
|
+
const config = loadConfig();
|
|
16
|
+
const client = new MoodleClient({ baseUrl: config.baseUrl, authProvider: getAuthProvider(config), timeoutMs: config.timeoutMs });
|
|
17
|
+
return new AssignmentService(client, config.baseUrl).getAssignmentDetail(input.courseModuleId);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export default GetAssignmentDetailTool;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { MCPTool } from "mcp-framework";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { loadConfig } from "../config/env.js";
|
|
4
|
+
import { getAuthProvider } from "../moodle/auth/provider-factory.js";
|
|
5
|
+
import { MoodleClient } from "../moodle/client.js";
|
|
6
|
+
import { CourseContentService } from "../services/course-content.service.js";
|
|
7
|
+
class GetCourseAnnouncementsTool extends MCPTool {
|
|
8
|
+
name = "get_course_announcements";
|
|
9
|
+
description = "Read up to 10 visible announcements from the Moodle Announcements forum in an enrolled course, one page at a time.";
|
|
10
|
+
annotations = { readOnlyHint: true, destructiveHint: false };
|
|
11
|
+
schema = z.object({
|
|
12
|
+
courseId: z.number().int().positive().safe().describe("Enrolled course ID from get_my_courses"),
|
|
13
|
+
page: z.number().int().nonnegative().safe().optional().describe("Zero-based page number. Defaults to 0."),
|
|
14
|
+
});
|
|
15
|
+
async execute(input) {
|
|
16
|
+
const config = loadConfig();
|
|
17
|
+
const client = new MoodleClient({ baseUrl: config.baseUrl, authProvider: getAuthProvider(config), timeoutMs: config.timeoutMs });
|
|
18
|
+
return new CourseContentService(client, config.baseUrl).getCourseAnnouncements(input.courseId, input.page);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export default GetCourseAnnouncementsTool;
|
|
@@ -4,15 +4,21 @@ import { loadConfig } from "../config/env.js";
|
|
|
4
4
|
import { getAuthProvider } from "../moodle/auth/provider-factory.js";
|
|
5
5
|
import { MoodleClient } from "../moodle/client.js";
|
|
6
6
|
import { CourseContentService } from "../services/course-content.service.js";
|
|
7
|
+
import { getCourseMetadataCache } from "../services/course-metadata-cache.js";
|
|
7
8
|
class GetCourseContentsTool extends MCPTool {
|
|
8
9
|
name = "get_course_contents";
|
|
9
10
|
description = "Get visible sections, activities and resource metadata in an enrolled course. Excludes hidden or inaccessible resources and does not download files.";
|
|
10
11
|
annotations = { readOnlyHint: true, destructiveHint: false };
|
|
11
|
-
schema = z.object({
|
|
12
|
+
schema = z.object({
|
|
13
|
+
courseId: z.number().int().positive().safe().describe("Enrolled course ID from get_my_courses"),
|
|
14
|
+
bypassCache: z.boolean().optional().describe("Fetch fresh course contents from Moodle"),
|
|
15
|
+
});
|
|
12
16
|
async execute(input) {
|
|
13
17
|
const config = loadConfig();
|
|
14
|
-
|
|
15
|
-
|
|
18
|
+
return getCourseMetadataCache(config).contents.getOrLoad(input.courseId, () => {
|
|
19
|
+
const client = new MoodleClient({ baseUrl: config.baseUrl, authProvider: getAuthProvider(config), timeoutMs: config.timeoutMs });
|
|
20
|
+
return new CourseContentService(client, config.baseUrl).getCourseContents(input.courseId);
|
|
21
|
+
}, input.bypassCache);
|
|
16
22
|
}
|
|
17
23
|
}
|
|
18
24
|
export default GetCourseContentsTool;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { MCPTool } from "mcp-framework";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { loadConfig } from "../config/env.js";
|
|
4
|
+
import { getAuthProvider } from "../moodle/auth/provider-factory.js";
|
|
5
|
+
import { MoodleClient } from "../moodle/client.js";
|
|
6
|
+
import { CourseContentService } from "../services/course-content.service.js";
|
|
7
|
+
class GetMaterialDetailTool extends MCPTool {
|
|
8
|
+
name = "get_material_detail";
|
|
9
|
+
description = "Read details for a visible File, Folder, Page or URL from get_course_contents. Returns Moodle file links without downloading files or opening external links.";
|
|
10
|
+
annotations = { readOnlyHint: true, destructiveHint: false };
|
|
11
|
+
schema = z.object({
|
|
12
|
+
courseId: z.number().int().positive().safe().describe("Enrolled course ID from get_my_courses"),
|
|
13
|
+
courseModuleId: z.number().int().positive().safe().describe("Material module ID from get_course_contents"),
|
|
14
|
+
});
|
|
15
|
+
async execute(input) {
|
|
16
|
+
const config = loadConfig();
|
|
17
|
+
const client = new MoodleClient({ baseUrl: config.baseUrl, authProvider: getAuthProvider(config), timeoutMs: config.timeoutMs });
|
|
18
|
+
return new CourseContentService(client, config.baseUrl).getMaterialDetail(input.courseId, input.courseModuleId);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export default GetMaterialDetailTool;
|
package/package.json
CHANGED
package/scripts/setup.mjs
CHANGED
|
@@ -81,12 +81,16 @@ export function stripJsonComments(text) {
|
|
|
81
81
|
const end = text.indexOf("*/", i + 2);
|
|
82
82
|
if (end === -1) break;
|
|
83
83
|
i = end + 1;
|
|
84
|
+
} else if (char === "}" || char === "]") {
|
|
85
|
+
// Strip trailing commas only outside strings, after skipping comments.
|
|
86
|
+
result = result.replace(/,(\s*)$/, "$1");
|
|
87
|
+
result += char;
|
|
84
88
|
} else {
|
|
85
89
|
result += char;
|
|
86
90
|
}
|
|
87
91
|
}
|
|
88
92
|
}
|
|
89
|
-
return result
|
|
93
|
+
return result;
|
|
90
94
|
}
|
|
91
95
|
|
|
92
96
|
export function updateJsonConfigFile(configPath, serverConfig, key = "mcpServers") {
|
|
@@ -119,10 +123,20 @@ export function updateJsonConfigFile(configPath, serverConfig, key = "mcpServers
|
|
|
119
123
|
return false;
|
|
120
124
|
}
|
|
121
125
|
|
|
122
|
-
if (
|
|
126
|
+
if (Object.hasOwn(json, key) &&
|
|
127
|
+
(json[key] === null || typeof json[key] !== "object" || Array.isArray(json[key]))) {
|
|
128
|
+
console.error(`\n❌ Cấu trúc ${key} không hợp lệ (không phải JSON object): ${configPath}`);
|
|
129
|
+
console.error(` ⚠️ Đã HỦY thao tác ghi để bảo vệ file của bạn.`);
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
if (!Object.hasOwn(json, key)) {
|
|
123
133
|
json[key] = {};
|
|
124
134
|
}
|
|
125
|
-
|
|
135
|
+
// Reuse the legacy name when present so setup does not add a second server.
|
|
136
|
+
const serverName = !Object.hasOwn(json[key], "fit-lms") && Object.hasOwn(json[key], "hanu-lms")
|
|
137
|
+
? "hanu-lms"
|
|
138
|
+
: "fit-lms";
|
|
139
|
+
json[key][serverName] = serverConfig;
|
|
126
140
|
|
|
127
141
|
try {
|
|
128
142
|
fs.mkdirSync(path.dirname(configPath), { recursive: true });
|
|
@@ -202,10 +216,11 @@ export function ask(question, isPassword = false) {
|
|
|
202
216
|
return isPassword ? askPassword(question) : askText(question);
|
|
203
217
|
}
|
|
204
218
|
|
|
205
|
-
export function saveEnvFile(envPath, { baseUrl, timeoutMs, username, password }) {
|
|
219
|
+
export function saveEnvFile(envPath, { baseUrl, timeoutMs, cacheTtlMs, username, password }) {
|
|
206
220
|
const envContent = [
|
|
207
221
|
`LMS_BASE_URL=${serializeEnvValue(baseUrl)}`,
|
|
208
222
|
`TIMEOUT_MS=${serializeEnvValue(timeoutMs)}`,
|
|
223
|
+
...(cacheTtlMs === undefined ? [] : [`LMS_CACHE_TTL_MS=${serializeEnvValue(cacheTtlMs)}`]),
|
|
209
224
|
"",
|
|
210
225
|
"# Auto-login credentials",
|
|
211
226
|
`LMS_USERNAME=${serializeEnvValue(username)}`,
|
|
@@ -261,6 +276,7 @@ export async function runSetup() {
|
|
|
261
276
|
let existingBaseUrl = "https://lms.fit.hanu.vn";
|
|
262
277
|
let existingUsername = "";
|
|
263
278
|
let existingTimeout = "5000";
|
|
279
|
+
let existingCacheTtlMs;
|
|
264
280
|
|
|
265
281
|
if (fs.existsSync(envPath)) {
|
|
266
282
|
try {
|
|
@@ -268,6 +284,7 @@ export async function runSetup() {
|
|
|
268
284
|
if (parsed.LMS_BASE_URL) existingBaseUrl = parsed.LMS_BASE_URL;
|
|
269
285
|
if (parsed.LMS_USERNAME) existingUsername = parsed.LMS_USERNAME;
|
|
270
286
|
if (parsed.TIMEOUT_MS) existingTimeout = parsed.TIMEOUT_MS;
|
|
287
|
+
existingCacheTtlMs = parsed.LMS_CACHE_TTL_MS;
|
|
271
288
|
} catch {
|
|
272
289
|
// Ignore read errors
|
|
273
290
|
}
|
|
@@ -280,6 +297,7 @@ export async function runSetup() {
|
|
|
280
297
|
if (parsed.LMS_BASE_URL) existingBaseUrl = parsed.LMS_BASE_URL;
|
|
281
298
|
if (parsed.LMS_USERNAME) existingUsername = parsed.LMS_USERNAME;
|
|
282
299
|
if (parsed.TIMEOUT_MS) existingTimeout = parsed.TIMEOUT_MS;
|
|
300
|
+
existingCacheTtlMs = parsed.LMS_CACHE_TTL_MS;
|
|
283
301
|
} catch {
|
|
284
302
|
// Ignore read errors
|
|
285
303
|
}
|
|
@@ -337,7 +355,7 @@ export async function runSetup() {
|
|
|
337
355
|
}
|
|
338
356
|
|
|
339
357
|
// 5. Save to .env with 0600 permissions and escaped values
|
|
340
|
-
saveEnvFile(envPath, { baseUrl, timeoutMs, username, password });
|
|
358
|
+
saveEnvFile(envPath, { baseUrl, timeoutMs, cacheTtlMs: existingCacheTtlMs, username, password });
|
|
341
359
|
console.log(`\n🎉 Đã lưu cấu hình an toàn (permissions: 0600) vào: ${envPath}`);
|
|
342
360
|
|
|
343
361
|
// 6. Define configurations for clients
|