fit-lms-mcp 2.2.1 → 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 +21 -0
- 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/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
|
|
@@ -58,6 +72,7 @@ For use via `npx`, create `~/.fit-lms-mcp/.env` with the settings below and rest
|
|
|
58
72
|
| `LMS_PASSWORD` | Password for automatic login (Option 1; automatically logs in and refreshes expired sessions) |
|
|
59
73
|
| `TIMEOUT_MS` | Optional request timeout in milliseconds (default: `5000`, maximum: `2147483647`) |
|
|
60
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. |
|
|
61
76
|
| `LMS_MOODLE_SESSION` | MoodleSession cookie value (Option 2 - Manual legacy session) |
|
|
62
77
|
| `LMS_MOODLE_SESSKEY` | sesskey query parameter from the same session (Option 2 - Manual legacy session) |
|
|
63
78
|
|
|
@@ -203,10 +218,14 @@ For OpenCode, use these values as a single command array. For Codex, use them as
|
|
|
203
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 |
|
|
204
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) |
|
|
205
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 |
|
|
206
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 |
|
|
207
224
|
|
|
208
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.
|
|
209
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
|
+
|
|
210
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.
|
|
211
230
|
|
|
212
231
|
### Tool Argument Examples
|
|
@@ -244,6 +263,8 @@ Once connected to your AI assistant, you can ask:
|
|
|
244
263
|
- "Show all assignments and upcoming deadlines for the next 7 days."
|
|
245
264
|
- "What topics and materials are in course 660?"
|
|
246
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."
|
|
247
268
|
- "Open the details of the exam guide listed in course 660."
|
|
248
269
|
|
|
249
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;
|