@av-leschinskiy/moodle-mcp 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +168 -2
- package/dist/api/functions.d.ts +21 -0
- package/dist/api/functions.d.ts.map +1 -0
- package/dist/api/functions.js +21 -0
- package/dist/api/functions.js.map +1 -0
- package/dist/api/moodle-client.d.ts +110 -0
- package/dist/api/moodle-client.d.ts.map +1 -0
- package/dist/api/moodle-client.js +308 -0
- package/dist/api/moodle-client.js.map +1 -0
- package/dist/auth/launch.d.ts +34 -0
- package/dist/auth/launch.d.ts.map +1 -0
- package/dist/auth/launch.js +68 -0
- package/dist/auth/launch.js.map +1 -0
- package/dist/auth/token-store.d.ts +51 -0
- package/dist/auth/token-store.d.ts.map +1 -0
- package/dist/auth/token-store.js +99 -0
- package/dist/auth/token-store.js.map +1 -0
- package/dist/cli/chrome.d.ts +65 -0
- package/dist/cli/chrome.d.ts.map +1 -0
- package/dist/cli/chrome.js +189 -0
- package/dist/cli/chrome.js.map +1 -0
- package/dist/cli/login.d.ts +19 -0
- package/dist/cli/login.d.ts.map +1 -0
- package/dist/cli/login.js +89 -0
- package/dist/cli/login.js.map +1 -0
- package/dist/config.d.ts +83 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +140 -0
- package/dist/config.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +36 -0
- package/dist/index.js.map +1 -0
- package/dist/server.d.ts +11 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +136 -0
- package/dist/server.js.map +1 -0
- package/dist/stdout-guard.d.ts +13 -0
- package/dist/stdout-guard.d.ts.map +1 -0
- package/dist/stdout-guard.js +16 -0
- package/dist/stdout-guard.js.map +1 -0
- package/dist/tools/assignments.d.ts +186 -0
- package/dist/tools/assignments.d.ts.map +1 -0
- package/dist/tools/assignments.js +235 -0
- package/dist/tools/assignments.js.map +1 -0
- package/dist/tools/files.d.ts +27 -0
- package/dist/tools/files.d.ts.map +1 -0
- package/dist/tools/files.js +81 -0
- package/dist/tools/files.js.map +1 -0
- package/dist/tools/grading.d.ts +52 -0
- package/dist/tools/grading.d.ts.map +1 -0
- package/dist/tools/grading.js +140 -0
- package/dist/tools/grading.js.map +1 -0
- package/dist/tools/index.d.ts +214 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +16 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/site.d.ts +51 -0
- package/dist/tools/site.d.ts.map +1 -0
- package/dist/tools/site.js +61 -0
- package/dist/tools/site.js.map +1 -0
- package/dist/tools/types.d.ts +54 -0
- package/dist/tools/types.d.ts.map +1 -0
- package/dist/tools/types.js +22 -0
- package/dist/tools/types.js.map +1 -0
- package/dist/utils/format.d.ts +37 -0
- package/dist/utils/format.d.ts.map +1 -0
- package/dist/utils/format.js +103 -0
- package/dist/utils/format.js.map +1 -0
- package/dist/utils/logger.d.ts +13 -0
- package/dist/utils/logger.d.ts.map +1 -0
- package/dist/utils/logger.js +38 -0
- package/dist/utils/logger.js.map +1 -0
- package/dist/utils/schemas.d.ts +9 -0
- package/dist/utils/schemas.d.ts.map +1 -0
- package/dist/utils/schemas.js +21 -0
- package/dist/utils/schemas.js.map +1 -0
- package/dist/version.d.ts +15 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +15 -0
- package/dist/version.js.map +1 -0
- package/package.json +73 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Alexander Leschinskiy
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,169 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Moodle MCP Server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An MCP server for AI assistants (Claude Code, Cursor, Codex and other stdio clients)
|
|
4
|
+
on top of the [Moodle](https://moodle.org) web services REST API. It is built for
|
|
5
|
+
**teachers**: the assistant can see courses, assignments and student submissions,
|
|
6
|
+
download submission files, and save a grade with feedback, acting as the teacher
|
|
7
|
+
and only after the teacher confirms. Unlike student-oriented Moodle MCP servers,
|
|
8
|
+
the focus here is reviewing assignments and grading.
|
|
9
|
+
|
|
10
|
+
The server works with any Moodle site that has the mobile web service
|
|
11
|
+
(`moodle_mobile_app`) enabled: the token is issued the same way as for the Moodle
|
|
12
|
+
mobile app, so login through an external OAuth provider with a captcha works too.
|
|
13
|
+
|
|
14
|
+
## Prerequisites
|
|
15
|
+
|
|
16
|
+
- [Node.js](https://nodejs.org/) ≥ 22.
|
|
17
|
+
- Google Chrome or Chromium, for the `moodle-mcp-login` command.
|
|
18
|
+
- Mobile app access enabled on the Moodle site (Site administration → Mobile app).
|
|
19
|
+
To check: `<site>/admin/tool/mobile/launch.php` should open rather than return
|
|
20
|
+
an error.
|
|
21
|
+
|
|
22
|
+
## Quick start
|
|
23
|
+
|
|
24
|
+
The example below uses `https://moodle.example.org`; replace it with your Moodle
|
|
25
|
+
address exactly as it appears in the browser (scheme, host, path; a trailing
|
|
26
|
+
slash does not matter).
|
|
27
|
+
|
|
28
|
+
1. Log in, once per machine and again whenever a tool returns a login error
|
|
29
|
+
([Moodle login and server token](docs/features/login.md), in Russian):
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
MOODLE_URL=https://moodle.example.org npx -y -p @av-leschinskiy/moodle-mcp moodle-mcp-login
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
A Chrome window opens: log in to the site as usual and solve the captcha
|
|
36
|
+
yourself. The command prints "Logged in as <name> on <site>" and closes the
|
|
37
|
+
window. Without `-p`, npx would start the server instead of the login command.
|
|
38
|
+
Chrome is looked up in PATH; on macOS and Windows, set its path in
|
|
39
|
+
`MOODLE_CHROME`.
|
|
40
|
+
|
|
41
|
+
2. Add the server to your client. Claude Code:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
claude mcp add moodle -e MOODLE_URL=https://moodle.example.org -- npx -y @av-leschinskiy/moodle-mcp
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Add `-s user` to enable it for all projects; without it, only for the current one.
|
|
48
|
+
|
|
49
|
+
Codex, with a command or a block in `~/.codex/config.toml`:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
codex mcp add moodle --env MOODLE_URL=https://moodle.example.org -- npx -y @av-leschinskiy/moodle-mcp
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
```toml
|
|
56
|
+
[mcp_servers.moodle]
|
|
57
|
+
command = "npx"
|
|
58
|
+
args = ["-y", "@av-leschinskiy/moodle-mcp"]
|
|
59
|
+
env = { MOODLE_URL = "https://moodle.example.org" }
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Cursor and other clients: a stdio server with the command
|
|
63
|
+
`npx -y @av-leschinskiy/moodle-mcp` and the `MOODLE_URL` variable:
|
|
64
|
+
|
|
65
|
+
```json
|
|
66
|
+
{
|
|
67
|
+
"mcpServers": {
|
|
68
|
+
"moodle": {
|
|
69
|
+
"command": "npx",
|
|
70
|
+
"args": ["-y", "@av-leschinskiy/moodle-mcp"],
|
|
71
|
+
"env": { "MOODLE_URL": "https://moodle.example.org" }
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
3. Check: ask the assistant "show my Moodle courses".
|
|
78
|
+
|
|
79
|
+
From a repository clone, use `node <clone>/dist/index.js` and
|
|
80
|
+
`node <clone>/dist/cli/login.js` instead of `npx`: `dist/` is committed, no build
|
|
81
|
+
is needed.
|
|
82
|
+
|
|
83
|
+
## What's inside
|
|
84
|
+
|
|
85
|
+
<!-- BEGIN:tools-table (generated by scripts/tool-docs.mjs) -->
|
|
86
|
+
|
|
87
|
+
**7 tools** in total; **1** of them requires user confirmation.
|
|
88
|
+
|
|
89
|
+
| Category | Tools | Confirmation | Covers |
|
|
90
|
+
|---|---:|---:|---|
|
|
91
|
+
| **Site** | 2 | — | who I am, Moodle version, available functions, my courses |
|
|
92
|
+
| **Assignments and submissions** | 3 | — | course assignments, participants and submission statuses, full submission |
|
|
93
|
+
| **Files** | 1 | — | downloading submission files to disk |
|
|
94
|
+
| **Grading** | 1 | 1 | grade and feedback for a student |
|
|
95
|
+
|
|
96
|
+
<details>
|
|
97
|
+
<summary>Full list of names</summary>
|
|
98
|
+
|
|
99
|
+
**Site**
|
|
100
|
+
|
|
101
|
+
- `moodle_list_courses`
|
|
102
|
+
- `moodle_site_info`
|
|
103
|
+
|
|
104
|
+
**Assignments and submissions**
|
|
105
|
+
|
|
106
|
+
- `moodle_get_submission`
|
|
107
|
+
- `moodle_list_assignments`
|
|
108
|
+
- `moodle_list_submissions`
|
|
109
|
+
|
|
110
|
+
**Files**
|
|
111
|
+
|
|
112
|
+
- `moodle_download_file`
|
|
113
|
+
|
|
114
|
+
**Grading**
|
|
115
|
+
|
|
116
|
+
- `moodle_save_grade` — confirmation
|
|
117
|
+
|
|
118
|
+
</details>
|
|
119
|
+
|
|
120
|
+
<!-- END:tools-table -->
|
|
121
|
+
|
|
122
|
+
The server acts **on your behalf**: it sees and changes the same things you do in
|
|
123
|
+
the Moodle interface. The host asks for confirmation only for writes that students
|
|
124
|
+
will see, i.e. grades and feedback (`destructiveHint: true`). Downloading a file
|
|
125
|
+
also writes, but only to your disk, and needs no confirmation.
|
|
126
|
+
|
|
127
|
+
Responses are trimmed for the model context: HTML in descriptions and submissions
|
|
128
|
+
is converted to plain text, times to ISO, a grade that is not set to `null`, and
|
|
129
|
+
participant emails are never returned.
|
|
130
|
+
|
|
131
|
+
## Configuration
|
|
132
|
+
|
|
133
|
+
<!-- BEGIN:env-table (generated by scripts/env-docs.mjs) -->
|
|
134
|
+
|
|
135
|
+
| Variable | Required | Default | Description |
|
|
136
|
+
|---|:---:|---|---|
|
|
137
|
+
| `MOODLE_URL` | yes | — | Moodle site address (wwwroot), e.g. `https://moodle.example.org` |
|
|
138
|
+
| `MOODLE_TOKEN_FILE` | — | `~/.config/mcp-moodle/token.json` | Where `moodle-mcp-login` saves the token (path is resolved via `homedir()`) |
|
|
139
|
+
| `MOODLE_TOKEN` | — | — | Web service token override (CI / smoke tests) |
|
|
140
|
+
| `MOODLE_TIMEOUT` | — | `30000` | Timeout of a single API request (ms) |
|
|
141
|
+
| `MOODLE_CHROME` | — | — | Chrome/Chromium binary for `moodle-mcp-login` (looked up in PATH by default) |
|
|
142
|
+
| `MOODLE_DEBUG` | — | `false` | `1`/`true`/`yes`/`on` enables debug output to stderr and `debug` level in the host log channel |
|
|
143
|
+
|
|
144
|
+
<!-- END:env-table -->
|
|
145
|
+
|
|
146
|
+
The token file has `0600` permissions and stores the site address it was issued
|
|
147
|
+
for: if it does not match `MOODLE_URL`, the server asks you to run
|
|
148
|
+
`moodle-mcp-login`. The server reads the file on every request, so there is no
|
|
149
|
+
need to restart the host after logging in again. The token is scrubbed from error
|
|
150
|
+
messages, logs and tool responses (including file URLs).
|
|
151
|
+
|
|
152
|
+
The Chrome profile used for login is kept separate from your main one
|
|
153
|
+
(`~/.config/mcp-moodle/chrome-profile`): site cookies persist, so logging in again
|
|
154
|
+
often works without a password.
|
|
155
|
+
|
|
156
|
+
## Development
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
npm install # also enables the git hooks (.githooks)
|
|
160
|
+
npm run dev # tsx, no compilation
|
|
161
|
+
npm run build # native TypeScript 7 → dist/
|
|
162
|
+
npm run verify # typecheck + lint + tests + docs check
|
|
163
|
+
MOODLE_URL=… npm run smoke # read-only tool chain against a live Moodle
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Build only with `npm run build`: `devDependencies` contain two compiler versions,
|
|
167
|
+
[details](AGENTS.md#typescript). `dist/` is committed; the pre-commit hook builds
|
|
168
|
+
and stages it, bumps the patch version and regenerates the tables above.
|
|
169
|
+
Architecture and rules are in [AGENTS.md](AGENTS.md) (in Russian).
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Функции веб-сервиса Moodle, которые зовут тулы.
|
|
3
|
+
*
|
|
4
|
+
* Единственный список имён в коде: тулы берут имена отсюда, а
|
|
5
|
+
* `moodle_site_info` сверяет его с функциями, которые открывает токен, —
|
|
6
|
+
* так видно, каких прав не хватает, до первого падения тула.
|
|
7
|
+
*/
|
|
8
|
+
export declare const WS: {
|
|
9
|
+
readonly siteInfo: 'core_webservice_get_site_info';
|
|
10
|
+
readonly userCourses: 'core_enrol_get_users_courses';
|
|
11
|
+
readonly moduleByInstance: 'core_course_get_course_module_by_instance';
|
|
12
|
+
readonly courseModule: 'core_course_get_course_module';
|
|
13
|
+
readonly assignments: 'mod_assign_get_assignments';
|
|
14
|
+
readonly listParticipants: 'mod_assign_list_participants';
|
|
15
|
+
readonly participant: 'mod_assign_get_participant';
|
|
16
|
+
readonly submissions: 'mod_assign_get_submissions';
|
|
17
|
+
readonly submissionStatus: 'mod_assign_get_submission_status';
|
|
18
|
+
readonly grades: 'mod_assign_get_grades';
|
|
19
|
+
readonly saveGrade: 'mod_assign_save_grade';
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=functions.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"functions.d.ts","sourceRoot":"","sources":["../../src/api/functions.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,eAAO,MAAM,EAAE;aACb,QAAQ,EAAE,+BAA+B;aACzC,WAAW,EAAE,8BAA8B;aAC3C,gBAAgB,EAAE,2CAA2C;aAC7D,YAAY,EAAE,+BAA+B;aAC7C,WAAW,EAAE,4BAA4B;aACzC,gBAAgB,EAAE,8BAA8B;aAChD,WAAW,EAAE,4BAA4B;aACzC,WAAW,EAAE,4BAA4B;aACzC,gBAAgB,EAAE,kCAAkC;aACpD,MAAM,EAAE,uBAAuB;aAC/B,SAAS,EAAE,uBAAuB;CAC1B,CAAC"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Функции веб-сервиса Moodle, которые зовут тулы.
|
|
3
|
+
*
|
|
4
|
+
* Единственный список имён в коде: тулы берут имена отсюда, а
|
|
5
|
+
* `moodle_site_info` сверяет его с функциями, которые открывает токен, —
|
|
6
|
+
* так видно, каких прав не хватает, до первого падения тула.
|
|
7
|
+
*/
|
|
8
|
+
export const WS = {
|
|
9
|
+
siteInfo: 'core_webservice_get_site_info',
|
|
10
|
+
userCourses: 'core_enrol_get_users_courses',
|
|
11
|
+
moduleByInstance: 'core_course_get_course_module_by_instance',
|
|
12
|
+
courseModule: 'core_course_get_course_module',
|
|
13
|
+
assignments: 'mod_assign_get_assignments',
|
|
14
|
+
listParticipants: 'mod_assign_list_participants',
|
|
15
|
+
participant: 'mod_assign_get_participant',
|
|
16
|
+
submissions: 'mod_assign_get_submissions',
|
|
17
|
+
submissionStatus: 'mod_assign_get_submission_status',
|
|
18
|
+
grades: 'mod_assign_get_grades',
|
|
19
|
+
saveGrade: 'mod_assign_save_grade',
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=functions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"functions.js","sourceRoot":"","sources":["../../src/api/functions.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,EAAE,GAAG;IAChB,QAAQ,EAAE,+BAA+B;IACzC,WAAW,EAAE,8BAA8B;IAC3C,gBAAgB,EAAE,2CAA2C;IAC7D,YAAY,EAAE,+BAA+B;IAC7C,WAAW,EAAE,4BAA4B;IACzC,gBAAgB,EAAE,8BAA8B;IAChD,WAAW,EAAE,4BAA4B;IACzC,WAAW,EAAE,4BAA4B;IACzC,gBAAgB,EAAE,kCAAkC;IACpD,MAAM,EAAE,uBAAuB;IAC/B,SAAS,EAAE,uBAAuB;CAC1B,CAAC"}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Клиент REST API веб-сервисов Moodle.
|
|
3
|
+
*
|
|
4
|
+
* Все функции зовутся одинаково: POST `<site>/webservice/rest/server.php` с
|
|
5
|
+
* `wstoken`, `wsfunction`, `moodlewsrestformat=json` и параметрами в
|
|
6
|
+
* form-кодировании Moodle (`ids[0]=5`, `plugindata[x][text]=…`). Ошибку
|
|
7
|
+
* функции Moodle отдаёт статусом 200 с телом `{exception, errorcode, message}` —
|
|
8
|
+
* поэтому успех определяется по телу, а не по HTTP.
|
|
9
|
+
*
|
|
10
|
+
* Файлы сдач лежат за `<site>/webservice/pluginfile.php/…?token=`. Токен
|
|
11
|
+
* живёт в URL запроса, поэтому всё, что уходит наружу (ошибки, логи, ответы
|
|
12
|
+
* тулов), прогоняется через `scrub`.
|
|
13
|
+
*
|
|
14
|
+
* Ретраи — только для чтения (network/timeout/5xx/429). Вызов с
|
|
15
|
+
* `mutation: true` не повторяется: оценка не должна записаться дважды.
|
|
16
|
+
*/
|
|
17
|
+
export interface MoodleClientConfig {
|
|
18
|
+
/** wwwroot сайта без завершающего слэша. */
|
|
19
|
+
siteUrl: string;
|
|
20
|
+
/** Токен веб-сервиса; зовётся на каждый запрос. */
|
|
21
|
+
getToken: () => Promise<string>;
|
|
22
|
+
timeoutMs?: number;
|
|
23
|
+
/** Повторы на transient-ошибках чтения. Default: 2. Шов для тестов. */
|
|
24
|
+
retries?: number;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Род ошибки:
|
|
28
|
+
* - `network` — сеть, таймаут;
|
|
29
|
+
* - `http` — HTTP не 2xx;
|
|
30
|
+
* - `parse` — тело не JSON;
|
|
31
|
+
* - `auth` — токен не принят (нужен перелогин);
|
|
32
|
+
* - `moodle` — функция вернула исключение (нет прав, неверный параметр…).
|
|
33
|
+
*/
|
|
34
|
+
export type MoodleErrorKind = 'network' | 'http' | 'parse' | 'auth' | 'moodle';
|
|
35
|
+
export declare class MoodleRequestError extends Error {
|
|
36
|
+
readonly kind: MoodleErrorKind;
|
|
37
|
+
readonly wsfunction: string;
|
|
38
|
+
readonly errorcode: string | undefined;
|
|
39
|
+
readonly statusCode: number | undefined;
|
|
40
|
+
constructor(kind: MoodleErrorKind, wsfunction: string, message: string, extra?: {
|
|
41
|
+
errorcode?: string | undefined;
|
|
42
|
+
statusCode?: number | undefined;
|
|
43
|
+
cause?: unknown;
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Вычищает токены из строки: параметры `token`/`wstoken`/`privatetoken` в URL
|
|
48
|
+
* и формах, а
|
|
49
|
+
* также конкретное значение токена, если оно известно, — на случай, если
|
|
50
|
+
* Moodle процитирует его в тексте ошибки.
|
|
51
|
+
*/
|
|
52
|
+
export declare function scrub(text: string, token?: string): string;
|
|
53
|
+
/** Скалярное значение параметра Moodle. Булевы уходят как 1/0 — так их ждёт PHP. */
|
|
54
|
+
export type MoodleScalar = string | number | boolean;
|
|
55
|
+
export type MoodleParams = {
|
|
56
|
+
[key: string]: MoodleParamValue;
|
|
57
|
+
};
|
|
58
|
+
export type MoodleParamValue = MoodleScalar | null | undefined | MoodleParamValue[] | MoodleParams;
|
|
59
|
+
/**
|
|
60
|
+
* Разворачивает вложенные параметры в плоские пары формата Moodle:
|
|
61
|
+
* `{ ids: [5, 6], data: { a: { text: 'x' } } }` →
|
|
62
|
+
* `ids[0]=5`, `ids[1]=6`, `data[a][text]=x`.
|
|
63
|
+
* `undefined`/`null` пропускаются: «не задано» у Moodle — отсутствие ключа.
|
|
64
|
+
*/
|
|
65
|
+
export declare function encodeParams(params: MoodleParams): [string, string][];
|
|
66
|
+
export interface CallOptions {
|
|
67
|
+
signal?: AbortSignal | undefined;
|
|
68
|
+
/** Вызов меняет данные: не ретраить. */
|
|
69
|
+
mutation?: boolean;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Таймаут одной попытки скачивания. Отдельно от MOODLE_TIMEOUT: тот рассчитан
|
|
73
|
+
* на JSON-ответы, а архив сдачи в десятки мегабайт законно качается дольше.
|
|
74
|
+
*/
|
|
75
|
+
export declare const DOWNLOAD_TIMEOUT_MS: number;
|
|
76
|
+
export declare class MoodleClient {
|
|
77
|
+
readonly siteUrl: string;
|
|
78
|
+
private readonly getToken;
|
|
79
|
+
private readonly timeoutMs;
|
|
80
|
+
private readonly retries;
|
|
81
|
+
constructor(config: MoodleClientConfig);
|
|
82
|
+
/** Вызывает функцию веб-сервиса и возвращает разобранный JSON. */
|
|
83
|
+
call<T>(wsfunction: string, params?: MoodleParams, options?: CallOptions): Promise<T>;
|
|
84
|
+
/**
|
|
85
|
+
* Приводит ссылку на файл к форме, по которой его отдаёт веб-сервис:
|
|
86
|
+
* тот же сайт, `/webservice/pluginfile.php/…`, без токена. Ссылка из
|
|
87
|
+
* интерфейса (`/pluginfile.php/…`) переписывается — по ней без cookie
|
|
88
|
+
* сессии файл не отдают.
|
|
89
|
+
*/
|
|
90
|
+
normalizeFileUrl(fileUrl: string): URL;
|
|
91
|
+
/**
|
|
92
|
+
* Открывает поток файла веб-сервиса. Ответ проверен: 2xx и не JSON-ошибка
|
|
93
|
+
* Moodle (её отдают вместо файла, например при чужом токене).
|
|
94
|
+
*/
|
|
95
|
+
openFile(fileUrl: string, options?: CallOptions): Promise<{
|
|
96
|
+
url: URL;
|
|
97
|
+
response: Response;
|
|
98
|
+
}>;
|
|
99
|
+
private loadToken;
|
|
100
|
+
private describe;
|
|
101
|
+
private toError;
|
|
102
|
+
}
|
|
103
|
+
export declare function createMoodleClientFromConfig(): MoodleClient;
|
|
104
|
+
/**
|
|
105
|
+
* Клиент текущего контекста: ALS (per-server, `runWithClient` в server.ts) →
|
|
106
|
+
* ленивый singleton для прямых вызовов `execute()` (смок-скрипт).
|
|
107
|
+
*/
|
|
108
|
+
export declare function getMoodleClient(): MoodleClient;
|
|
109
|
+
export declare function runWithClient<T>(client: MoodleClient, fn: () => Promise<T>): Promise<T>;
|
|
110
|
+
//# sourceMappingURL=moodle-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"moodle-client.d.ts","sourceRoot":"","sources":["../../src/api/moodle-client.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Клиент REST API веб-сервисов Moodle.
|
|
3
|
+
*
|
|
4
|
+
* Все функции зовутся одинаково: POST `<site>/webservice/rest/server.php` с
|
|
5
|
+
* `wstoken`, `wsfunction`, `moodlewsrestformat=json` и параметрами в
|
|
6
|
+
* form-кодировании Moodle (`ids[0]=5`, `plugindata[x][text]=…`). Ошибку
|
|
7
|
+
* функции Moodle отдаёт статусом 200 с телом `{exception, errorcode, message}` —
|
|
8
|
+
* поэтому успех определяется по телу, а не по HTTP.
|
|
9
|
+
*
|
|
10
|
+
* Файлы сдач лежат за `<site>/webservice/pluginfile.php/…?token=`. Токен
|
|
11
|
+
* живёт в URL запроса, поэтому всё, что уходит наружу (ошибки, логи, ответы
|
|
12
|
+
* тулов), прогоняется через `scrub`.
|
|
13
|
+
*
|
|
14
|
+
* Ретраи — только для чтения (network/timeout/5xx/429). Вызов с
|
|
15
|
+
* `mutation: true` не повторяется: оценка не должна записаться дважды.
|
|
16
|
+
*/
|
|
17
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
18
|
+
import { getToken, LOGIN_HINT } from '../auth/token-store.js';
|
|
19
|
+
import { getConfig } from '../config.js';
|
|
20
|
+
import { log } from '../utils/logger.js';
|
|
21
|
+
export class MoodleRequestError extends Error {
|
|
22
|
+
kind;
|
|
23
|
+
wsfunction;
|
|
24
|
+
errorcode;
|
|
25
|
+
statusCode;
|
|
26
|
+
// Поля объявлены явно: tsconfig держит `erasableSyntaxOnly`.
|
|
27
|
+
constructor(kind, wsfunction, message, extra) {
|
|
28
|
+
super(`${wsfunction}: ${message}`, { cause: extra?.cause });
|
|
29
|
+
this.name = 'MoodleRequestError';
|
|
30
|
+
this.kind = kind;
|
|
31
|
+
this.wsfunction = wsfunction;
|
|
32
|
+
this.errorcode = extra?.errorcode;
|
|
33
|
+
this.statusCode = extra?.statusCode;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Коды исключений Moodle, означающие «токен не годится». Остальные коды —
|
|
38
|
+
* обычные ошибки функции: перелогин их не лечит, и советовать его нельзя.
|
|
39
|
+
*/
|
|
40
|
+
const AUTH_ERROR_CODES = new Set(['invalidtoken', 'accessexception', 'expiredtoken']);
|
|
41
|
+
/**
|
|
42
|
+
* Вычищает токены из строки: параметры `token`/`wstoken`/`privatetoken` в URL
|
|
43
|
+
* и формах, а
|
|
44
|
+
* также конкретное значение токена, если оно известно, — на случай, если
|
|
45
|
+
* Moodle процитирует его в тексте ошибки.
|
|
46
|
+
*/
|
|
47
|
+
export function scrub(text, token) {
|
|
48
|
+
let out = text.replace(/((?:^|[^a-z0-9_])(?:ws|private)?token=)[^&\s"'<>\\]+/gi, '$1***');
|
|
49
|
+
if (token && token.length >= 8)
|
|
50
|
+
out = out.split(token).join('***');
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Разворачивает вложенные параметры в плоские пары формата Moodle:
|
|
55
|
+
* `{ ids: [5, 6], data: { a: { text: 'x' } } }` →
|
|
56
|
+
* `ids[0]=5`, `ids[1]=6`, `data[a][text]=x`.
|
|
57
|
+
* `undefined`/`null` пропускаются: «не задано» у Moodle — отсутствие ключа.
|
|
58
|
+
*/
|
|
59
|
+
export function encodeParams(params) {
|
|
60
|
+
const out = [];
|
|
61
|
+
const walk = (prefix, value) => {
|
|
62
|
+
if (value === undefined || value === null)
|
|
63
|
+
return;
|
|
64
|
+
if (Array.isArray(value)) {
|
|
65
|
+
value.forEach((item, i) => walk(`${prefix}[${i}]`, item));
|
|
66
|
+
}
|
|
67
|
+
else if (typeof value === 'object') {
|
|
68
|
+
for (const [key, item] of Object.entries(value))
|
|
69
|
+
walk(`${prefix}[${key}]`, item);
|
|
70
|
+
}
|
|
71
|
+
else if (typeof value === 'boolean') {
|
|
72
|
+
out.push([prefix, value ? '1' : '0']);
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
out.push([prefix, String(value)]);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
for (const [key, value] of Object.entries(params))
|
|
79
|
+
walk(key, value);
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
function isMoodleException(body) {
|
|
83
|
+
return (typeof body === 'object' &&
|
|
84
|
+
body !== null &&
|
|
85
|
+
typeof body.exception === 'string');
|
|
86
|
+
}
|
|
87
|
+
const RETRIABLE_HTTP_CODES = new Set([429, 500, 502, 503, 504]);
|
|
88
|
+
const BACKOFF_BASE_MS = 300;
|
|
89
|
+
/**
|
|
90
|
+
* Таймаут одной попытки скачивания. Отдельно от MOODLE_TIMEOUT: тот рассчитан
|
|
91
|
+
* на JSON-ответы, а архив сдачи в десятки мегабайт законно качается дольше.
|
|
92
|
+
*/
|
|
93
|
+
export const DOWNLOAD_TIMEOUT_MS = 5 * 60_000;
|
|
94
|
+
function isRetriable(err) {
|
|
95
|
+
if (!(err instanceof Error))
|
|
96
|
+
return false;
|
|
97
|
+
if (err.name === 'AbortError')
|
|
98
|
+
return false;
|
|
99
|
+
if (err.name === 'TimeoutError')
|
|
100
|
+
return true;
|
|
101
|
+
return /fetch failed|ETIMEDOUT|ECONNRESET|ENOTFOUND|EAI_AGAIN/i.test(err.message);
|
|
102
|
+
}
|
|
103
|
+
function combineSignals(...signals) {
|
|
104
|
+
const defined = signals.filter((s) => s !== undefined);
|
|
105
|
+
return defined.length === 1 ? defined[0] : AbortSignal.any(defined);
|
|
106
|
+
}
|
|
107
|
+
function sleep(ms, signal) {
|
|
108
|
+
if (signal?.aborted)
|
|
109
|
+
return Promise.reject(signal.reason);
|
|
110
|
+
return new Promise((resolve, reject) => {
|
|
111
|
+
const timer = setTimeout(() => {
|
|
112
|
+
signal?.removeEventListener('abort', onAbort);
|
|
113
|
+
resolve();
|
|
114
|
+
}, ms);
|
|
115
|
+
const onAbort = () => {
|
|
116
|
+
clearTimeout(timer);
|
|
117
|
+
reject(signal.reason);
|
|
118
|
+
};
|
|
119
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
export class MoodleClient {
|
|
123
|
+
siteUrl;
|
|
124
|
+
getToken;
|
|
125
|
+
timeoutMs;
|
|
126
|
+
retries;
|
|
127
|
+
constructor(config) {
|
|
128
|
+
this.siteUrl = config.siteUrl.replace(/\/+$/, '');
|
|
129
|
+
this.getToken = config.getToken;
|
|
130
|
+
this.timeoutMs = config.timeoutMs ?? 30_000;
|
|
131
|
+
this.retries = config.retries ?? 2;
|
|
132
|
+
}
|
|
133
|
+
/** Вызывает функцию веб-сервиса и возвращает разобранный JSON. */
|
|
134
|
+
async call(wsfunction, params = {}, options) {
|
|
135
|
+
const token = await this.loadToken(wsfunction);
|
|
136
|
+
const body = new URLSearchParams([
|
|
137
|
+
['wstoken', token],
|
|
138
|
+
['wsfunction', wsfunction],
|
|
139
|
+
['moodlewsrestformat', 'json'],
|
|
140
|
+
...encodeParams(params),
|
|
141
|
+
]);
|
|
142
|
+
const url = `${this.siteUrl}/webservice/rest/server.php`;
|
|
143
|
+
log('info', `call ${wsfunction}`);
|
|
144
|
+
const maxAttempts = options?.mutation ? 1 : this.retries + 1;
|
|
145
|
+
let response;
|
|
146
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
147
|
+
const last = attempt === maxAttempts - 1;
|
|
148
|
+
try {
|
|
149
|
+
response = await fetch(url, {
|
|
150
|
+
method: 'POST',
|
|
151
|
+
headers: { Accept: 'application/json' },
|
|
152
|
+
body,
|
|
153
|
+
signal: combineSignals(AbortSignal.timeout(this.timeoutMs), options?.signal),
|
|
154
|
+
});
|
|
155
|
+
if (response.ok || !RETRIABLE_HTTP_CODES.has(response.status) || last)
|
|
156
|
+
break;
|
|
157
|
+
void response.body?.cancel().catch(() => { });
|
|
158
|
+
}
|
|
159
|
+
catch (err) {
|
|
160
|
+
if (err instanceof Error && err.name === 'AbortError')
|
|
161
|
+
throw err;
|
|
162
|
+
if (!isRetriable(err) || last) {
|
|
163
|
+
throw new MoodleRequestError('network', wsfunction, this.describe(err, token), {
|
|
164
|
+
cause: err,
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
log('warning', `Retry ${attempt + 1}/${maxAttempts - 1} for ${wsfunction}`);
|
|
169
|
+
await sleep(BACKOFF_BASE_MS * 2 ** attempt, options?.signal);
|
|
170
|
+
}
|
|
171
|
+
if (!response) {
|
|
172
|
+
throw new MoodleRequestError('network', wsfunction, 'request returned no response');
|
|
173
|
+
}
|
|
174
|
+
const text = await response.text().catch(() => '');
|
|
175
|
+
if (!response.ok) {
|
|
176
|
+
throw new MoodleRequestError('http', wsfunction, `HTTP ${response.status}: ${scrub(text.slice(0, 500), token)}`, { statusCode: response.status });
|
|
177
|
+
}
|
|
178
|
+
let json;
|
|
179
|
+
try {
|
|
180
|
+
json = JSON.parse(text);
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
throw new MoodleRequestError('parse', wsfunction, `response is not JSON: ${scrub(text.slice(0, 200), token)}`, { statusCode: response.status });
|
|
184
|
+
}
|
|
185
|
+
if (isMoodleException(json))
|
|
186
|
+
throw this.toError(wsfunction, json, token);
|
|
187
|
+
return json;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Приводит ссылку на файл к форме, по которой его отдаёт веб-сервис:
|
|
191
|
+
* тот же сайт, `/webservice/pluginfile.php/…`, без токена. Ссылка из
|
|
192
|
+
* интерфейса (`/pluginfile.php/…`) переписывается — по ней без cookie
|
|
193
|
+
* сессии файл не отдают.
|
|
194
|
+
*/
|
|
195
|
+
normalizeFileUrl(fileUrl) {
|
|
196
|
+
let url;
|
|
197
|
+
try {
|
|
198
|
+
url = new URL(fileUrl);
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
throw new Error('fileUrl is not an absolute URL.');
|
|
202
|
+
}
|
|
203
|
+
const site = new URL(this.siteUrl);
|
|
204
|
+
if (url.origin !== site.origin) {
|
|
205
|
+
throw new Error(`fileUrl does not point to ${site.origin}; only files from this site can be downloaded.`);
|
|
206
|
+
}
|
|
207
|
+
const sitePath = site.pathname.replace(/\/+$/, '');
|
|
208
|
+
const rel = url.pathname.slice(sitePath.length);
|
|
209
|
+
if (!url.pathname.startsWith(sitePath)) {
|
|
210
|
+
throw new Error('fileUrl is outside the Moodle site path.');
|
|
211
|
+
}
|
|
212
|
+
if (rel.startsWith('/pluginfile.php/')) {
|
|
213
|
+
url.pathname = `${sitePath}/webservice${rel}`;
|
|
214
|
+
}
|
|
215
|
+
else if (!rel.startsWith('/webservice/pluginfile.php/')) {
|
|
216
|
+
throw new Error('fileUrl is not a Moodle file URL (expected …/pluginfile.php/…).');
|
|
217
|
+
}
|
|
218
|
+
url.searchParams.delete('token');
|
|
219
|
+
url.searchParams.delete('wstoken');
|
|
220
|
+
return url;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Открывает поток файла веб-сервиса. Ответ проверен: 2xx и не JSON-ошибка
|
|
224
|
+
* Moodle (её отдают вместо файла, например при чужом токене).
|
|
225
|
+
*/
|
|
226
|
+
async openFile(fileUrl, options) {
|
|
227
|
+
const what = 'pluginfile';
|
|
228
|
+
const url = this.normalizeFileUrl(fileUrl);
|
|
229
|
+
const token = await this.loadToken(what);
|
|
230
|
+
const withToken = new URL(url);
|
|
231
|
+
withToken.searchParams.set('token', token);
|
|
232
|
+
log('info', `download ${url.pathname}`);
|
|
233
|
+
let response;
|
|
234
|
+
try {
|
|
235
|
+
response = await fetch(withToken, {
|
|
236
|
+
signal: combineSignals(AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS), options?.signal),
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
catch (err) {
|
|
240
|
+
if (err instanceof Error && err.name === 'AbortError')
|
|
241
|
+
throw err;
|
|
242
|
+
throw new MoodleRequestError('network', what, this.describe(err, token), { cause: err });
|
|
243
|
+
}
|
|
244
|
+
const contentType = response.headers.get('content-type') ?? '';
|
|
245
|
+
if (!response.ok || contentType.includes('application/json')) {
|
|
246
|
+
const text = await response.text().catch(() => '');
|
|
247
|
+
let json;
|
|
248
|
+
try {
|
|
249
|
+
json = JSON.parse(text);
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
json = undefined;
|
|
253
|
+
}
|
|
254
|
+
if (isMoodleException(json))
|
|
255
|
+
throw this.toError(what, json, token);
|
|
256
|
+
if (response.ok)
|
|
257
|
+
return { url, response: new Response(text, response) };
|
|
258
|
+
throw new MoodleRequestError('http', what, `HTTP ${response.status}: ${scrub(text.slice(0, 300), token)}`, { statusCode: response.status });
|
|
259
|
+
}
|
|
260
|
+
return { url, response };
|
|
261
|
+
}
|
|
262
|
+
async loadToken(wsfunction) {
|
|
263
|
+
try {
|
|
264
|
+
return await this.getToken();
|
|
265
|
+
}
|
|
266
|
+
catch (err) {
|
|
267
|
+
throw new MoodleRequestError('auth', wsfunction, err instanceof Error ? err.message : String(err), { cause: err });
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
describe(err, token) {
|
|
271
|
+
return scrub(err instanceof Error ? err.message : String(err), token);
|
|
272
|
+
}
|
|
273
|
+
toError(wsfunction, body, token) {
|
|
274
|
+
const errorcode = body.errorcode;
|
|
275
|
+
const message = scrub(body.message ?? body.exception, token);
|
|
276
|
+
if (errorcode && AUTH_ERROR_CODES.has(errorcode)) {
|
|
277
|
+
return new MoodleRequestError('auth', wsfunction, `${message} ${LOGIN_HINT}`, { errorcode });
|
|
278
|
+
}
|
|
279
|
+
return new MoodleRequestError('moodle', wsfunction, `${message} [${errorcode ?? body.exception}]`, {
|
|
280
|
+
errorcode,
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
let clientInstance = null;
|
|
285
|
+
const clientStorage = new AsyncLocalStorage();
|
|
286
|
+
export function createMoodleClientFromConfig() {
|
|
287
|
+
const cfg = getConfig();
|
|
288
|
+
return new MoodleClient({
|
|
289
|
+
siteUrl: cfg.MOODLE_URL,
|
|
290
|
+
getToken,
|
|
291
|
+
timeoutMs: cfg.MOODLE_TIMEOUT,
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Клиент текущего контекста: ALS (per-server, `runWithClient` в server.ts) →
|
|
296
|
+
* ленивый singleton для прямых вызовов `execute()` (смок-скрипт).
|
|
297
|
+
*/
|
|
298
|
+
export function getMoodleClient() {
|
|
299
|
+
const fromAls = clientStorage.getStore();
|
|
300
|
+
if (fromAls)
|
|
301
|
+
return fromAls;
|
|
302
|
+
clientInstance ??= createMoodleClientFromConfig();
|
|
303
|
+
return clientInstance;
|
|
304
|
+
}
|
|
305
|
+
export function runWithClient(client, fn) {
|
|
306
|
+
return clientStorage.run(client, fn);
|
|
307
|
+
}
|
|
308
|
+
//# sourceMappingURL=moodle-client.js.map
|