fit-lms-mcp 2.0.1 → 2.2.1

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 CHANGED
@@ -13,7 +13,7 @@ Requires **Node.js 22 or later**. Node.js 24 LTS is recommended. CI tests Node.j
13
13
  Run the interactive setup assistant directly with `npx`:
14
14
 
15
15
  ```bash
16
- npx fit-lms-mcp setup
16
+ npx -y fit-lms-mcp@latest setup
17
17
  ```
18
18
 
19
19
  Or, from a local workspace:
@@ -28,9 +28,15 @@ The interactive setup assistant will:
28
28
  1. Prompt for your LMS student ID and password (safely masked).
29
29
  2. Test the connection against HANU LMS immediately.
30
30
  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**). For Codex, use the manual configuration below.
31
+ 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.
32
32
 
33
- After running setup, you can use the MCP server directly in your AI client with `npx -y fit-lms-mcp`.
33
+ 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.
34
+
35
+ ### Updating an existing installation
36
+
37
+ 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.
38
+
39
+ If you installed the package globally, run `npm install -g fit-lms-mcp@latest` and restart your client.
34
40
 
35
41
  ---
36
42
 
@@ -51,6 +57,7 @@ For use via `npx`, create `~/.fit-lms-mcp/.env` with the settings below and rest
51
57
  | `LMS_USERNAME` | Student ID / username for automatic login (Option 1 - Recommended) |
52
58
  | `LMS_PASSWORD` | Password for automatic login (Option 1; automatically logs in and refreshes expired sessions) |
53
59
  | `TIMEOUT_MS` | Optional request timeout in milliseconds (default: `5000`, maximum: `2147483647`) |
60
+ | `LMS_CACHE_TTL_MS` | Optional course metadata cache lifetime in milliseconds (default `900000`, maximum `2147483647`, `0` disables caching) |
54
61
  | `LMS_MOODLE_SESSION` | MoodleSession cookie value (Option 2 - Manual legacy session) |
55
62
  | `LMS_MOODLE_SESSKEY` | sesskey query parameter from the same session (Option 2 - Manual legacy session) |
56
63
 
@@ -69,7 +76,7 @@ The following examples use the credentials saved by the `npx` setup flow.
69
76
  Register via CLI:
70
77
 
71
78
  ```bash
72
- claude mcp add fit-lms -- npx -y fit-lms-mcp
79
+ claude mcp add fit-lms -- npx -y fit-lms-mcp@latest
73
80
  ```
74
81
 
75
82
  Or add to `~/.claude.json`:
@@ -79,7 +86,7 @@ Or add to `~/.claude.json`:
79
86
  "mcpServers": {
80
87
  "fit-lms": {
81
88
  "command": "npx",
82
- "args": ["-y", "fit-lms-mcp"]
89
+ "args": ["-y", "fit-lms-mcp@latest"]
83
90
  }
84
91
  }
85
92
  }
