@missing-elements/h5p-mcp 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 missing-elements
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,69 @@
1
- # Temporary Holding Version
1
+ # H5P Author MCP by Missing Elements
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@missing-elements/h5p-mcp` lets an AI app make H5P content on your computer: quizzes, fill in the
4
+ blanks, flash cards, presentations, interactive books, branching scenarios and the rest of the 53
5
+ content types the H5P hub serves. It writes a playable `.h5p` that carries its libraries, checks
6
+ that it plays in a real H5P player, and opens it in your browser. It reads a `.h5p` you have back
7
+ into its source too, to change it and build it again. No H5P site, server or account.
8
+
9
+ It is a local [MCP](https://modelcontextprotocol.io) server: your app starts it on your computer,
10
+ and it sends nothing to a server of ours. It needs Node 22 or newer, and for the check Chrome or
11
+ Edge; without either, run `npx playwright install chromium` once.
12
+
13
+ ## Add it to your app
14
+
15
+ **Claude Desktop**: Settings, Developer, Edit Config, then in `claude_desktop_config.json`:
16
+
17
+ ```json
18
+ {
19
+ "mcpServers": {
20
+ "h5p": { "command": "npx", "args": ["-y", "@missing-elements/h5p-mcp"] }
21
+ }
22
+ }
23
+ ```
24
+
25
+ **Claude Code**: `claude mcp add h5p -- npx -y @missing-elements/h5p-mcp`
26
+
27
+ **VS Code**: in `.vscode/mcp.json`:
28
+
29
+ ```json
30
+ { "servers": { "h5p": { "command": "npx", "args": ["-y", "@missing-elements/h5p-mcp"] } } }
31
+ ```
32
+
33
+ Then ask, for example: "Make a five-question quiz about the water cycle as an H5P file."
34
+
35
+ ## The folders it uses
36
+
37
+ It reads the files your content names, and writes packages, only in its folders: those you give
38
+ with `--allow`, as in `"args": ["-y", "@missing-elements/h5p-mcp", "--allow", "/Users/me/Lessons"]`
39
+ (repeat it for more); else the folders your app gives it; else your Desktop, Documents and
40
+ Downloads, and then never your home folder whole. It never writes over a file: a name that is taken
41
+ gets a number, and it says which.
42
+
43
+ ## Tools
44
+
45
+ - `h5p_types`: the content types, and how to write a source for one.
46
+ - `h5p_build`: a package from a source, its source beside it as `.source.json`. A source with
47
+ problems is refused, each problem named. It checks the package and says what it holds.
48
+ - `h5p_preview`: opens a package in your browser, in the real player, served from your computer
49
+ until its tab is closed.
50
+ - `h5p_read`: a package back into its source, with its pictures and other files, in a new folder
51
+ beside it, to change and build again. It reads content made for the library pack's versions of
52
+ its libraries, and says what a source cannot hold, such as the author's comments.
53
+
54
+ ## What leaves your computer
55
+
56
+ The build downloads each picture, video, recording or other file your content names by web
57
+ address, and refuses to download from an address on your local network: a guard against a mistaken
58
+ or planted address, not against a hostile network. A video on YouTube, Vimeo, Panopto or Echo360 is
59
+ not downloaded: it stays an address, which the player loads wherever it points, as H5P does
60
+ anywhere. Math is drawn by the package's own copy of MathJax, which loads nothing from elsewhere.
61
+ The check and the preview play the package from your computer. Your app
62
+ sends your conversation to its model, as it does without this server.
63
+
64
+ ## Licence
65
+
66
+ MIT. The H5P libraries a package carries are under their own licences, listed in it.
67
+
68
+ H5P is a trademark of H5P Group. This server is made by Missing Elements and is not affiliated with
69
+ or endorsed by H5P Group.
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from 'node:fs/promises'
3
+ import { parseArgs } from 'node:util'
4
+ import { StdioServerTransport } from '@modelcontextprotocol/server/stdio'
5
+
6
+ // Standard output is the protocol's: anything a library prints there would break a message.
7
+ console.log = console.error
8
+ console.info = console.error
9
+
10
+ const HELP = `Usage: h5p-mcp [--allow <folder>]... [--no-open]
11
+
12
+ H5P Author MCP by Missing Elements: an MCP server over standard input and output that builds
13
+ .h5p packages, checks that they play, and opens them in the browser. An app such as Claude
14
+ Desktop starts it; it does nothing on its own.
15
+
16
+ Options:
17
+ --allow <folder> a folder builds may read files from and write packages to; repeat it for
18
+ more. Without it: the folders the app gives, else Desktop, Documents and
19
+ Downloads
20
+ --no-open answer a preview with its address instead of opening the browser
21
+ --version
22
+ -h, --help
23
+ `
24
+
25
+ let values
26
+ try {
27
+ ;({ values } = parseArgs({
28
+ options: {
29
+ allow: { type: 'string', multiple: true },
30
+ 'no-open': { type: 'boolean' },
31
+ version: { type: 'boolean' },
32
+ help: { type: 'boolean', short: 'h' }
33
+ }
34
+ }))
35
+ } catch (error) {
36
+ console.error(`h5p-mcp: ${error instanceof Error ? error.message : error}\n\n${HELP}`)
37
+ process.exit(2)
38
+ }
39
+ if (values.help) {
40
+ process.stdout.write(HELP)
41
+ process.exit(0)
42
+ }
43
+ if (values.version) {
44
+ const { version } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'))
45
+ process.stdout.write(`@missing-elements/h5p-mcp ${version}\n`)
46
+ process.exit(0)
47
+ }
48
+
49
+ // Loaded only now, so that --help and --version answer without loading the build and the pack.
50
+ const { createServer } = await import('../lib/server.mjs')
51
+ const { server, close } = await createServer({ allow: values.allow, open: !values['no-open'] })
52
+ // The app ends the server by closing its input; a preview still open would keep it alive.
53
+ const stop = () => {
54
+ close()
55
+ process.exit(0)
56
+ }
57
+ process.stdin.on('end', stop)
58
+ process.stdin.on('close', stop)
59
+ await server.connect(new StdioServerTransport())
@@ -0,0 +1,58 @@
1
+ import { realpath, stat } from 'node:fs/promises'
2
+ import { homedir } from 'node:os'
3
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+
6
+ /**
7
+ * Where a build may read and write when neither the person nor the app named a folder: Desktop,
8
+ * Documents and Downloads, those that exist. Never the home folder whole, which holds keys and
9
+ * settings no build has a reason to read: one that is a link to the home folder, or to a folder
10
+ * that holds it, is left out. A link to a folder elsewhere, as on another drive, is kept.
11
+ * @param {string} [home]
12
+ * @returns {Promise<string[]>}
13
+ */
14
+ export async function defaultFolders(home = homedir()) {
15
+ const own = await realpath(home).catch(() => resolve(home))
16
+ /** @type {string[]} */
17
+ const found = []
18
+ for (const name of ['Desktop', 'Documents', 'Downloads']) {
19
+ const path = join(home, name)
20
+ if (!(await stat(path).catch(() => null))?.isDirectory()) continue
21
+ const up = relative(await realpath(path), own)
22
+ if (up === '' || (!isAbsolute(up) && up !== '..' && !up.startsWith(`..${sep}`))) continue
23
+ found.push(path)
24
+ }
25
+ return found
26
+ }
27
+
28
+ /**
29
+ * The folders among an app's roots: those it names by a `file:` address. A root of another scheme
30
+ * is no folder on this computer.
31
+ * @param {{ uri: string }[]} roots
32
+ * @returns {string[]}
33
+ */
34
+ export function rootFolders(roots) {
35
+ return roots.filter((root) => root.uri.startsWith('file:')).map((root) => fileURLToPath(root.uri))
36
+ }
37
+
38
+ /** The names Windows keeps for its devices, an extension or not: no file can take one there. */
39
+ const DEVICE = /^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])$/
40
+
41
+ /**
42
+ * A file name for a package from its title: its letters and digits, in any script and as written,
43
+ * joined by `-`, at most 60 characters; `h5p-content` for a title with none of them, and `-file`
44
+ * after a name Windows keeps for a device, as `con`.
45
+ * @param {unknown} title
46
+ * @returns {string}
47
+ */
48
+ export function fileStem(title) {
49
+ const words = String(title ?? '')
50
+ .normalize('NFC')
51
+ .toLowerCase()
52
+ .replace(/[^\p{L}\p{M}\p{N}]+/gu, '-')
53
+ .replace(/^-+|-+$/g, '')
54
+ // Cut by characters, not by halves of one: a letter outside the basic range is two.
55
+ const stem = Array.from(words).slice(0, 60).join('').replace(/-+$/, '')
56
+ if (!stem) return 'h5p-content'
57
+ return DEVICE.test(stem) ? `${stem}-file` : stem
58
+ }
package/lib/server.mjs ADDED
@@ -0,0 +1,314 @@
1
+ import { lstat, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import { basename, dirname, join, resolve } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { McpServer } from '@modelcontextprotocol/server'
6
+ import { z } from 'zod'
7
+ import { SourceError, buildPackage, contentTypes, inside, openPack, publicFetch, readPackage, schemaOf, sourceSchema, sourceType } from '@missing-elements/h5p-author'
8
+ import { VerifyError, openBrowser, previewPackage, summarize, verifyPackage } from '@missing-elements/h5p-verify'
9
+ import { defaultFolders, fileStem, rootFolders } from './folders.mjs'
10
+
11
+ /**
12
+ * @typedef {object} ServerOptions
13
+ * @property {string[]} [allow] the folders a build may read and write, given when the server starts;
14
+ * they take precedence over the app's roots, which take precedence over Desktop, Documents and
15
+ * Downloads
16
+ * @property {boolean} [open] open a preview in the person's browser; default true
17
+ * @property {string} [libraries] the pack's `parts/` folder to build from; the installed pack by default
18
+ */
19
+
20
+ /** The skill's flow, which every app shows the model with the tools. */
21
+ const INSTRUCTIONS = `Builds H5P content as a .h5p file from a short JSON source, checks that it plays, and opens it in the person's browser.
22
+ 1. The content type is chosen with the person: where their request names none, ask which, and ask nothing else. h5p_types with no type lists them.
23
+ 2. Call h5p_types with the type and write the source from its notes, example and fields: only what differs from the defaults.
24
+ 3. Call h5p_build. Where it lists problems, fix each at its path and build again.
25
+ 4. Tell the person where the file is and what the check found, and offer h5p_preview.
26
+ The author and the licence are what the person gave; otherwise the name you know them by, or "Unknown", and the licence "U". Say which you used.
27
+ To change a .h5p the person has, h5p_read it, change its source as asked, and h5p_build that.`
28
+
29
+ const READ = `Reads a .h5p package back into its source, to change it and build it again with h5p_build: its type, title, language, licence, authors, and the params that differ from the defaults. Writes the source and the package's media into a new folder beside it, and answers with the source, each file named where it was written. Reads content made for the library pack's versions of its libraries.`
30
+
31
+ const TYPES = `The H5P content types and how to write a source for one. With no type: the list, and how to write good content. With a type: its notes, a tested example and its fields. Read the type's answer before writing its source.`
32
+
33
+ const BUILD = `Builds a .h5p package from a source, its params holding only what differs from the type's defaults. A file is { "path": ... }, in a folder this server may use or at a web address. Writes the package and its source (.source.json) to output, or under a new name in the first folder it may use. A source with problems is refused, each problem named by its path. With verify (the default), plays the package in a headless browser and reports whether it works.`
34
+
35
+ const PREVIEW = `Opens a .h5p package in the person's browser in the real player, served from this computer until its tab is closed. Answers with the address.`
36
+
37
+ const LIST_HEAD = `The content types the library pack has, by the name a source's "type" takes. Those marked * have notes and a tested example; for the rest h5p_types gives their fields.`
38
+
39
+ /**
40
+ * A source's own fields as the author package declares them (#230), shown to the app as the
41
+ * properties of `source`, and nothing more: no field is said to be required and none forbidden.
42
+ * The build is the check, which reads a source written another way as it is meant (#174) and says
43
+ * every problem at once, where the SDK, or an app holding a call to the schema, would refuse it
44
+ * before the build looked.
45
+ */
46
+ const SOURCE_PROPERTIES = z.toJSONSchema(sourceSchema, { io: 'input' }).properties
47
+
48
+ /** @param {string} text */
49
+ const answer = (text) => ({ content: [{ type: /** @type {const} */ ('text'), text }] })
50
+ /** @param {string} text */
51
+ const refusal = (text) => ({ content: [{ type: /** @type {const} */ ('text'), text }], isError: true })
52
+
53
+ /** @param {number} bytes */
54
+ const sized = (bytes) => (bytes < 1e6 ? `${Math.max(1, Math.round(bytes / 1e3))} kB` : `${(bytes / 1e6).toFixed(1)} MB`)
55
+
56
+ /**
57
+ * Where the person's files are, for the model: it cannot know, and a path it guesses is refused.
58
+ * @param {string[]} folders
59
+ */
60
+ const whereFiles = (folders) => folders.length
61
+ ? `This server reads files and writes packages only in ${folders.join(', ')}. A file's path written alone, as { "path": "picture.png" }, is read from ${folders[0]}.`
62
+ : 'This server has no folder to read or write in: start it with --allow <folder>.'
63
+
64
+ /** Lines of an outline past which an answer says how many more there are. */
65
+ const OUTLINE_LINES = 80
66
+
67
+ /** @param {string} path a package's */
68
+ const sourceBeside = (path) => path.replace(/\.h5p$/i, '.source.json')
69
+
70
+ /**
71
+ * A read source's files named in the folder it was read into, so that a build looks for each there
72
+ * and nowhere else: one the read wrote, where it is, and one the package lacks, where the person can
73
+ * put it. Every file a read source names, but by a web address, is under its folder by its path
74
+ * (`readPackage`); a path is a field of a file alone in every content type.
75
+ * @param {unknown} value
76
+ * @param {string} folder
77
+ * @returns {unknown}
78
+ */
79
+ function located(value, folder) {
80
+ if (Array.isArray(value)) return value.map((each) => located(each, folder))
81
+ if (!value || typeof value !== 'object') return value
82
+ const local = (/** @type {unknown} */ each) => typeof each === 'string' && !/^[a-z][a-z0-9+.-]*:/i.test(each)
83
+ const entries = Object.entries(value).map(([key, each]) => [key, key === 'path' && local(each) ? join(folder, ...String(each).split('/')) : located(each, folder)])
84
+ return Object.fromEntries(entries)
85
+ }
86
+
87
+ /**
88
+ * The server and its four tools. It holds no rules of its own: the build, the read, their checks
89
+ * and the confinement to folders are h5p-author's, the check and the preview h5p-verify's.
90
+ * @param {ServerOptions} [options]
91
+ */
92
+ export async function createServer(options = {}) {
93
+ const { version } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'))
94
+ const server = new McpServer({ name: 'h5p-mcp', title: 'H5P Author MCP by Missing Elements', version }, { instructions: INSTRUCTIONS })
95
+ const author = dirname(fileURLToPath(import.meta.resolve('@missing-elements/h5p-author/package.json')))
96
+ const typeFiles = join(author, 'references', 'types')
97
+ /** @type {Set<{ close: () => void }>} */
98
+ const previews = new Set()
99
+
100
+ /** The folders a build may read and write, asked of the app on each call, since its roots can change. */
101
+ async function folders() {
102
+ if (options.allow?.length) return options.allow.map((folder) => resolve(folder))
103
+ if (server.server.getClientCapabilities()?.roots) {
104
+ try {
105
+ const found = rootFolders((await server.server.listRoots(undefined, { timeout: 5_000 })).roots)
106
+ if (found.length) return found
107
+ } catch {
108
+ // An app that says it has roots and does not answer gets the default folders.
109
+ }
110
+ }
111
+ return defaultFolders()
112
+ }
113
+
114
+ /** @type {Promise<{ name: string, title: string }[]> | undefined} */
115
+ let typeList
116
+ /** The pack's content types, read once: each needs its part opened. */
117
+ function types() {
118
+ typeList ??= (async () => {
119
+ const pack = await openPack(options.libraries)
120
+ try {
121
+ return (await contentTypes(pack)).map((part) => ({ name: part.library.machineName, title: part.library.title }))
122
+ } finally {
123
+ await pack.close()
124
+ }
125
+ })()
126
+ return typeList
127
+ }
128
+
129
+ /** The content types the skill has a file for, as the author package carries them. */
130
+ async function filed() {
131
+ const names = await readdir(typeFiles).catch(() => [])
132
+ return new Set(names.filter((name) => name.endsWith('.md')).map((name) => name.slice(0, -3)))
133
+ }
134
+
135
+ /** The packages being built, lower-cased, as macOS and Windows match a name in any case. */
136
+ const building = new Set()
137
+
138
+ /**
139
+ * A package's path in the folder, with a number added to the name where it is taken, the
140
+ * package's or its source's: a build never writes over a file, so a package built again takes
141
+ * the next number. A link takes its name too, even one that leads nowhere. The path is held for
142
+ * the build until it is let go of, so that builds at once take names of their own.
143
+ * @param {string} folder
144
+ * @param {string} stem the file name without `.h5p`
145
+ */
146
+ async function freeName(folder, stem) {
147
+ for (let n = 1; ; n++) {
148
+ const path = join(folder, `${stem}${n === 1 ? '' : `-${n}`}.h5p`)
149
+ const taken = await Promise.all([path, sourceBeside(path)].map((each) => lstat(each).then(() => true, () => false)))
150
+ // Asked after the wait and held at once, with no wait between, so no other build takes it.
151
+ if (taken.includes(true) || building.has(path.toLowerCase())) continue
152
+ building.add(path.toLowerCase())
153
+ return path
154
+ }
155
+ }
156
+
157
+ /**
158
+ * A new folder beside a package for what a read writes, named after it, with a number added where
159
+ * the name is taken, as a build's package takes one; held while the read runs.
160
+ * @param {string} parent
161
+ * @param {string} stem
162
+ */
163
+ async function freeFolder(parent, stem) {
164
+ for (let n = 1; ; n++) {
165
+ const path = join(parent, n === 1 ? stem : `${stem}-${n}`)
166
+ const taken = await lstat(path).then(() => true, () => false)
167
+ if (taken || building.has(path.toLowerCase())) continue
168
+ building.add(path.toLowerCase())
169
+ return path
170
+ }
171
+ }
172
+
173
+ server.registerTool('h5p_types', {
174
+ title: 'H5P content types',
175
+ description: TYPES,
176
+ inputSchema: z.object({ type: z.string().optional().describe('A content type, as H5P.MultiChoice or "multiple choice"') }),
177
+ annotations: { readOnlyHint: true, openWorldHint: false }
178
+ }, async ({ type }) => {
179
+ const list = await types()
180
+ const files = await filed()
181
+ // Said with every answer, before a source is written: a model cannot know the folders, and a
182
+ // path it guesses is refused.
183
+ const where = whereFiles(await folders())
184
+ if (!type) {
185
+ const lines = list.map(({ name, title }) => `${files.has(name) ? '*' : '-'} ${name}: ${title}`)
186
+ const brief = await readFile(join(author, 'references', 'authoring.md'), 'utf8').catch(() => '')
187
+ return answer([LIST_HEAD, ...lines, '', where, ...(brief ? ['', brief] : [])].join('\n'))
188
+ }
189
+ const name = sourceType({ type }, list.map((each) => each.name))
190
+ if (!name) return refusal(`The library pack has no content type "${type}". h5p_types with no type lists them.`)
191
+ const text = files.has(name) ? await readFile(join(typeFiles, `${name}.md`), 'utf8') : await schemaOf(name, { markdown: true, libraries: options.libraries })
192
+ return answer(`${text.trimEnd()}\n\n${where}`)
193
+ })
194
+
195
+ server.registerTool('h5p_build', {
196
+ title: 'Build an H5P package',
197
+ description: BUILD,
198
+ inputSchema: z.object({
199
+ source: z.record(z.string(), z.unknown()).meta({ properties: SOURCE_PROPERTIES, description: 'The source, as h5p_types describes it for its type' }),
200
+ output: z.string().optional().describe('Leave it out unless the person named a place: a file name, or a path in a folder this server may use'),
201
+ verify: z.boolean().optional().describe('Play it and report whether it works; default true')
202
+ }),
203
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
204
+ }, async ({ source, output, verify = true }) => {
205
+ const allowed = await folders()
206
+ if (!allowed.length) return refusal('This server has no folder to write in: start it with --allow <folder>, or give it a folder from the app.')
207
+ let target = resolve(allowed[0], output || `${fileStem(source.title)}.h5p`)
208
+ if (!/\.h5p$/i.test(target)) target += '.h5p'
209
+ // Said here, with the folders, since a model cannot know them: the build's own refusal names none.
210
+ if (!(await inside(target, allowed))) return refusal(`${target} is outside the folders this server may write in: ${allowed.join(', ')}. Give a file name alone, or leave output out.`)
211
+ // A name that is taken gets a number, as a build never writes over a file.
212
+ target = await freeName(dirname(target), basename(target).replace(/\.h5p$/i, ''))
213
+ const sourceFile = sourceBeside(target)
214
+ let result
215
+ /** @type {Error | undefined} */
216
+ let unwritten
217
+ try {
218
+ result = await buildPackage(source, target, { base: dirname(target), within: allowed, fetch: publicFetch, libraries: options.libraries })
219
+ // Made new: a file or a link put at its name since the name was found free is not written through.
220
+ unwritten = await writeFile(sourceFile, `${JSON.stringify(source, null, 2)}\n`, { flag: 'wx' }).then(() => undefined, (error) => error)
221
+ } catch (error) {
222
+ if (error instanceof SourceError) return refusal(`${error.message}\nFix each at its path and build again.${/outside the folders/.test(error.message) ? ` ${whereFiles(allowed)}` : ''}`)
223
+ return refusal(error instanceof Error ? error.message : String(error))
224
+ } finally {
225
+ building.delete(target.toLowerCase())
226
+ }
227
+ const install = result.install.length ? `, ${result.install.length} more for installing on an H5P site` : ''
228
+ const media = result.media.length ? `, ${result.media.length} media file${result.media.length === 1 ? '' : 's'}` : ''
229
+ const lines = [
230
+ `Built ${target} (${sized((await stat(target)).size)}): ${result.manifest.mainLibrary}, ${result.libraries.length} libraries${install}${media}.`,
231
+ unwritten
232
+ ? `Its source was not written beside it: ${unwritten.message}`
233
+ : `Its source is beside it, ${basename(sourceFile)}: https://missing-elements.github.io/h5p/build/ opens it under "Or open a file", to change and build again.`
234
+ ]
235
+ for (const { path, message } of result.notes) lines.push(`Note: ${path} ${message}`)
236
+ const outline = result.outline.split('\n')
237
+ lines.push('', 'What it holds:', ...outline.slice(0, OUTLINE_LINES))
238
+ if (outline.length > OUTLINE_LINES) lines.push(`… and ${outline.length - OUTLINE_LINES} more lines.`)
239
+ /** @type {{ type: 'image', data: string, mimeType: string }[]} */
240
+ const images = []
241
+ if (verify) {
242
+ const out = await mkdtemp(join(tmpdir(), 'h5p-mcp-'))
243
+ try {
244
+ const report = await verifyPackage({ file: target, out, libraries: options.libraries })
245
+ // Its screenshot goes with the answer as an image; the path it was written to is gone.
246
+ lines.push('', summarize(report).split('\n').filter((line) => !/^\s*screenshot:/.test(line)).join('\n'))
247
+ const shot = await readFile(join(out, 'screenshot.png')).catch(() => null)
248
+ if (shot) images.push({ type: 'image', data: shot.toString('base64'), mimeType: 'image/png' })
249
+ } catch (error) {
250
+ lines.push('', `Not verified: ${error instanceof VerifyError || error instanceof Error ? error.message : String(error)}`)
251
+ } finally {
252
+ await rm(out, { recursive: true, force: true })
253
+ }
254
+ }
255
+ return { content: [{ type: /** @type {const} */ ('text'), text: lines.join('\n') }, ...images] }
256
+ })
257
+
258
+ server.registerTool('h5p_read', {
259
+ title: 'Read an H5P package',
260
+ description: READ,
261
+ inputSchema: z.object({ package: z.string().describe('The .h5p by its file name alone, as the person names it, or its path in a folder this server may use') }),
262
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }
263
+ }, async ({ package: file }) => {
264
+ const allowed = await folders()
265
+ // A name alone is the first folder's, as a source's file is.
266
+ const path = resolve(allowed[0] ?? '.', file)
267
+ if (!allowed.length || !(await inside(path, allowed))) return refusal(`${file} is not in a folder this server may use.${allowed.length ? ` ${whereFiles(allowed)}` : ''}`)
268
+ const folder = await freeFolder(dirname(path), fileStem(basename(path).replace(/\.h5p$/i, '')))
269
+ let result
270
+ try {
271
+ result = await readPackage(path, folder, { within: allowed, libraries: options.libraries })
272
+ } catch (error) {
273
+ return refusal(error instanceof Error ? error.message : String(error))
274
+ } finally {
275
+ building.delete(folder.toLowerCase())
276
+ }
277
+ const media = result.files.length ? `, with its ${result.files.length} media file${result.files.length === 1 ? '' : 's'} beside it` : ''
278
+ const lines = [`Read ${path}: ${result.source.type}. Its source is in ${result.output}${media}.`]
279
+ for (const { path: at, message } of result.notes) lines.push(`Note: ${at} ${message}`)
280
+ const source = { ...result.source, params: located(result.source.params, folder) }
281
+ lines.push('', 'The source, each file named where it was written: change it as the person asks and pass it to h5p_build.', JSON.stringify(source))
282
+ return answer(lines.join('\n'))
283
+ })
284
+
285
+ server.registerTool('h5p_preview', {
286
+ title: 'Preview an H5P package',
287
+ description: PREVIEW,
288
+ inputSchema: z.object({ package: z.string().describe('The .h5p to open, in a folder this server may use') }),
289
+ annotations: { readOnlyHint: true, openWorldHint: false }
290
+ }, async ({ package: file }) => {
291
+ const allowed = await folders()
292
+ const path = resolve(allowed[0] ?? '.', file)
293
+ if (!allowed.length || !(await inside(path, allowed))) return refusal(`${file} is not in a folder this server may use.`)
294
+ let preview
295
+ try {
296
+ preview = await previewPackage({ file: path, libraries: options.libraries })
297
+ } catch (error) {
298
+ return refusal(error instanceof Error ? error.message : String(error))
299
+ }
300
+ previews.add(preview)
301
+ preview.closed.then(() => previews.delete(preview))
302
+ const address = `${preview.url}/`
303
+ const opened = options.open !== false && (await openBrowser(address))
304
+ return answer(`${opened ? `Opened ${basename(path)} in the browser at ${address}.` : `The preview of ${basename(path)} is at ${address}: open it in a browser.`} It is served from this computer until its tab is closed.`)
305
+ })
306
+
307
+ return {
308
+ server,
309
+ /** Ends every preview still open, as the server stops. */
310
+ close() {
311
+ for (const preview of previews) preview.close()
312
+ }
313
+ }
314
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@missing-elements/h5p-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "H5P Author MCP by Missing Elements: a local MCP server that builds playable H5P packages of any content type from a short source, checks them in a real player and opens them in the person's browser. No H5P server needed.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/missing-elements/h5p-toolkit.git",
9
+ "directory": "packages/mcp"
10
+ },
11
+ "homepage": "https://github.com/missing-elements/h5p-toolkit/tree/main/packages/mcp#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/missing-elements/h5p-toolkit/issues"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "type": "module",
19
+ "bin": {
20
+ "h5p-mcp": "./bin/h5p-mcp.mjs"
21
+ },
22
+ "exports": {
23
+ "./package.json": "./package.json"
24
+ },
25
+ "files": [
26
+ "bin",
27
+ "lib"
28
+ ],
29
+ "keywords": [
30
+ "h5p",
31
+ "mcp",
32
+ "model-context-protocol",
33
+ "authoring",
34
+ "elearning",
35
+ "quiz",
36
+ "ai"
37
+ ],
38
+ "dependencies": {
39
+ "@modelcontextprotocol/server": "^2.4.0",
40
+ "zod": "^4.6.7",
41
+ "@missing-elements/h5p-author": "^0.13.0",
42
+ "@missing-elements/h5p-verify": "^1.6.0"
43
+ },
44
+ "devDependencies": {
45
+ "@modelcontextprotocol/client": "^2.4.0",
46
+ "@types/node": "^26.6.6",
47
+ "typescript": "^7.0.2",
48
+ "vitest": "^5.1.0"
49
+ },
50
+ "engines": {
51
+ "node": ">=22"
52
+ },
53
+ "scripts": {
54
+ "test": "pnpm --filter @missing-elements/h5p-offline-player build && pnpm --filter @missing-elements/h5p-author exec node scripts/copy-skill.mjs && vitest run",
55
+ "typecheck": "tsc -p tsconfig.json"
56
+ }
6
57
  }