fit-lms-mcp 2.2.0 → 2.3.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 +39 -12
- package/dist/config/env.js +3 -0
- package/dist/mcp/server.js +4 -0
- package/dist/moodle/api/announcement-attachments.js +41 -0
- package/dist/moodle/api/course-announcements.js +36 -23
- package/dist/moodle/client.js +57 -18
- package/dist/services/site-announcement.service.js +62 -0
- package/dist/tools/DownloadAnnouncementAttachmentTool.js +21 -0
- package/dist/tools/GetSiteAnnouncementsTool.js +20 -0
- package/package.json +1 -1
- package/scripts/setup.mjs +35 -33
package/README.md
CHANGED
|
@@ -4,6 +4,20 @@ A Model Context Protocol (MCP) server providing authorized, read-only access to
|
|
|
4
4
|
|
|
5
5
|
It exposes enrolled courses, course assignments, upcoming deadlines, and course structure over stdio, with **automatic background authentication** and **interactive setup**.
|
|
6
6
|
|
|
7
|
+
## Cài MCP cho Moodle LMS FIT HANU
|
|
8
|
+
|
|
9
|
+
`fit-lms-mcp` kết nối Claude Code, Codex, OpenCode hoặc Antigravity với Moodle LMS của Khoa Công nghệ Thông tin, Trường Đại học Hà Nội (HANU). Sinh viên có thể xem môn học, tài liệu, bài tập và hạn nộp bằng tài khoản LMS của mình.
|
|
10
|
+
|
|
11
|
+
Cài Node.js 22 trở lên rồi chạy lệnh sau để thiết lập.
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npx -y fit-lms-mcp@latest setup
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Nhập mã sinh viên và mật khẩu LMS khi được hỏi. Chọn đăng ký MCP với ứng dụng AI mà setup phát hiện, rồi khởi động lại ứng dụng. Với Codex, tự động đăng ký cần lệnh `codex` trên `PATH`.
|
|
18
|
+
|
|
19
|
+
Sau khi kết nối, thử hỏi “Tuần này mình có bài tập nào sắp đến hạn?” hoặc “Cho mình xem tài liệu của môn Cơ sở dữ liệu”.
|
|
20
|
+
|
|
7
21
|
---
|
|
8
22
|
|
|
9
23
|
## 🚀 Quick Start
|
|
@@ -13,7 +27,7 @@ Requires **Node.js 22 or later**. Node.js 24 LTS is recommended. CI tests Node.j
|
|
|
13
27
|
Run the interactive setup assistant directly with `npx`:
|
|
14
28
|
|
|
15
29
|
```bash
|
|
16
|
-
npx fit-lms-mcp setup
|
|
30
|
+
npx -y fit-lms-mcp@latest setup
|
|
17
31
|
```
|
|
18
32
|
|
|
19
33
|
Or, from a local workspace:
|
|
@@ -28,9 +42,15 @@ The interactive setup assistant will:
|
|
|
28
42
|
1. Prompt for your LMS student ID and password (safely masked).
|
|
29
43
|
2. Test the connection against HANU LMS immediately.
|
|
30
44
|
3. Save your configuration securely with `0600` permissions to `~/.fit-lms-mcp/.env` when run via `npx`, or the workspace `.env` when run from the package root.
|
|
31
|
-
4. Offer to register the MCP server with detected AI clients (**Claude Code**, **OpenCode**, **Codex**, or **Antigravity**).
|
|
45
|
+
4. Offer to register the MCP server with detected AI clients (**Claude Code**, **OpenCode**, **Codex**, or **Antigravity**). Automatic registration for Codex requires the `codex` CLI on your PATH.
|
|
46
|
+
|
|
47
|
+
After running setup, restart your AI client. The npm configuration uses `npx -y fit-lms-mcp@latest` so npm resolves the latest stable release whenever the client starts the MCP server.
|
|
32
48
|
|
|
33
|
-
|
|
49
|
+
### Updating an existing installation
|
|
50
|
+
|
|
51
|
+
If your client already uses `fit-lms-mcp@latest`, restart it to pick up a new release. For an older `npx` entry, change the package argument to `fit-lms-mcp@latest` and restart the client. You can keep using the credentials saved by setup.
|
|
52
|
+
|
|
53
|
+
If you installed the package globally, run `npm install -g fit-lms-mcp@latest` and restart your client.
|
|
34
54
|
|
|
35
55
|
---
|
|
36
56
|
|
|
@@ -52,6 +72,7 @@ For use via `npx`, create `~/.fit-lms-mcp/.env` with the settings below and rest
|
|
|
52
72
|
| `LMS_PASSWORD` | Password for automatic login (Option 1; automatically logs in and refreshes expired sessions) |
|
|
53
73
|
| `TIMEOUT_MS` | Optional request timeout in milliseconds (default: `5000`, maximum: `2147483647`) |
|
|
54
74
|
| `LMS_CACHE_TTL_MS` | Optional course metadata cache lifetime in milliseconds (default `900000`, maximum `2147483647`, `0` disables caching) |
|
|
75
|
+
| `LMS_DOWNLOAD_DIR` | Optional local directory for announcement downloads. Defaults to `~/Downloads/fit-lms` on the MCP server. |
|
|
55
76
|
| `LMS_MOODLE_SESSION` | MoodleSession cookie value (Option 2 - Manual legacy session) |
|
|
56
77
|
| `LMS_MOODLE_SESSKEY` | sesskey query parameter from the same session (Option 2 - Manual legacy session) |
|
|
57
78
|
|
|
@@ -70,7 +91,7 @@ The following examples use the credentials saved by the `npx` setup flow.
|
|
|
70
91
|
Register via CLI:
|
|
71
92
|
|
|
72
93
|
```bash
|
|
73
|
-
claude mcp add fit-lms -- npx -y fit-lms-mcp
|
|
94
|
+
claude mcp add fit-lms -- npx -y fit-lms-mcp@latest
|
|
74
95
|
```
|
|
75
96
|
|
|
76
97
|
Or add to `~/.claude.json`:
|
|
@@ -80,7 +101,7 @@ Or add to `~/.claude.json`:
|
|
|
80
101
|
"mcpServers": {
|
|
81
102
|
"fit-lms": {
|
|
82
103
|
"command": "npx",
|
|
83
|
-
"args": ["-y", "fit-lms-mcp"]
|
|
104
|
+
"args": ["-y", "fit-lms-mcp@latest"]
|
|
84
105
|
}
|
|
85
106
|
}
|
|
86
107
|
}
|
|
@@ -95,7 +116,7 @@ Add to `~/.config/opencode/opencode.jsonc` (or project `opencode.json`):
|
|
|
95
116
|
"mcp": {
|
|
96
117
|
"fit-lms": {
|
|
97
118
|
"type": "local",
|
|
98
|
-
"command": ["npx", "-y", "fit-lms-mcp"],
|
|
119
|
+
"command": ["npx", "-y", "fit-lms-mcp@latest"],
|
|
99
120
|
"enabled": true,
|
|
100
121
|
"timeout": 60000
|
|
101
122
|
}
|
|
@@ -108,7 +129,7 @@ Add to `~/.config/opencode/opencode.jsonc` (or project `opencode.json`):
|
|
|
108
129
|
Register via CLI:
|
|
109
130
|
|
|
110
131
|
```bash
|
|
111
|
-
codex mcp add fit-lms -- npx -y fit-lms-mcp
|
|
132
|
+
codex mcp add fit-lms -- npx -y fit-lms-mcp@latest
|
|
112
133
|
```
|
|
113
134
|
|
|
114
135
|
Or add to `~/.codex/config.toml`:
|
|
@@ -116,10 +137,10 @@ Or add to `~/.codex/config.toml`:
|
|
|
116
137
|
```toml
|
|
117
138
|
[mcp_servers.fit-lms]
|
|
118
139
|
command = "npx"
|
|
119
|
-
args = ["-y", "fit-lms-mcp"]
|
|
140
|
+
args = ["-y", "fit-lms-mcp@latest"]
|
|
120
141
|
```
|
|
121
142
|
|
|
122
|
-
See the [Codex MCP documentation](https://developers.openai.com/codex/mcp/).
|
|
143
|
+
See the [Codex MCP documentation](https://developers.openai.com/codex/mcp/).
|
|
123
144
|
|
|
124
145
|
### 4. Antigravity
|
|
125
146
|
|
|
@@ -130,7 +151,7 @@ Add to `~/.gemini/config/mcp_config.json`:
|
|
|
130
151
|
"mcpServers": {
|
|
131
152
|
"fit-lms": {
|
|
132
153
|
"command": "npx",
|
|
133
|
-
"args": ["-y", "fit-lms-mcp"]
|
|
154
|
+
"args": ["-y", "fit-lms-mcp@latest"]
|
|
134
155
|
}
|
|
135
156
|
}
|
|
136
157
|
}
|
|
@@ -145,7 +166,7 @@ Add to `~/.cursor/mcp.json` or `.cursor/mcp.json` in your project:
|
|
|
145
166
|
"mcpServers": {
|
|
146
167
|
"fit-lms": {
|
|
147
168
|
"command": "npx",
|
|
148
|
-
"args": ["-y", "fit-lms-mcp"]
|
|
169
|
+
"args": ["-y", "fit-lms-mcp@latest"]
|
|
149
170
|
}
|
|
150
171
|
}
|
|
151
172
|
}
|
|
@@ -160,7 +181,7 @@ Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:
|
|
|
160
181
|
"mcpServers": {
|
|
161
182
|
"fit-lms": {
|
|
162
183
|
"command": "npx",
|
|
163
|
-
"args": ["-y", "fit-lms-mcp"]
|
|
184
|
+
"args": ["-y", "fit-lms-mcp@latest"]
|
|
164
185
|
}
|
|
165
186
|
}
|
|
166
187
|
}
|
|
@@ -197,10 +218,14 @@ For OpenCode, use these values as a single command array. For Codex, use them as
|
|
|
197
218
|
| `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 |
|
|
198
219
|
| `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
220
|
| `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 |
|
|
221
|
+
| `get_site_announcements` | Optional zero-based `page` (default **0**) | Up to 10 posts per page from the [FIT site Announcements forum](https://lms.fit.hanu.vn/mod/forum/view.php?id=1), with discussion ID, title, message text, author, timestamp, discussion link, and Moodle-hosted attachments |
|
|
222
|
+
| `download_announcement_attachment` | Required `discussionId` from `get_site_announcements`. Pass the attachment's exact `fileUrl` when there are multiple files. | Saves one file of up to 100 MiB and returns the local path, filename, and byte count |
|
|
200
223
|
| `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
224
|
|
|
202
225
|
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
226
|
|
|
227
|
+
Each announcement download gets its own folder under `LMS_DOWNLOAD_DIR` so repeated downloads keep separate copies. `TIMEOUT_MS` applies to the file transfer.
|
|
228
|
+
|
|
204
229
|
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.
|
|
205
230
|
|
|
206
231
|
### Tool Argument Examples
|
|
@@ -238,6 +263,8 @@ Once connected to your AI assistant, you can ask:
|
|
|
238
263
|
- "Show all assignments and upcoming deadlines for the next 7 days."
|
|
239
264
|
- "What topics and materials are in course 660?"
|
|
240
265
|
- "Show the announcements for course 660."
|
|
266
|
+
- "Show the latest announcements on the FIT LMS homepage."
|
|
267
|
+
- "Download the PDF attached to the semester registration announcement."
|
|
241
268
|
- "Open the details of the exam guide listed in course 660."
|
|
242
269
|
|
|
243
270
|
---
|
package/dist/config/env.js
CHANGED
|
@@ -86,6 +86,9 @@ export function loadConfig(env = process.env) {
|
|
|
86
86
|
const config = { baseUrl, timeoutMs };
|
|
87
87
|
if (cacheTtlMs !== undefined)
|
|
88
88
|
config.cacheTtlMs = cacheTtlMs;
|
|
89
|
+
const downloadDir = env.LMS_DOWNLOAD_DIR?.trim();
|
|
90
|
+
if (downloadDir)
|
|
91
|
+
config.downloadDir = downloadDir;
|
|
89
92
|
if (moodleSession !== undefined)
|
|
90
93
|
config.moodleSession = moodleSession;
|
|
91
94
|
if (moodleSesskey !== undefined)
|
package/dist/mcp/server.js
CHANGED
|
@@ -8,6 +8,8 @@ import GetCourseContentsTool from "../tools/GetCourseContentsTool.js";
|
|
|
8
8
|
import GetAssignmentDetailTool from "../tools/GetAssignmentDetailTool.js";
|
|
9
9
|
import GetCourseAnnouncementsTool from "../tools/GetCourseAnnouncementsTool.js";
|
|
10
10
|
import GetMaterialDetailTool from "../tools/GetMaterialDetailTool.js";
|
|
11
|
+
import GetSiteAnnouncementsTool from "../tools/GetSiteAnnouncementsTool.js";
|
|
12
|
+
import DownloadAnnouncementAttachmentTool from "../tools/DownloadAnnouncementAttachmentTool.js";
|
|
11
13
|
export function createServer(config) {
|
|
12
14
|
const server = new MCPServer({
|
|
13
15
|
name: "hanu-lms-mcp",
|
|
@@ -23,6 +25,8 @@ export function createServer(config) {
|
|
|
23
25
|
server.addTool(GetAssignmentDetailTool);
|
|
24
26
|
server.addTool(GetCourseAnnouncementsTool);
|
|
25
27
|
server.addTool(GetMaterialDetailTool);
|
|
28
|
+
server.addTool(GetSiteAnnouncementsTool);
|
|
29
|
+
server.addTool(DownloadAnnouncementAttachmentTool);
|
|
26
30
|
return server;
|
|
27
31
|
}
|
|
28
32
|
export default createServer;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
const attachmentSchema = z.object({
|
|
3
|
+
filename: z.string().min(1),
|
|
4
|
+
url: z.string().min(1),
|
|
5
|
+
isdir: z.boolean().optional(),
|
|
6
|
+
filesize: z.number().int().nonnegative().safe().optional(),
|
|
7
|
+
});
|
|
8
|
+
export function announcementAttachments(post, baseUrl) {
|
|
9
|
+
if (post.id === undefined)
|
|
10
|
+
return [];
|
|
11
|
+
const endpoint = new URL(`${baseUrl}/pluginfile.php`);
|
|
12
|
+
const filePath = new RegExp(`^/[1-9]\\d*/mod_forum/(?:attachment|post)/${post.id}/(?:[^/]+/)*[^/]+$`);
|
|
13
|
+
const attachments = new Map();
|
|
14
|
+
for (const files of [post.attachments, post.messageinlinefiles]) {
|
|
15
|
+
if (!Array.isArray(files))
|
|
16
|
+
continue;
|
|
17
|
+
for (const file of files) {
|
|
18
|
+
const result = attachmentSchema.safeParse(file);
|
|
19
|
+
if (!result.success || result.data.isdir || !URL.canParse(result.data.url, endpoint))
|
|
20
|
+
continue;
|
|
21
|
+
const source = new URL(result.data.url, endpoint);
|
|
22
|
+
if (source.origin !== endpoint.origin || source.username || source.password)
|
|
23
|
+
continue;
|
|
24
|
+
const path = source.pathname === endpoint.pathname ? source.searchParams.get("file") :
|
|
25
|
+
source.pathname.startsWith(`${endpoint.pathname}/`) ? source.pathname.slice(endpoint.pathname.length) : null;
|
|
26
|
+
if (!path || !filePath.test(path))
|
|
27
|
+
continue;
|
|
28
|
+
const forceDownload = source.searchParams.get("forcedownload") === "1";
|
|
29
|
+
source.search = "";
|
|
30
|
+
source.hash = "";
|
|
31
|
+
if (source.pathname === endpoint.pathname)
|
|
32
|
+
source.searchParams.set("file", path);
|
|
33
|
+
if (forceDownload)
|
|
34
|
+
source.searchParams.set("forcedownload", "1");
|
|
35
|
+
if (!attachments.has(path)) {
|
|
36
|
+
attachments.set(path, { name: result.data.filename, url: source.toString(), sizeBytes: result.data.filesize });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return [...attachments.values()];
|
|
41
|
+
}
|
|
@@ -3,19 +3,23 @@ import { z } from "zod";
|
|
|
3
3
|
import { ANNOUNCEMENTS_PAGE_SIZE } from "../client.js";
|
|
4
4
|
import { MoodleError } from "../errors.js";
|
|
5
5
|
import { attr, hasClass, readableText, visibleElements } from "../html.js";
|
|
6
|
+
const announcementPostSchema = z.object({
|
|
7
|
+
id: z.number().int().positive().safe().optional(),
|
|
8
|
+
discussionid: z.number(),
|
|
9
|
+
hasparent: z.boolean(),
|
|
10
|
+
isdeleted: z.boolean(),
|
|
11
|
+
capabilities: z.object({ view: z.boolean().nullable() }),
|
|
12
|
+
subject: z.string(),
|
|
13
|
+
message: z.string(),
|
|
14
|
+
author: z.object({ fullname: z.string() }).nullish(),
|
|
15
|
+
timecreated: z.number().int().min(0).max(253402300799).nullish(),
|
|
16
|
+
attachments: z.unknown(),
|
|
17
|
+
messageinlinefiles: z.unknown(),
|
|
18
|
+
});
|
|
6
19
|
const discussionPostsSchema = z.object({
|
|
7
20
|
courseid: z.number(),
|
|
8
21
|
forumid: z.number(),
|
|
9
|
-
posts: z.array(
|
|
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
|
-
})),
|
|
22
|
+
posts: z.array(announcementPostSchema),
|
|
19
23
|
});
|
|
20
24
|
const responseError = () => new MoodleError("Unrecognized Moodle forum response", "MOODLE_RESPONSE_ERROR");
|
|
21
25
|
export function parseAnnouncementsForum(html, baseUrl) {
|
|
@@ -36,10 +40,14 @@ export function parseAnnouncementsForum(html, baseUrl) {
|
|
|
36
40
|
if (attr(row, "data-region") !== "discussion-list-item")
|
|
37
41
|
continue;
|
|
38
42
|
const id = Number(attr(row, "data-discussionid"));
|
|
39
|
-
const
|
|
43
|
+
const rowElements = visibleElements(row);
|
|
44
|
+
// FIT LMS leaves the row's forum ID blank and sets it on the favorite control.
|
|
45
|
+
const favorite = rowElements.find(element => attr(element, "data-type") === "favorite-toggle" &&
|
|
46
|
+
attr(element, "data-discussionid") === String(id));
|
|
47
|
+
const forumId = Number(attr(row, "data-forumid") || (favorite && attr(favorite, "data-forumid")));
|
|
40
48
|
if (!Number.isSafeInteger(id) || id <= 0 || !Number.isSafeInteger(forumId) || forumId <= 0)
|
|
41
49
|
continue;
|
|
42
|
-
const topic =
|
|
50
|
+
const topic = rowElements.find(element => hasClass(element, "topic"));
|
|
43
51
|
const hasDiscussionLink = topic && visibleElements(topic).some(element => {
|
|
44
52
|
const href = attr(element, "href");
|
|
45
53
|
if (element.tagName !== "a" || !href)
|
|
@@ -59,26 +67,31 @@ export function parseAnnouncementsForum(html, baseUrl) {
|
|
|
59
67
|
return [...discussions.values()].slice(0, ANNOUNCEMENTS_PAGE_SIZE);
|
|
60
68
|
}
|
|
61
69
|
export async function fetchCourseAnnouncements(client, courseId, discussions, baseUrl) {
|
|
70
|
+
return (await fetchAnnouncementPosts(client, courseId, discussions)).map(post => formatAnnouncement(post, baseUrl));
|
|
71
|
+
}
|
|
72
|
+
export async function fetchAnnouncementPosts(client, courseId, discussions, includeInlineFiles = false) {
|
|
62
73
|
if (!discussions.length)
|
|
63
74
|
return [];
|
|
64
75
|
const responses = await client.callBatch(discussions.map(({ id }) => ({
|
|
65
76
|
method: "mod_forum_get_discussion_posts",
|
|
66
|
-
args: { discussionid: id },
|
|
77
|
+
args: includeInlineFiles ? { discussionid: id, includeinlineattachments: true } : { discussionid: id },
|
|
67
78
|
})));
|
|
68
79
|
return discussions.flatMap(({ id, forumId }, index) => {
|
|
69
80
|
const result = discussionPostsSchema.safeParse(responses[index]);
|
|
70
81
|
if (!result.success || result.data.courseid !== courseId || result.data.forumid !== forumId)
|
|
71
82
|
throw responseError();
|
|
72
83
|
const post = result.data.posts.find(item => item.discussionid === id && !item.hasparent && !item.isdeleted && item.capabilities.view === true);
|
|
73
|
-
|
|
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
|
-
}];
|
|
84
|
+
return post ? [post] : [];
|
|
83
85
|
});
|
|
84
86
|
}
|
|
87
|
+
export function formatAnnouncement(post, baseUrl) {
|
|
88
|
+
const id = post.discussionid;
|
|
89
|
+
return {
|
|
90
|
+
id,
|
|
91
|
+
title: post.subject,
|
|
92
|
+
messageText: readableText(parseFragment(post.message)),
|
|
93
|
+
author: post.author?.fullname || undefined,
|
|
94
|
+
postedAt: post.timecreated ? new Date(post.timecreated * 1000).toISOString() : undefined,
|
|
95
|
+
url: `${baseUrl}/mod/forum/discuss.php?d=${id}`,
|
|
96
|
+
};
|
|
97
|
+
}
|
package/dist/moodle/client.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { createWriteStream } from "node:fs";
|
|
2
|
+
import { pipeline } from "node:stream/promises";
|
|
1
3
|
import { validateCredentials } from "./auth/credentials.js";
|
|
2
4
|
import { MoodleAuthError, MoodleError, MoodleNetworkError, MoodleSessionKeyError } from "./errors.js";
|
|
3
5
|
import { decodeMoodleResponses } from "./response.js";
|
|
@@ -7,6 +9,8 @@ export function isMaterialType(type) {
|
|
|
7
9
|
}
|
|
8
10
|
const responseError = () => new MoodleError("Moodle returned an invalid or oversized response", "MOODLE_RESPONSE_ERROR");
|
|
9
11
|
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
12
|
+
const MAX_ATTACHMENT_BYTES = 100 * 1024 * 1024;
|
|
13
|
+
const attachmentSizeError = () => new MoodleError("Announcement attachments are limited to 100 MiB", "ATTACHMENT_TOO_LARGE");
|
|
10
14
|
export class MoodleClient {
|
|
11
15
|
baseUrl;
|
|
12
16
|
authProvider;
|
|
@@ -83,6 +87,36 @@ export class MoodleClient {
|
|
|
83
87
|
const options = type === "resource" || type === "url" ? { forceview: "1" } : undefined;
|
|
84
88
|
return this.getPage(`/mod/${type}/view.php`, courseModuleId, "course module ID", options);
|
|
85
89
|
}
|
|
90
|
+
async downloadAttachment(fileUrl, destination) {
|
|
91
|
+
const endpoint = new URL(`${this.baseUrl}/pluginfile.php`);
|
|
92
|
+
const url = new URL(fileUrl);
|
|
93
|
+
if (url.origin !== endpoint.origin || url.username || url.password ||
|
|
94
|
+
(url.pathname !== endpoint.pathname && !url.pathname.startsWith(`${endpoint.pathname}/`))) {
|
|
95
|
+
throw new MoodleError("Invalid Moodle attachment URL", "INVALID_REQUEST");
|
|
96
|
+
}
|
|
97
|
+
url.searchParams.set("forcedownload", "1");
|
|
98
|
+
return this.withAuthRetry(credentials => this.withRequestTimeout(async (signal) => {
|
|
99
|
+
const response = await this.request(url, {}, credentials, signal);
|
|
100
|
+
if (!response.ok)
|
|
101
|
+
throw this.httpError(response.status);
|
|
102
|
+
if (response.status !== 200 || !response.body ||
|
|
103
|
+
!/^attachment(?:;|$)/i.test(response.headers.get("content-disposition") ?? "")) {
|
|
104
|
+
throw responseError();
|
|
105
|
+
}
|
|
106
|
+
if (Number(response.headers.get("content-length")) > MAX_ATTACHMENT_BYTES)
|
|
107
|
+
throw attachmentSizeError();
|
|
108
|
+
let size = 0;
|
|
109
|
+
await pipeline(response.body, async function* (chunks) {
|
|
110
|
+
for await (const chunk of chunks) {
|
|
111
|
+
size += chunk.byteLength;
|
|
112
|
+
if (size > MAX_ATTACHMENT_BYTES)
|
|
113
|
+
throw attachmentSizeError();
|
|
114
|
+
yield chunk;
|
|
115
|
+
}
|
|
116
|
+
}, createWriteStream(destination, { flags: "wx", mode: 0o600 }), { signal });
|
|
117
|
+
return size;
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
86
120
|
async getPage(path, id, label = "course ID", options) {
|
|
87
121
|
if (!Number.isSafeInteger(id) || id <= 0)
|
|
88
122
|
throw new MoodleError(`Invalid ${label}`, "INVALID_REQUEST");
|
|
@@ -124,26 +158,25 @@ export class MoodleClient {
|
|
|
124
158
|
httpError(status) {
|
|
125
159
|
return new MoodleError(`Moodle HTTP request failed (${status})`, "MOODLE_HTTP_ERROR");
|
|
126
160
|
}
|
|
127
|
-
async
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
161
|
+
async request(url, init, credentials, signal) {
|
|
162
|
+
const response = await fetch(url, {
|
|
163
|
+
...init,
|
|
164
|
+
headers: { ...init.headers, Cookie: `MoodleSession=${credentials.session}` },
|
|
165
|
+
redirect: "manual", signal,
|
|
166
|
+
});
|
|
167
|
+
if ([301, 302, 303, 307, 308, 401].includes(response.status))
|
|
168
|
+
throw this.loginError();
|
|
169
|
+
return response;
|
|
170
|
+
}
|
|
171
|
+
send(path, init, credentials, expectedHtml = false) {
|
|
172
|
+
return this.withRequestTimeout(async (signal) => {
|
|
173
|
+
const response = await this.request(`${this.baseUrl}${path}`, init, credentials, signal);
|
|
138
174
|
if (expectedHtml && response.ok && (!response.headers.get("content-type")?.toLowerCase().includes("text/html") ||
|
|
139
175
|
/^attachment\b/i.test(response.headers.get("content-disposition") ?? ""))) {
|
|
140
|
-
controller.abort();
|
|
141
176
|
throw responseError();
|
|
142
177
|
}
|
|
143
|
-
if (Number(response.headers.get("content-length")) > MAX_RESPONSE_BYTES)
|
|
144
|
-
controller.abort();
|
|
178
|
+
if (Number(response.headers.get("content-length")) > MAX_RESPONSE_BYTES)
|
|
145
179
|
throw responseError();
|
|
146
|
-
}
|
|
147
180
|
const reader = response.body?.getReader();
|
|
148
181
|
if (!reader)
|
|
149
182
|
return { response, body: "" };
|
|
@@ -155,10 +188,8 @@ export class MoodleClient {
|
|
|
155
188
|
if (done)
|
|
156
189
|
break;
|
|
157
190
|
size += value.byteLength;
|
|
158
|
-
if (size > MAX_RESPONSE_BYTES)
|
|
159
|
-
controller.abort();
|
|
191
|
+
if (size > MAX_RESPONSE_BYTES)
|
|
160
192
|
throw responseError();
|
|
161
|
-
}
|
|
162
193
|
chunks.push(value);
|
|
163
194
|
}
|
|
164
195
|
}
|
|
@@ -166,6 +197,13 @@ export class MoodleClient {
|
|
|
166
197
|
reader.releaseLock();
|
|
167
198
|
}
|
|
168
199
|
return { response, body: Buffer.concat(chunks).toString("utf8") };
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
async withRequestTimeout(read) {
|
|
203
|
+
const controller = new AbortController();
|
|
204
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
205
|
+
try {
|
|
206
|
+
return await read(controller.signal);
|
|
169
207
|
}
|
|
170
208
|
catch (error) {
|
|
171
209
|
if (error instanceof MoodleError)
|
|
@@ -176,6 +214,7 @@ export class MoodleClient {
|
|
|
176
214
|
}
|
|
177
215
|
finally {
|
|
178
216
|
clearTimeout(timer);
|
|
217
|
+
controller.abort();
|
|
179
218
|
}
|
|
180
219
|
}
|
|
181
220
|
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { mkdir, mkdtemp, rm } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { announcementAttachments } from "../moodle/api/announcement-attachments.js";
|
|
5
|
+
import { fetchAnnouncementPosts, formatAnnouncement, parseAnnouncementsForum } from "../moodle/api/course-announcements.js";
|
|
6
|
+
import { MoodleError } from "../moodle/errors.js";
|
|
7
|
+
// The FIT LMS front-page news forum has its own course, module, and forum IDs.
|
|
8
|
+
const SITE_FORUM = { courseId: 1, courseModuleId: 1, forumId: 1 };
|
|
9
|
+
function localFileName(name) {
|
|
10
|
+
const sanitized = name.replace(/[<>:"/\\|?*\p{Cc}]/gu, "_").replace(/[. ]+$/, "");
|
|
11
|
+
const reserved = /^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i.test(sanitized);
|
|
12
|
+
const safe = reserved ? `_${sanitized}` : sanitized;
|
|
13
|
+
return safe && Buffer.byteLength(safe) <= 255 ? safe : "attachment";
|
|
14
|
+
}
|
|
15
|
+
export class SiteAnnouncementService {
|
|
16
|
+
client;
|
|
17
|
+
constructor(client) {
|
|
18
|
+
this.client = client;
|
|
19
|
+
}
|
|
20
|
+
async getAnnouncements(page = 0) {
|
|
21
|
+
const { baseUrl } = this.client;
|
|
22
|
+
const html = await this.client.getForumPage(SITE_FORUM.courseModuleId, page);
|
|
23
|
+
const discussions = parseAnnouncementsForum(html, baseUrl);
|
|
24
|
+
if (!discussions || discussions.some(discussion => discussion.forumId !== SITE_FORUM.forumId)) {
|
|
25
|
+
throw new MoodleError("Unrecognized FIT site Announcements forum", "MOODLE_RESPONSE_ERROR");
|
|
26
|
+
}
|
|
27
|
+
const posts = await fetchAnnouncementPosts(this.client, SITE_FORUM.courseId, discussions, true);
|
|
28
|
+
return posts.map(post => ({
|
|
29
|
+
...formatAnnouncement(post, baseUrl),
|
|
30
|
+
attachments: announcementAttachments(post, baseUrl),
|
|
31
|
+
}));
|
|
32
|
+
}
|
|
33
|
+
async downloadAttachment(discussionId, fileUrl, downloadDir) {
|
|
34
|
+
const [post] = await fetchAnnouncementPosts(this.client, SITE_FORUM.courseId, [{ id: discussionId, forumId: SITE_FORUM.forumId }], true);
|
|
35
|
+
if (!post)
|
|
36
|
+
throw new MoodleError("Site announcement is unavailable", "ANNOUNCEMENT_NOT_AVAILABLE");
|
|
37
|
+
const attachments = announcementAttachments(post, this.client.baseUrl);
|
|
38
|
+
if (!fileUrl && attachments.length > 1) {
|
|
39
|
+
throw new MoodleError("This announcement has multiple files. Pass the file URL from get_site_announcements", "ATTACHMENT_SELECTION_REQUIRED");
|
|
40
|
+
}
|
|
41
|
+
const attachment = fileUrl ? attachments.find(file => file.url === fileUrl) : attachments[0];
|
|
42
|
+
if (!attachment)
|
|
43
|
+
throw new MoodleError("Requested file is unavailable on this site announcement", "ATTACHMENT_NOT_AVAILABLE");
|
|
44
|
+
const root = resolve(downloadDir ?? join(homedir(), "Downloads", "fit-lms"));
|
|
45
|
+
const fileName = localFileName(attachment.name);
|
|
46
|
+
let directory;
|
|
47
|
+
try {
|
|
48
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
49
|
+
directory = await mkdtemp(join(root, `announcement-${discussionId}-`));
|
|
50
|
+
const path = join(directory, fileName);
|
|
51
|
+
const sizeBytes = await this.client.downloadAttachment(attachment.url, path);
|
|
52
|
+
return { discussionId, fileName, path, sizeBytes };
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (directory)
|
|
56
|
+
await rm(directory, { recursive: true, force: true });
|
|
57
|
+
if (error instanceof MoodleError)
|
|
58
|
+
throw error;
|
|
59
|
+
throw new MoodleError("Could not save the announcement attachment locally", "ATTACHMENT_SAVE_ERROR");
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -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 { SiteAnnouncementService } from "../services/site-announcement.service.js";
|
|
7
|
+
class DownloadAnnouncementAttachmentTool extends MCPTool {
|
|
8
|
+
name = "download_announcement_attachment";
|
|
9
|
+
description = "Download one attachment from a site-wide FIT announcement to the local MCP server. Returns its saved path, filename, and size.";
|
|
10
|
+
annotations = { readOnlyHint: false, destructiveHint: false, idempotentHint: false };
|
|
11
|
+
schema = z.object({
|
|
12
|
+
discussionId: z.number().int().positive().safe().describe("Announcement ID from get_site_announcements"),
|
|
13
|
+
fileUrl: z.string().url().optional().describe("Exact attachment URL from get_site_announcements. Required if there is more than one file."),
|
|
14
|
+
});
|
|
15
|
+
async execute(input) {
|
|
16
|
+
const config = loadConfig();
|
|
17
|
+
const client = new MoodleClient({ ...config, authProvider: getAuthProvider(config) });
|
|
18
|
+
return new SiteAnnouncementService(client).downloadAttachment(input.discussionId, input.fileUrl, config.downloadDir);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export default DownloadAnnouncementAttachmentTool;
|
|
@@ -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 { SiteAnnouncementService } from "../services/site-announcement.service.js";
|
|
7
|
+
class GetSiteAnnouncementsTool extends MCPTool {
|
|
8
|
+
name = "get_site_announcements";
|
|
9
|
+
description = "Read up to 10 posts from the site-wide FIT Announcements forum, including text and downloadable attachments.";
|
|
10
|
+
annotations = { readOnlyHint: true, destructiveHint: false };
|
|
11
|
+
schema = z.object({
|
|
12
|
+
page: z.number().int().nonnegative().safe().optional().describe("Zero-based page number. Defaults to 0."),
|
|
13
|
+
});
|
|
14
|
+
async execute(input) {
|
|
15
|
+
const config = loadConfig();
|
|
16
|
+
const client = new MoodleClient({ ...config, authProvider: getAuthProvider(config) });
|
|
17
|
+
return new SiteAnnouncementService(client).getAnnouncements(input.page);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export default GetSiteAnnouncementsTool;
|
package/package.json
CHANGED
package/scripts/setup.mjs
CHANGED
|
@@ -5,7 +5,7 @@ import path from "node:path";
|
|
|
5
5
|
import os from "node:os";
|
|
6
6
|
import readline from "node:readline";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
|
-
import { execSync } from "node:child_process";
|
|
8
|
+
import childProcess, { execSync } from "node:child_process";
|
|
9
9
|
|
|
10
10
|
export function serializeEnvValue(val) {
|
|
11
11
|
const str = String(val ?? "");
|
|
@@ -148,6 +148,20 @@ export function updateJsonConfigFile(configPath, serverConfig, key = "mcpServers
|
|
|
148
148
|
}
|
|
149
149
|
}
|
|
150
150
|
|
|
151
|
+
function registerCodexMcp({ command, args }) {
|
|
152
|
+
const options = { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] };
|
|
153
|
+
try {
|
|
154
|
+
const servers = JSON.parse(childProcess.execFileSync("codex", ["mcp", "list", "--json"], options));
|
|
155
|
+
const hasFitLms = servers.some(server => server.name === "fit-lms");
|
|
156
|
+
const hasLegacyLms = servers.some(server => server.name === "hanu-lms");
|
|
157
|
+
const name = !hasFitLms && hasLegacyLms ? "hanu-lms" : "fit-lms";
|
|
158
|
+
childProcess.execFileSync("codex", ["mcp", "add", name, "--", command, ...args], options);
|
|
159
|
+
return true;
|
|
160
|
+
} catch {
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
151
165
|
export function askText(question) {
|
|
152
166
|
return new Promise((resolve) => {
|
|
153
167
|
const rl = readline.createInterface({
|
|
@@ -366,22 +380,17 @@ export async function runSetup() {
|
|
|
366
380
|
}
|
|
367
381
|
: {
|
|
368
382
|
command: "npx",
|
|
369
|
-
args: ["-y", "fit-lms-mcp"],
|
|
383
|
+
args: ["-y", "fit-lms-mcp@latest"],
|
|
370
384
|
};
|
|
371
385
|
|
|
372
|
-
const
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
type: "local",
|
|
381
|
-
command: ["npx", "-y", "fit-lms-mcp"],
|
|
382
|
-
enabled: true,
|
|
383
|
-
timeout: 60000,
|
|
384
|
-
};
|
|
386
|
+
const mcpCommand = [mcpServerConfig.command, ...mcpServerConfig.args];
|
|
387
|
+
const openCodeConfig = {
|
|
388
|
+
type: "local",
|
|
389
|
+
command: mcpCommand,
|
|
390
|
+
enabled: true,
|
|
391
|
+
timeout: 60000,
|
|
392
|
+
};
|
|
393
|
+
const codexConfigPath = path.join(process.env.CODEX_HOME || path.join(os.homedir(), ".codex"), "config.toml");
|
|
385
394
|
|
|
386
395
|
// 7. Auto-detect and configure: Claude Code, OpenCode, Codex, Antigravity
|
|
387
396
|
console.log("\n-------------------------------------------------");
|
|
@@ -413,18 +422,9 @@ export async function runSetup() {
|
|
|
413
422
|
},
|
|
414
423
|
{
|
|
415
424
|
name: "Codex",
|
|
416
|
-
detect: () =>
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
return fs.existsSync(dir) || fs.existsSync(altDir);
|
|
420
|
-
},
|
|
421
|
-
getConfigPath: () => {
|
|
422
|
-
const dir = path.join(os.homedir(), ".codex");
|
|
423
|
-
if (fs.existsSync(path.join(dir, "mcp.json"))) return path.join(dir, "mcp.json");
|
|
424
|
-
return path.join(dir, "config.json");
|
|
425
|
-
},
|
|
426
|
-
key: "mcpServers",
|
|
427
|
-
getConfig: () => mcpServerConfig,
|
|
425
|
+
detect: () => fs.existsSync(path.dirname(codexConfigPath)) || fs.existsSync(path.join(os.homedir(), ".config/codex")),
|
|
426
|
+
getConfigPath: () => codexConfigPath,
|
|
427
|
+
register: () => registerCodexMcp(mcpServerConfig),
|
|
428
428
|
},
|
|
429
429
|
{
|
|
430
430
|
name: "Antigravity",
|
|
@@ -445,7 +445,9 @@ export async function runSetup() {
|
|
|
445
445
|
const targetPath = client.getConfigPath();
|
|
446
446
|
const answer = await ask(`Phát hiện ${client.name} (${targetPath}).\n 👉 Tự động đăng ký MCP vào ${client.name}? (Y/n): `);
|
|
447
447
|
if (!answer || answer.toLowerCase() === "y") {
|
|
448
|
-
const ok =
|
|
448
|
+
const ok = client.register
|
|
449
|
+
? client.register()
|
|
450
|
+
: updateJsonConfigFile(targetPath, client.getConfig(), client.key);
|
|
449
451
|
if (ok) {
|
|
450
452
|
console.log(` ✅ Đã đăng ký thành công vào: ${targetPath}\n`);
|
|
451
453
|
} else {
|
|
@@ -464,9 +466,7 @@ export async function runSetup() {
|
|
|
464
466
|
console.log(" Cấu hình MCP cho các AI Client (Copy thủ công)");
|
|
465
467
|
console.log("=================================================\n");
|
|
466
468
|
|
|
467
|
-
const cliExample =
|
|
468
|
-
? `claude mcp add fit-lms -- ${nodePath} --env-file=${envPath} ${distIndexPath}`
|
|
469
|
-
: `claude mcp add fit-lms -- npx -y fit-lms-mcp`;
|
|
469
|
+
const cliExample = `claude mcp add fit-lms -- ${mcpCommand.join(" ")}`;
|
|
470
470
|
|
|
471
471
|
console.log("1. Claude Code:");
|
|
472
472
|
console.log(` Lệnh CLI: ${cliExample}`);
|
|
@@ -476,8 +476,10 @@ export async function runSetup() {
|
|
|
476
476
|
console.log("\n2. OpenCode (~/.config/opencode/opencode.jsonc):");
|
|
477
477
|
console.log(JSON.stringify({ mcp: { "fit-lms": openCodeConfig } }, null, 2));
|
|
478
478
|
|
|
479
|
-
console.log(
|
|
480
|
-
console.log(
|
|
479
|
+
console.log(`\n3. Codex (${codexConfigPath}):`);
|
|
480
|
+
console.log("[mcp_servers.fit-lms]");
|
|
481
|
+
console.log(`command = ${JSON.stringify(mcpServerConfig.command)}`);
|
|
482
|
+
console.log(`args = ${JSON.stringify(mcpServerConfig.args)}`);
|
|
481
483
|
|
|
482
484
|
console.log("\n4. Antigravity (~/.gemini/config/mcp_config.json):");
|
|
483
485
|
console.log(JSON.stringify({ mcpServers: { "fit-lms": mcpServerConfig } }, null, 2));
|