@@ -94,7 +101,7 @@ Add to `~/.config/opencode/opencode.jsonc` (or project `opencode.json`):
94
101
  "mcp": {
95
102
  "fit-lms": {
96
103
  "type": "local",
97
- "command": ["npx", "-y", "fit-lms-mcp"],
104
+ "command": ["npx", "-y", "fit-lms-mcp@latest"],
98
105
  "enabled": true,
99
106
  "timeout": 60000
100
107
  }
@@ -107,7 +114,7 @@ Add to `~/.config/opencode/opencode.jsonc` (or project `opencode.json`):
107
114
  Register via CLI:
108
115
 
109
116
  ```bash
110
- codex mcp add fit-lms -- npx -y fit-lms-mcp
117
+ codex mcp add fit-lms -- npx -y fit-lms-mcp@latest
111
118
  ```
112
119
 
113
120
  Or add to `~/.codex/config.toml`:
@@ -115,10 +122,10 @@ Or add to `~/.codex/config.toml`:
115
122
  ```toml
116
123
  [mcp_servers.fit-lms]
117
124
  command = "npx"
118
- args = ["-y", "fit-lms-mcp"]
125
+ args = ["-y", "fit-lms-mcp@latest"]
119
126
  ```
120
127
 
121
- See the [Codex MCP documentation](https://developers.openai.com/codex/mcp/). The setup assistant currently writes a JSON configuration for Codex; use the CLI command or TOML configuration above instead.
128
+ See the [Codex MCP documentation](https://developers.openai.com/codex/mcp/).
122
129
 
123
130
  ### 4. Antigravity
124
131
 
@@ -129,7 +136,7 @@ Add to `~/.gemini/config/mcp_config.json`:
129
136
  "mcpServers": {
130
137
  "fit-lms": {
131
138
  "command": "npx",
132
- "args": ["-y", "fit-lms-mcp"]
139
+ "args": ["-y", "fit-lms-mcp@latest"]
133
140
  }
134
141
  }
135
142
  }
@@ -144,7 +151,7 @@ Add to `~/.cursor/mcp.json` or `.cursor/mcp.json` in your project:
144
151
  "mcpServers": {
145
152
  "fit-lms": {
146
153
  "command": "npx",
147
- "args": ["-y", "fit-lms-mcp"]
154
+ "args": ["-y", "fit-lms-mcp@latest"]
148
155
  }
149
156
  }
150
157
  }
@@ -159,7 +166,7 @@ Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:
159
166
  "mcpServers": {
160
167
  "fit-lms": {
161
168
  "command": "npx",
162
- "args": ["-y", "fit-lms-mcp"]
169
+ "args": ["-y", "fit-lms-mcp@latest"]
163
170
  }
164
171
  }
165
172
  }
@@ -190,10 +197,17 @@ For OpenCode, use these values as a single command array. For Codex, use them as
190
197
 
191
198
  | Tool | Input | Output |
192
199
  | :--- | :--- | :--- |
193
- | `get_my_courses` | Optional `classification`: `all` (default), `inprogress`, `future`, `past` | Enrolled courses with ID, course name, short name, start/end dates, progress percentage, and LMS URL |
200
+ | `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
201
  | `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 |
202
+ | `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
203
  | `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) |
204
+ | `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
+ | `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 |
206
+ | `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
+
208
+ 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
+
210
+ 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
211
 
198
212
  ### Tool Argument Examples
199
213
 
@@ -205,6 +219,10 @@ For OpenCode, use these values as a single command array. For Codex, use them as
205
219
  ```json
206
220
  {}
207
221
  ```
222
+ - Get detailed submission status and instructions for an assignment:
223
+ ```json
224
+ { "courseModuleId": 42 }
225
+ ```
208
226
  - Deadlines for the next 14 days for a specific course:
209
227
  ```json
210
228
  { "courseId": 660, "daysAhead": 14 }
@@ -225,6 +243,8 @@ Once connected to your AI assistant, you can ask:
225
243
  - "List my enrolled courses on HANU FIT LMS."
226
244
  - "Show all assignments and upcoming deadlines for the next 7 days."
227
245
  - "What topics and materials are in course 660?"
246
+ - "Show the announcements for course 660."
247
+ - "Open the details of the exam guide listed in course 660."
228
248
 
229
249
  ---
230
250
 
@@ -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)
@@ -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 authProvider = getAuthProvider(config);
22
- const client = new MoodleClient({
23
- baseUrl: config.baseUrl,
24
- authProvider,
25
- timeoutMs: config.timeoutMs,
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.keys()].some(key => key !== "id" && key !== "sesskey"))
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}`;
@@ -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, courseId) {
69
- if (!Number.isSafeInteger(courseId) || courseId <= 0)
70
- throw new MoodleError("Invalid course ID", "INVALID_REQUEST");
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 { response, body } = await this.send(`${path}?id=${courseId}`, { headers: { Accept: "text/html" } }, credentials);
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();
@@ -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({ courseId: z.number().int().positive().safe().describe("Enrolled course ID from get_my_courses") });
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
- const client = new MoodleClient({ baseUrl: config.baseUrl, authProvider: getAuthProvider(config), timeoutMs: config.timeoutMs });
15
- return new CourseContentService(client, config.baseUrl).getCourseContents(input.courseId);
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fit-lms-mcp",
3
- "version": "2.0.1",
3
+ "version": "2.2.1",
4
4
  "description": "Model Context Protocol (MCP) server for HANU Faculty of Information Technology (FIT) Moodle LMS",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
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({
@@ -216,10 +230,11 @@ export function ask(question, isPassword = false) {
216
230
  return isPassword ? askPassword(question) : askText(question);
217
231
  }
218
232
 
219
- export function saveEnvFile(envPath, { baseUrl, timeoutMs, username, password }) {
233
+ export function saveEnvFile(envPath, { baseUrl, timeoutMs, cacheTtlMs, username, password }) {
220
234
  const envContent = [
221
235
  `LMS_BASE_URL=${serializeEnvValue(baseUrl)}`,
222
236
  `TIMEOUT_MS=${serializeEnvValue(timeoutMs)}`,
237
+ ...(cacheTtlMs === undefined ? [] : [`LMS_CACHE_TTL_MS=${serializeEnvValue(cacheTtlMs)}`]),
223
238
  "",
224
239
  "# Auto-login credentials",
225
240
  `LMS_USERNAME=${serializeEnvValue(username)}`,
@@ -275,6 +290,7 @@ export async function runSetup() {
275
290
  let existingBaseUrl = "https://lms.fit.hanu.vn";
276
291
  let existingUsername = "";
277
292
  let existingTimeout = "5000";
293
+ let existingCacheTtlMs;
278
294
 
279
295
  if (fs.existsSync(envPath)) {
280
296
  try {
@@ -282,6 +298,7 @@ export async function runSetup() {
282
298
  if (parsed.LMS_BASE_URL) existingBaseUrl = parsed.LMS_BASE_URL;
283
299
  if (parsed.LMS_USERNAME) existingUsername = parsed.LMS_USERNAME;
284
300
  if (parsed.TIMEOUT_MS) existingTimeout = parsed.TIMEOUT_MS;
301
+ existingCacheTtlMs = parsed.LMS_CACHE_TTL_MS;
285
302
  } catch {
286
303
  // Ignore read errors
287
304
  }
@@ -294,6 +311,7 @@ export async function runSetup() {
294
311
  if (parsed.LMS_BASE_URL) existingBaseUrl = parsed.LMS_BASE_URL;
295
312
  if (parsed.LMS_USERNAME) existingUsername = parsed.LMS_USERNAME;
296
313
  if (parsed.TIMEOUT_MS) existingTimeout = parsed.TIMEOUT_MS;
314
+ existingCacheTtlMs = parsed.LMS_CACHE_TTL_MS;
297
315
  } catch {
298
316
  // Ignore read errors
299
317
  }
@@ -351,7 +369,7 @@ export async function runSetup() {
351
369
  }
352
370
 
353
371
  // 5. Save to .env with 0600 permissions and escaped values
354
- saveEnvFile(envPath, { baseUrl, timeoutMs, username, password });
372
+ saveEnvFile(envPath, { baseUrl, timeoutMs, cacheTtlMs: existingCacheTtlMs, username, password });
355
373
  console.log(`\n🎉 Đã lưu cấu hình an toàn (permissions: 0600) vào: ${envPath}`);
356
374
 
357
375
  // 6. Define configurations for clients
@@ -362,22 +380,17 @@ export async function runSetup() {
362
380
  }
363
381
  : {
364
382
  command: "npx",
365
- args: ["-y", "fit-lms-mcp"],
383
+ args: ["-y", "fit-lms-mcp@latest"],
366
384
  };
367
385
 
368
- const openCodeConfig = isLocalDev
369
- ? {
370
- type: "local",
371
- command: [nodePath, `--env-file=${envPath}`, distIndexPath],
372
- enabled: true,
373
- timeout: 60000,
374
- }
375
- : {
376
- type: "local",
377
- command: ["npx", "-y", "fit-lms-mcp"],
378
- enabled: true,
379
- timeout: 60000,
380
- };
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");
381
394
 
382
395
  // 7. Auto-detect and configure: Claude Code, OpenCode, Codex, Antigravity
383
396
  console.log("\n-------------------------------------------------");
@@ -409,18 +422,9 @@ export async function runSetup() {
409
422
  },
410
423
  {
411
424
  name: "Codex",
412
- detect: () => {
413
- const dir = path.join(os.homedir(), ".codex");
414
- const altDir = path.join(os.homedir(), ".config/codex");
415
- return fs.existsSync(dir) || fs.existsSync(altDir);
416
- },
417
- getConfigPath: () => {
418
- const dir = path.join(os.homedir(), ".codex");
419
- if (fs.existsSync(path.join(dir, "mcp.json"))) return path.join(dir, "mcp.json");
420
- return path.join(dir, "config.json");
421
- },
422
- key: "mcpServers",
423
- getConfig: () => mcpServerConfig,
425
+ detect: () => fs.existsSync(path.dirname(codexConfigPath)) || fs.existsSync(path.join(os.homedir(), ".config/codex")),
426
+ getConfigPath: () => codexConfigPath,
427
+ register: () => registerCodexMcp(mcpServerConfig),
424
428
  },
425
429
  {
426
430
  name: "Antigravity",
@@ -441,7 +445,9 @@ export async function runSetup() {
441
445
  const targetPath = client.getConfigPath();
442
446
  const answer = await ask(`Phát hiện ${client.name} (${targetPath}).\n 👉 Tự động đăng ký MCP vào ${client.name}? (Y/n): `);
443
447
  if (!answer || answer.toLowerCase() === "y") {
444
- const ok = updateJsonConfigFile(targetPath, client.getConfig(), client.key);
448
+ const ok = client.register
449
+ ? client.register()
450
+ : updateJsonConfigFile(targetPath, client.getConfig(), client.key);
445
451
  if (ok) {
446
452
  console.log(` ✅ Đã đăng ký thành công vào: ${targetPath}\n`);
447
453
  } else {
@@ -460,9 +466,7 @@ export async function runSetup() {
460
466
  console.log(" Cấu hình MCP cho các AI Client (Copy thủ công)");
461
467
  console.log("=================================================\n");
462
468
 
463
- const cliExample = isLocalDev
464
- ? `claude mcp add fit-lms -- ${nodePath} --env-file=${envPath} ${distIndexPath}`
465
- : `claude mcp add fit-lms -- npx -y fit-lms-mcp`;
469
+ const cliExample = `claude mcp add fit-lms -- ${mcpCommand.join(" ")}`;
466
470
 
467
471
  console.log("1. Claude Code:");
468
472
  console.log(` Lệnh CLI: ${cliExample}`);
@@ -472,8 +476,10 @@ export async function runSetup() {
472
476
  console.log("\n2. OpenCode (~/.config/opencode/opencode.jsonc):");
473
477
  console.log(JSON.stringify({ mcp: { "fit-lms": openCodeConfig } }, null, 2));
474
478
 
475
- console.log("\n3. Codex (~/.codex/config.json):");
476
- console.log(JSON.stringify({ mcpServers: { "fit-lms": mcpServerConfig } }, null, 2));
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)}`);
477
483
 
478
484
  console.log("\n4. Antigravity (~/.gemini/config/mcp_config.json):");
479
485
  console.log(JSON.stringify({ mcpServers: { "fit-lms": mcpServerConfig } }, null, 2));