diff --git a/.gitignore b/.gitignore index ae5d323..ce53c7d 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,7 @@ packages/player/LICENSE packages/normalize/LICENSE packages/verify/LICENSE packages/author/LICENSE +packages/mcp/LICENSE # The h5p-author skill's text and build routes, which the author's `prepack` copies beside its type files (#178, #204). packages/author/SKILL.md packages/author/references/authoring.md diff --git a/AGENTS.md b/AGENTS.md index 27c6e3a..dca5f5f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,7 +40,7 @@ by assumption, and asks a page for what only a page can do through the frame: ## Where things are, and whose rules -A pnpm workspace of nine packages and two apps. [`design/layout.md`](design/layout.md) maps the +A pnpm workspace of ten packages and two apps. [`design/layout.md`](design/layout.md) maps the folders; in `design/`, `src/…` and `scripts/…` mean the player's unless a file says otherwise. | Part | What it is | Rules | @@ -51,6 +51,7 @@ folders; in `design/`, `src/…` and `scripts/…` mean the player's unless a fi | `packages/normalize/` | rewrites a package so it streams | [normalize](design/normalize.md) | | `packages/verify/` | plays a package headless and reports | [verify](design/verify.md) | | `packages/author/`, `skills/h5p-author/` | a playable package of any content type from a short source | [author](design/author.md) | +| `packages/mcp/` | the local MCP server: builds, checks and previews in an app with no shell | [mcp](design/mcp.md) | | `packages/cmi5/` | the element as a cmi5 assignable unit | [cmi5](design/cmi5.md) | | `packages/embed/`, `skills/h5p-to-scorm/` | the embed site for a player domain, and a package as a SCORM zip | [embed](design/embed.md), [scorm](design/scorm.md) | | `packages/vscode/` | H5P Preview, the VS Code extension | [vscode](design/vscode.md) | diff --git a/README.md b/README.md index db10d0e..582b1c4 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,7 @@ esbuild, and the one-prompt install on Lovable; | [`@missing-elements/h5p-verify`](https://github.com/missing-elements/h5p-offline-player/tree/main/packages/verify#readme) | Plays a package headless and reports whether it works, or opens it in your browser | | [`@missing-elements/h5p-normalize`](https://github.com/missing-elements/h5p-offline-player/tree/main/packages/normalize#readme) | Rewrites a package so its video streams | | [`@missing-elements/h5p-author`](https://github.com/missing-elements/h5p-offline-player/tree/main/packages/author#readme) | Builds a package of any content type from a short JSON source | +| [`@missing-elements/h5p-mcp`](https://github.com/missing-elements/h5p-offline-player/tree/main/packages/mcp#readme) | A local MCP server: an app such as Claude Desktop builds a package onto your disk, checks it and opens it in your browser | | [`@missing-elements/h5p-cmi5`](https://github.com/missing-elements/h5p-offline-player/tree/main/packages/cmi5#readme) | Makes a page holding the element a cmi5 assignable unit | | [H5P Preview](https://marketplace.visualstudio.com/items?itemName=MissingElements.h5p-preview) | Plays `.h5p` files in VS Code, and from [Open VSX](https://open-vsx.org/extension/MissingElements/h5p-preview) in Cursor and VSCodium | diff --git a/SECURITY.md b/SECURITY.md index 92b047b..21f549e 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -14,6 +14,8 @@ versions of the packages in this repository: | `@missing-elements/h5p-embed` | Latest release and `main` | | `@missing-elements/h5p-runtime` | Latest release and `main` | | `@missing-elements/h5p-libraries` | Latest release and `main` | +| `@missing-elements/h5p-author` | Latest release and `main` | +| `@missing-elements/h5p-mcp` | Latest release and `main` | | Demo and installable app | Deployment from `main` | Older releases may receive a fix when practical, but users should upgrade to a @@ -68,6 +70,20 @@ The relevant security boundary depends on how the player is deployed: cannot make a package's own JavaScript safe when the package plays as it is; that is what `untrusted` withholds. +The author package and the MCP server build packages from a source that a +model may have written: + +- Given `within`, a build reads local files and writes its package only in + those folders, links followed. Given `publicFetch`, it refuses to download + from a web address on a local network, redirects included; it resolves a + name and then asks, so it guards against a mistaken or planted address, not + a hostile network. A video on YouTube, Vimeo, Panopto or Echo360 is not + downloaded: its address is kept, and the player loads it wherever it points. +- The MCP server always builds so, in the folders the person gave it, else the + app's roots, as they are given. Given none, it uses Desktop, Documents and + Downloads, and never the home folder whole. It never writes over a file, and + its preview serves one package on `127.0.0.1` until its tab is closed. + Reports are particularly helpful for issues such as: - archive path traversal, package-to-package data exposure, or virtual-route @@ -82,8 +98,12 @@ Reports are particularly helpful for issues such as: - cross-origin request, redirect, or navigation-policy bypasses; - denial of service that defeats documented streaming, size, storage, or lifecycle safeguards; +- a build confined by `within` that reads or writes outside its folders or + writes over a file, `publicFetch` reaching a local network by an address it + should refuse, or the MCP server reaching a file outside its folders; - vulnerabilities in the published player, runtime, library bundle, normalizer, - verifier, cmi5 package, embed site writer, demo, or installable app. + verifier, author package, MCP server, cmi5 package, embed site writer, demo, + or installable app. A malicious H5P archive executing its own bundled JavaScript when it plays as it is, is an expected property of H5P, not by itself a vulnerability. It diff --git a/design/author.md b/design/author.md index a1ef636..948fbc2 100644 --- a/design/author.md +++ b/design/author.md @@ -308,12 +308,12 @@ text to the content check's rules, and `apps/skills` plays every example untrust - **A source's own fields are declared once, as `sourceSchema`** (#230). `sourceOf` takes the list of fields from it, holds each field to it and says its message where the field was written; it is the `Source` type, it takes no other field, as a build does not, and it is exported so that a - model can be shown the shape before writing a source. What one field cannot say alone stays in - `sourceOf`: the content type named loosely, a licence written with its version, a version for a - licence that takes none, and fields in the wrong place. Every problem of an author is said at - once, and an author written as a name alone is said with the object to write. It is zod/mini, - 23 kB minified, since a build runs in a page too, where zod's chained API takes 93 kB; JSON - Schema is made where it is shown. + model can be shown the shape before writing a source, as the MCP server shows it for + `h5p_build`'s source. What one field cannot say alone stays in `sourceOf`: the content type + named loosely, a licence written with its version, a version for a licence that takes none, and + fields in the wrong place. Every problem of an author is said at once, and an author written as + a name alone is said with the object to write. It is zod/mini, 23 kB minified, since a build + runs in a page too, where zod's chained API takes 93 kB; JSON Schema is made where it is shown. - **The skill is installed, and its page lists what step 3 fetches.** Claude and ChatGPT install the skill as a zip, and Grok reads the zip attached to a message; reading it by its link was dropped (missing-elements.github.io#42). Since the 0.10.0 pin the organisation's site serves the diff --git a/design/layout.md b/design/layout.md index 627b758..537f34c 100644 --- a/design/layout.md +++ b/design/layout.md @@ -1,6 +1,6 @@ # Layout -A pnpm workspace of nine packages and two apps. Eight packages are published to npm; the VS Code +A pnpm workspace of ten packages and two apps. Nine packages are published to npm; the VS Code extension is a `.vsix`. Paths in `design/` are relative to their part: `src/…` and `scripts/…` mean the player's unless a file says otherwise. `dist/`, `types/`, the player's `public/` and the runtime's `index.js` are generated and not in git. @@ -30,6 +30,8 @@ packages/verify/ a package played headless (lib/verify.mjs) and in a brows packages/author/ a playable .h5p from a short source: lib/build.mjs both builds, node.mjs Node's, generator.mjs content from semantics, check.mjs, outline.mjs, types.mjs the editor widgets' rules; scripts/ the skill's sync and copy +packages/mcp/ the local MCP server: bin/h5p-mcp.mjs the command, lib/server.mjs its three + tools, lib/folders.mjs the folders it may use packages/cmi5/ the element as a cmi5 AU: src/index.ts startCmi5, src/client.ts the protocol packages/embed/ site/ the embed page and the SCORM page; lib/build.mjs the site, lib/scorm*.mjs the SCORM zip in Node and in a page; scorm/ its launch page diff --git a/design/mcp.md b/design/mcp.md new file mode 100644 index 0000000..98c4d0c --- /dev/null +++ b/design/mcp.md @@ -0,0 +1,66 @@ +# The MCP server + +`packages/mcp` is `@missing-elements/h5p-mcp`, shown as **H5P Author MCP by Missing Elements**: a +local MCP server over standard input and output that builds a package onto the person's disk, +checks it, and opens it in their browser. It is for apps with no shell, Claude Desktop first; in an +app with a shell, the skill and `npx` build already. A remote server, for ChatGPT or Claude on the +web, is #210 and not this. + +- **It holds no rules of its own.** The build, its checks, the outline and the confinement to + folders (`buildPackage`, `within`, `publicFetch`, `inside`) are h5p-author's; the check, the + preview and opening the browser (`verifyPackage`, `summarize`, `previewPackage`, `openBrowser`) + are h5p-verify's. A rule a tool needs goes into those packages first, exported, so the author + package and the verifier are published before a server that uses something new of theirs. +- **Three tools, and the skill's flow as the instructions.** `h5p_types` lists the pack's content + types, those with a type file marked, and the skill's brief; given a type, read as a build reads + one (`sourceType`, so "true false" works), it answers with the type's file, or with `schemaOf` for + a type with none. `h5p_build` builds a source and `h5p_preview` opens a package. The instructions + are the flow in a few lines: the type is the one question, its answer is read before the source is + written, then the build, where the file is and what the check found, and the preview offered. + Not `SKILL.md`, whose build routes do not apply here. An app sends the descriptions and the + instructions with every message, so they stay under about 1,500 tokens; `server.test.ts` holds + them under 6,000 characters. +- **`h5p_build` shows a source's own fields; the build checks them.** Its `source` carries the + fields of the author package's `sourceSchema` as JSON Schema properties (#230), so a model writes + the authors and the licence right before its first build: without them, Haiku wrote + `"authors": ["Unknown"]` in 2 of 3 runs that built, and with them in none of 9. Nothing is said + to be required or forbidden, and the field takes any object, since the build reads a source + written another way as it is meant and says every problem at once (#174), where the SDK, or an + app that holds a call to the schema, would refuse it unread. +- **The folders: `--allow`, else the app's roots, else Desktop, Documents and Downloads.** A folder + the person named when adding the server is their choice and comes first; the app's roots come + next, asked on every call, since they change; both are taken as given. The defaults are never + the home folder whole: one that is a link to the home folder, or to a folder holding it, is left + out. A build reads local files and writes its package only there (`within`), and refuses to + download from an address on a local network (`publicFetch`, a guard against a model's mistake or + a planted address, not a hostile network); the preview opens only a package there (`inside`). A + hosted video's address is no download: it is kept, and the player loads it wherever it points, + since Panopto is often an institution's own server on its own network. +- **A build never writes over a file.** With no `output`, the package is named from its title + (`fileStem`: the title's letters and digits, in any script, cut at 60 characters, and `-file` + after a name Windows keeps for a device, as `con`). A name that is taken, the package's or its + source's, by a file or by a link even to nowhere, gets the next number, and so does a taken + `output`, as the build itself refuses to write over a file. A name is held while its build runs, + so builds at once take names of their own. The answer names the path written. Beside the package + goes its source, `.source.json`, which the build page opens to change and build again; it + is made new, never written over or through a link, and where it cannot be, the answer says so. +- **A build answers with the content, the check and a picture.** The build's line, its notes, the + outline (80 lines at most) and, with `verify`, the default, the verifier's summary of a check run + in a temporary folder, with its screenshot as an image. Where neither Chrome, Edge nor + Playwright's Chromium is found, the answer says "Not verified" and why. A source with problems + is refused, every problem by its path, and nothing is written. +- **The SDK is v2, and the package ships its source.** `@modelcontextprotocol/server` brings only + its core and zod, none of the HTTP frameworks v1 installed, so `bin/` and `lib/` are published as + written, with no bundle. `McpServer` on `StdioServerTransport` serves the 2025 protocol, which + every app speaks; protocol 2026-07-28 deprecates roots, so serving it would leave the folders to + `--allow` and the defaults. Standard output is the protocol's, so the command sends `console.log` + to standard error, and loads the server only after `--help` and `--version` have had their turn. +- **Tested as an app runs it.** `tests/server.test.ts` starts the command over standard input and + output with the SDK's own client, given one folder, and calls each tool: the list, a type by a + loose name and one with no file, a build checked in Chromium, a taken name and a link at one, + two builds at once, a source with a problem, an output outside the folder, a preview served and + one refused. Each test builds what it needs, so each runs alone. The test script first copies + the skill's type files into the author package, as the author's `prepack` does. + +Not built yet: reading a package back to a source (step 3 of #219), the MCP registry's +`server.json` and Claude Desktop's one-click bundle. diff --git a/docs/compatibility.md b/docs/compatibility.md index 8691d09..4b3bdf7 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -130,7 +130,8 @@ long as the player streams the result at least as well. The command's options, its exit codes — 0 plays, 1 does not, 2 could not run; with `--preview`, 0 when the preview ends and 2 when it could not start — `report.json`, to -which fields may be added, and `verifyPackage()` and `summarize()`, with their types: `VerifyReport` +which fields may be added, and `verifyPackage()`, `summarize()`, `previewPackage()` and +`openBrowser()`, with their types: `VerifyReport` is `report.json`'s shape, and gains fields the same way. The verifier is a step in other people's pipelines, so a check that turns a pass into a fail comes in a minor, never a patch; a new warning can come in any release. diff --git a/packages/author/README.md b/packages/author/README.md index 1b7fef8..266e848 100644 --- a/packages/author/README.md +++ b/packages/author/README.md @@ -197,7 +197,9 @@ plain lines for a review, made when it is first read: what the author wrote, the marked, slides, chapters and questions numbered, a scenario's links and a video's times written, interface texts and settings left out. `outlineOf(libraries, content, { limit })` makes one from what `loadLibraries` loaded for a content and the content, `{ type, params }`, as `checkContent` -takes them, cut at `limit` lines where one is given. +takes them, cut at `limit` lines where one is given. `await inside(path, folders)` is the +confinement `within` applies, for a tool beside the build that reads files of its own: whether a +path, links followed, is in one of the folders. ```js import { readFile } from 'node:fs/promises' diff --git a/packages/author/lib/author.mjs b/packages/author/lib/author.mjs index ee5c338..98bc5d2 100644 --- a/packages/author/lib/author.mjs +++ b/packages/author/lib/author.mjs @@ -16,7 +16,7 @@ import { schemaLines, schemaMarkdown } from './schema.mjs' import { LAYOUTS } from './types.mjs' export * from './core.mjs' -export { buildPackage, openPack, publicFetch, writeBundle, writeBundles } from './node.mjs' +export { buildPackage, inside, openPack, publicFetch, writeBundle, writeBundles } from './node.mjs' /** * @typedef {import('./node.mjs').BuildResult} BuildResult diff --git a/packages/author/tests/package-types.ts b/packages/author/tests/package-types.ts index 0ee4a35..01caed2 100644 --- a/packages/author/tests/package-types.ts +++ b/packages/author/tests/package-types.ts @@ -1,7 +1,7 @@ // The package as a caller sees it, by its own name: through the `types` condition, so this checks the // published declarations, not the source. `pnpm typecheck` writes them first. import { - allowedTags, buildPackage, bundleLibraries, checkContent, ContentGenerator, contentTypes, GENERATED_START, loadLibraries, markupText, openPack, packageLibraries, plainText, schemaOf, SourceError, + allowedTags, buildPackage, bundleLibraries, checkContent, ContentGenerator, contentTypes, GENERATED_START, inside, loadLibraries, markupText, openPack, packageLibraries, plainText, schemaOf, SourceError, sourceSchema, writeBundle, writeBundles, type BuildResult, type BundleResult, type CheckedContent, type LibraryRecord, type LibrarySource, type PackageFiles, type Source, type TranslationReport } from '@missing-elements/h5p-author' @@ -26,6 +26,9 @@ export async function check(): Promise<[BuildResult, string, string]> { const generator = new ContentGenerator(new Map(), { lenient: true, id: (count) => String(count) }) generator.problems.length = 0 void readSource + // A tool that confines what it reads to folders asks as a confined build does. + const confined: boolean = await inside('lesson/picture.png', ['lesson']) + void confined return [built, await schemaOf('H5P.Blanks', { markdown: true }), GENERATED_START] } diff --git a/packages/mcp/README.md b/packages/mcp/README.md new file mode 100644 index 0000000..34c0675 --- /dev/null +++ b/packages/mcp/README.md @@ -0,0 +1,65 @@ +# H5P Author MCP by Missing Elements + +`@missing-elements/h5p-mcp` lets an AI app make H5P content on your computer: quizzes, fill in the +blanks, flash cards, presentations, interactive books, branching scenarios and the rest of the 53 +content types the H5P hub serves. It writes a playable `.h5p` that carries its libraries, checks +that it plays in a real H5P player, and opens it in your browser. No H5P site, server or account. + +It is a local [MCP](https://modelcontextprotocol.io) server: your app starts it on your computer, +and it sends nothing to a server of ours. It needs Node 22 or newer, and for the check Chrome or +Edge; without either, run `npx playwright install chromium` once. + +## Add it to your app + +**Claude Desktop**: Settings, Developer, Edit Config, then in `claude_desktop_config.json`: + +```json +{ + "mcpServers": { + "h5p": { "command": "npx", "args": ["-y", "@missing-elements/h5p-mcp"] } + } +} +``` + +**Claude Code**: `claude mcp add h5p -- npx -y @missing-elements/h5p-mcp` + +**VS Code**: in `.vscode/mcp.json`: + +```json +{ "servers": { "h5p": { "command": "npx", "args": ["-y", "@missing-elements/h5p-mcp"] } } } +``` + +Then ask, for example: "Make a five-question quiz about the water cycle as an H5P file." + +## The folders it uses + +It reads the files your content names, and writes packages, only in its folders: those you give +with `--allow`, as in `"args": ["-y", "@missing-elements/h5p-mcp", "--allow", "/Users/me/Lessons"]` +(repeat it for more); else the folders your app gives it; else your Desktop, Documents and +Downloads, and then never your home folder whole. It never writes over a file: a name that is taken +gets a number, and it says which. + +## Tools + +- `h5p_types`: the content types, and how to write a source for one. +- `h5p_build`: a package from a source, its source beside it as `.source.json`. A source with + problems is refused, each problem named. It checks the package and says what it holds. +- `h5p_preview`: opens a package in your browser, in the real player, served from your computer + until its tab is closed. + +## What leaves your computer + +The build downloads each picture, video, recording or other file your content names by web +address, and refuses to download from an address on your local network: a guard against a mistaken +or planted address, not against a hostile network. A video on YouTube, Vimeo, Panopto or Echo360 is +not downloaded: it stays an address, which the player loads wherever it points, as H5P does +anywhere. Math is drawn by the package's own copy of MathJax, which loads nothing from elsewhere. +The check and the preview play the package from your computer. Your app +sends your conversation to its model, as it does without this server. + +## Licence + +MIT. The H5P libraries a package carries are under their own licences, listed in it. + +H5P is a trademark of H5P Group. This server is made by Missing Elements and is not affiliated with +or endorsed by H5P Group. diff --git a/packages/mcp/bin/h5p-mcp.mjs b/packages/mcp/bin/h5p-mcp.mjs new file mode 100644 index 0000000..cfa1926 --- /dev/null +++ b/packages/mcp/bin/h5p-mcp.mjs @@ -0,0 +1,59 @@ +#!/usr/bin/env node +import { readFile } from 'node:fs/promises' +import { parseArgs } from 'node:util' +import { StdioServerTransport } from '@modelcontextprotocol/server/stdio' + +// Standard output is the protocol's: anything a library prints there would break a message. +console.log = console.error +console.info = console.error + +const HELP = `Usage: h5p-mcp [--allow ]... [--no-open] + +H5P Author MCP by Missing Elements: an MCP server over standard input and output that builds +.h5p packages, checks that they play, and opens them in the browser. An app such as Claude +Desktop starts it; it does nothing on its own. + +Options: + --allow a folder builds may read files from and write packages to; repeat it for + more. Without it: the folders the app gives, else Desktop, Documents and + Downloads + --no-open answer a preview with its address instead of opening the browser + --version + -h, --help +` + +let values +try { + ;({ values } = parseArgs({ + options: { + allow: { type: 'string', multiple: true }, + 'no-open': { type: 'boolean' }, + version: { type: 'boolean' }, + help: { type: 'boolean', short: 'h' } + } + })) +} catch (error) { + console.error(`h5p-mcp: ${error instanceof Error ? error.message : error}\n\n${HELP}`) + process.exit(2) +} +if (values.help) { + process.stdout.write(HELP) + process.exit(0) +} +if (values.version) { + const { version } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')) + process.stdout.write(`@missing-elements/h5p-mcp ${version}\n`) + process.exit(0) +} + +// Loaded only now, so that --help and --version answer without loading the build and the pack. +const { createServer } = await import('../lib/server.mjs') +const { server, close } = await createServer({ allow: values.allow, open: !values['no-open'] }) +// The app ends the server by closing its input; a preview still open would keep it alive. +const stop = () => { + close() + process.exit(0) +} +process.stdin.on('end', stop) +process.stdin.on('close', stop) +await server.connect(new StdioServerTransport()) diff --git a/packages/mcp/lib/folders.mjs b/packages/mcp/lib/folders.mjs new file mode 100644 index 0000000..6963219 --- /dev/null +++ b/packages/mcp/lib/folders.mjs @@ -0,0 +1,58 @@ +import { realpath, stat } from 'node:fs/promises' +import { homedir } from 'node:os' +import { isAbsolute, join, relative, resolve, sep } from 'node:path' +import { fileURLToPath } from 'node:url' + +/** + * Where a build may read and write when neither the person nor the app named a folder: Desktop, + * Documents and Downloads, those that exist. Never the home folder whole, which holds keys and + * settings no build has a reason to read: one that is a link to the home folder, or to a folder + * that holds it, is left out. A link to a folder elsewhere, as on another drive, is kept. + * @param {string} [home] + * @returns {Promise} + */ +export async function defaultFolders(home = homedir()) { + const own = await realpath(home).catch(() => resolve(home)) + /** @type {string[]} */ + const found = [] + for (const name of ['Desktop', 'Documents', 'Downloads']) { + const path = join(home, name) + if (!(await stat(path).catch(() => null))?.isDirectory()) continue + const up = relative(await realpath(path), own) + if (up === '' || (!isAbsolute(up) && up !== '..' && !up.startsWith(`..${sep}`))) continue + found.push(path) + } + return found +} + +/** + * The folders among an app's roots: those it names by a `file:` address. A root of another scheme + * is no folder on this computer. + * @param {{ uri: string }[]} roots + * @returns {string[]} + */ +export function rootFolders(roots) { + return roots.filter((root) => root.uri.startsWith('file:')).map((root) => fileURLToPath(root.uri)) +} + +/** The names Windows keeps for its devices, an extension or not: no file can take one there. */ +const DEVICE = /^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])$/ + +/** + * A file name for a package from its title: its letters and digits, in any script and as written, + * joined by `-`, at most 60 characters; `h5p-content` for a title with none of them, and `-file` + * after a name Windows keeps for a device, as `con`. + * @param {unknown} title + * @returns {string} + */ +export function fileStem(title) { + const words = String(title ?? '') + .normalize('NFC') + .toLowerCase() + .replace(/[^\p{L}\p{M}\p{N}]+/gu, '-') + .replace(/^-+|-+$/g, '') + // Cut by characters, not by halves of one: a letter outside the basic range is two. + const stem = Array.from(words).slice(0, 60).join('').replace(/-+$/, '') + if (!stem) return 'h5p-content' + return DEVICE.test(stem) ? `${stem}-file` : stem +} diff --git a/packages/mcp/lib/server.mjs b/packages/mcp/lib/server.mjs new file mode 100644 index 0000000..7bdab70 --- /dev/null +++ b/packages/mcp/lib/server.mjs @@ -0,0 +1,251 @@ +import { lstat, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { basename, dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { McpServer } from '@modelcontextprotocol/server' +import { z } from 'zod' +import { SourceError, buildPackage, contentTypes, inside, openPack, publicFetch, schemaOf, sourceSchema, sourceType } from '@missing-elements/h5p-author' +import { VerifyError, openBrowser, previewPackage, summarize, verifyPackage } from '@missing-elements/h5p-verify' +import { defaultFolders, fileStem, rootFolders } from './folders.mjs' + +/** + * @typedef {object} ServerOptions + * @property {string[]} [allow] the folders a build may read and write, given when the server starts; + * they take precedence over the app's roots, which take precedence over Desktop, Documents and + * Downloads + * @property {boolean} [open] open a preview in the person's browser; default true + * @property {string} [libraries] the pack's `parts/` folder to build from; the installed pack by default + */ + +/** The skill's flow, which every app shows the model with the tools. */ +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. +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. +2. Call h5p_types with the type and write the source from its notes, example and fields: only what differs from the defaults. +3. Call h5p_build. Where it lists problems, fix each at its path and build again. +4. Tell the person where the file is and what the check found, and offer h5p_preview. +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.` + +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.` + +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.` + +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.` + +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.` + +/** + * A source's own fields as the author package declares them (#230), shown to the app as the + * properties of `source`, and nothing more: no field is said to be required and none forbidden. + * The build is the check, which reads a source written another way as it is meant (#174) and says + * every problem at once, where the SDK, or an app holding a call to the schema, would refuse it + * before the build looked. + */ +const SOURCE_PROPERTIES = z.toJSONSchema(sourceSchema, { io: 'input' }).properties + +/** @param {string} text */ +const answer = (text) => ({ content: [{ type: /** @type {const} */ ('text'), text }] }) +/** @param {string} text */ +const refusal = (text) => ({ content: [{ type: /** @type {const} */ ('text'), text }], isError: true }) + +/** @param {number} bytes */ +const sized = (bytes) => (bytes < 1e6 ? `${Math.max(1, Math.round(bytes / 1e3))} kB` : `${(bytes / 1e6).toFixed(1)} MB`) + +/** + * Where the person's files are, for the model: it cannot know, and a path it guesses is refused. + * @param {string[]} folders + */ +const whereFiles = (folders) => folders.length + ? `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]}.` + : 'This server has no folder to read or write in: start it with --allow .' + +/** Lines of an outline past which an answer says how many more there are. */ +const OUTLINE_LINES = 80 + +/** @param {string} path a package's */ +const sourceBeside = (path) => path.replace(/\.h5p$/i, '.source.json') + +/** + * The server and its three tools. It holds no rules of its own: the build, its checks and the + * confinement to folders are h5p-author's, the check and the preview h5p-verify's. + * @param {ServerOptions} [options] + */ +export async function createServer(options = {}) { + const { version } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')) + const server = new McpServer({ name: 'h5p-mcp', title: 'H5P Author MCP by Missing Elements', version }, { instructions: INSTRUCTIONS }) + const author = dirname(fileURLToPath(import.meta.resolve('@missing-elements/h5p-author/package.json'))) + const typeFiles = join(author, 'references', 'types') + /** @type {Set<{ close: () => void }>} */ + const previews = new Set() + + /** The folders a build may read and write, asked of the app on each call, since its roots can change. */ + async function folders() { + if (options.allow?.length) return options.allow.map((folder) => resolve(folder)) + if (server.server.getClientCapabilities()?.roots) { + try { + const found = rootFolders((await server.server.listRoots(undefined, { timeout: 5_000 })).roots) + if (found.length) return found + } catch { + // An app that says it has roots and does not answer gets the default folders. + } + } + return defaultFolders() + } + + /** @type {Promise<{ name: string, title: string }[]> | undefined} */ + let typeList + /** The pack's content types, read once: each needs its part opened. */ + function types() { + typeList ??= (async () => { + const pack = await openPack(options.libraries) + try { + return (await contentTypes(pack)).map((part) => ({ name: part.library.machineName, title: part.library.title })) + } finally { + await pack.close() + } + })() + return typeList + } + + /** The content types the skill has a file for, as the author package carries them. */ + async function filed() { + const names = await readdir(typeFiles).catch(() => []) + return new Set(names.filter((name) => name.endsWith('.md')).map((name) => name.slice(0, -3))) + } + + /** The packages being built, lower-cased, as macOS and Windows match a name in any case. */ + const building = new Set() + + /** + * A package's path in the folder, with a number added to the name where it is taken, the + * package's or its source's: a build never writes over a file, so a package built again takes + * the next number. A link takes its name too, even one that leads nowhere. The path is held for + * the build until it is let go of, so that builds at once take names of their own. + * @param {string} folder + * @param {string} stem the file name without `.h5p` + */ + async function freeName(folder, stem) { + for (let n = 1; ; n++) { + const path = join(folder, `${stem}${n === 1 ? '' : `-${n}`}.h5p`) + const taken = await Promise.all([path, sourceBeside(path)].map((each) => lstat(each).then(() => true, () => false))) + // Asked after the wait and held at once, with no wait between, so no other build takes it. + if (taken.includes(true) || building.has(path.toLowerCase())) continue + building.add(path.toLowerCase()) + return path + } + } + + server.registerTool('h5p_types', { + title: 'H5P content types', + description: TYPES, + inputSchema: z.object({ type: z.string().optional().describe('A content type, as H5P.MultiChoice or "multiple choice"') }), + annotations: { readOnlyHint: true, openWorldHint: false } + }, async ({ type }) => { + const list = await types() + const files = await filed() + // Said with every answer, before a source is written: a model cannot know the folders, and a + // path it guesses is refused. + const where = whereFiles(await folders()) + if (!type) { + const lines = list.map(({ name, title }) => `${files.has(name) ? '*' : '-'} ${name}: ${title}`) + const brief = await readFile(join(author, 'references', 'authoring.md'), 'utf8').catch(() => '') + return answer([LIST_HEAD, ...lines, '', where, ...(brief ? ['', brief] : [])].join('\n')) + } + const name = sourceType({ type }, list.map((each) => each.name)) + if (!name) return refusal(`The library pack has no content type "${type}". h5p_types with no type lists them.`) + const text = files.has(name) ? await readFile(join(typeFiles, `${name}.md`), 'utf8') : await schemaOf(name, { markdown: true, libraries: options.libraries }) + return answer(`${text.trimEnd()}\n\n${where}`) + }) + + server.registerTool('h5p_build', { + title: 'Build an H5P package', + description: BUILD, + inputSchema: z.object({ + source: z.record(z.string(), z.unknown()).meta({ properties: SOURCE_PROPERTIES, description: 'The source, as h5p_types describes it for its type' }), + 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'), + verify: z.boolean().optional().describe('Play it and report whether it works; default true') + }), + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true } + }, async ({ source, output, verify = true }) => { + const allowed = await folders() + if (!allowed.length) return refusal('This server has no folder to write in: start it with --allow , or give it a folder from the app.') + let target = resolve(allowed[0], output || `${fileStem(source.title)}.h5p`) + if (!/\.h5p$/i.test(target)) target += '.h5p' + // Said here, with the folders, since a model cannot know them: the build's own refusal names none. + 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.`) + // A name that is taken gets a number, as a build never writes over a file. + target = await freeName(dirname(target), basename(target).replace(/\.h5p$/i, '')) + const sourceFile = sourceBeside(target) + let result + /** @type {Error | undefined} */ + let unwritten + try { + result = await buildPackage(source, target, { base: dirname(target), within: allowed, fetch: publicFetch, libraries: options.libraries }) + // Made new: a file or a link put at its name since the name was found free is not written through. + unwritten = await writeFile(sourceFile, `${JSON.stringify(source, null, 2)}\n`, { flag: 'wx' }).then(() => undefined, (error) => error) + } catch (error) { + if (error instanceof SourceError) return refusal(`${error.message}\nFix each at its path and build again.${/outside the folders/.test(error.message) ? ` ${whereFiles(allowed)}` : ''}`) + return refusal(error instanceof Error ? error.message : String(error)) + } finally { + building.delete(target.toLowerCase()) + } + const install = result.install.length ? `, ${result.install.length} more for installing on an H5P site` : '' + const media = result.media.length ? `, ${result.media.length} media file${result.media.length === 1 ? '' : 's'}` : '' + const lines = [ + `Built ${target} (${sized((await stat(target)).size)}): ${result.manifest.mainLibrary}, ${result.libraries.length} libraries${install}${media}.`, + unwritten + ? `Its source was not written beside it: ${unwritten.message}` + : `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.` + ] + for (const { path, message } of result.notes) lines.push(`Note: ${path} ${message}`) + const outline = result.outline.split('\n') + lines.push('', 'What it holds:', ...outline.slice(0, OUTLINE_LINES)) + if (outline.length > OUTLINE_LINES) lines.push(`… and ${outline.length - OUTLINE_LINES} more lines.`) + /** @type {{ type: 'image', data: string, mimeType: string }[]} */ + const images = [] + if (verify) { + const out = await mkdtemp(join(tmpdir(), 'h5p-mcp-')) + try { + const report = await verifyPackage({ file: target, out, libraries: options.libraries }) + // Its screenshot goes with the answer as an image; the path it was written to is gone. + lines.push('', summarize(report).split('\n').filter((line) => !/^\s*screenshot:/.test(line)).join('\n')) + const shot = await readFile(join(out, 'screenshot.png')).catch(() => null) + if (shot) images.push({ type: 'image', data: shot.toString('base64'), mimeType: 'image/png' }) + } catch (error) { + lines.push('', `Not verified: ${error instanceof VerifyError || error instanceof Error ? error.message : String(error)}`) + } finally { + await rm(out, { recursive: true, force: true }) + } + } + return { content: [{ type: /** @type {const} */ ('text'), text: lines.join('\n') }, ...images] } + }) + + server.registerTool('h5p_preview', { + title: 'Preview an H5P package', + description: PREVIEW, + inputSchema: z.object({ package: z.string().describe('The .h5p to open, in a folder this server may use') }), + annotations: { readOnlyHint: true, openWorldHint: false } + }, async ({ package: file }) => { + const allowed = await folders() + const path = resolve(allowed[0] ?? '.', file) + if (!allowed.length || !(await inside(path, allowed))) return refusal(`${file} is not in a folder this server may use.`) + let preview + try { + preview = await previewPackage({ file: path, libraries: options.libraries }) + } catch (error) { + return refusal(error instanceof Error ? error.message : String(error)) + } + previews.add(preview) + preview.closed.then(() => previews.delete(preview)) + const address = `${preview.url}/` + const opened = options.open !== false && (await openBrowser(address)) + 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.`) + }) + + return { + server, + /** Ends every preview still open, as the server stops. */ + close() { + for (const preview of previews) preview.close() + } + } +} diff --git a/packages/mcp/package.json b/packages/mcp/package.json new file mode 100644 index 0000000..d7a4847 --- /dev/null +++ b/packages/mcp/package.json @@ -0,0 +1,59 @@ +{ + "name": "@missing-elements/h5p-mcp", + "version": "0.1.0", + "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.", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/missing-elements/h5p-offline-player.git", + "directory": "packages/mcp" + }, + "homepage": "https://github.com/missing-elements/h5p-offline-player/tree/main/packages/mcp#readme", + "bugs": { + "url": "https://github.com/missing-elements/h5p-offline-player/issues" + }, + "publishConfig": { + "access": "public" + }, + "type": "module", + "bin": { + "h5p-mcp": "./bin/h5p-mcp.mjs" + }, + "exports": { + "./package.json": "./package.json" + }, + "files": [ + "bin", + "lib" + ], + "keywords": [ + "h5p", + "mcp", + "model-context-protocol", + "authoring", + "elearning", + "quiz", + "ai" + ], + "scripts": { + "test": "pnpm --filter @missing-elements/h5p-offline-player build && pnpm --filter @missing-elements/h5p-author exec node scripts/copy-skill.mjs && vitest run", + "typecheck": "tsc -p tsconfig.json", + "prepack": "node -e \"require('node:fs').copyFileSync('../../LICENSE', 'LICENSE')\"", + "prepublishOnly": "node -e \"if (!/^pnpm\\//.test(process.env.npm_config_user_agent || '')) { console.error('Publish with pnpm publish: npm would ship the workspace:^ dependency ranges as they are, and the package would not install.'); process.exit(1) }\" && pnpm typecheck && pnpm test" + }, + "dependencies": { + "@missing-elements/h5p-author": "workspace:^", + "@missing-elements/h5p-verify": "workspace:^", + "@modelcontextprotocol/server": "^2.4.0", + "zod": "^4.6.7" + }, + "devDependencies": { + "@modelcontextprotocol/client": "^2.4.0", + "@types/node": "^26.6.6", + "typescript": "^7.0.2", + "vitest": "^5.1.0" + }, + "engines": { + "node": ">=22" + } +} diff --git a/packages/mcp/tests/folders.test.ts b/packages/mcp/tests/folders.test.ts new file mode 100644 index 0000000..abb10f6 --- /dev/null +++ b/packages/mcp/tests/folders.test.ts @@ -0,0 +1,55 @@ +import { mkdir, mkdtemp, rm, symlink } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { describe, expect, it } from 'vitest' +import { defaultFolders, fileStem, rootFolders } from '../lib/folders.mjs' + +describe('the folders a build may use', () => { + it('are Desktop, Documents and Downloads where they exist, never the home folder whole', async () => { + const home = await mkdtemp(join(tmpdir(), 'h5p-mcp-home-')) + const drive = await mkdtemp(join(tmpdir(), 'h5p-mcp-drive-')) + try { + await mkdir(join(home, 'Documents')) + expect(await defaultFolders(home)).toEqual([join(home, 'Documents')]) + // A link to a folder elsewhere, as on another drive, is that folder; a link to the home + // folder, or to one that holds it, would open the whole of it. + await symlink(drive, join(home, 'Downloads'), 'junction') + await symlink(home, join(home, 'Desktop'), 'junction') + expect(await defaultFolders(home)).toEqual([join(home, 'Documents'), join(home, 'Downloads')]) + await rm(join(home, 'Desktop')) + await symlink(dirname(home), join(home, 'Desktop'), 'junction') + expect(await defaultFolders(home)).toEqual([join(home, 'Documents'), join(home, 'Downloads')]) + } finally { + await rm(home, { recursive: true, force: true }) + await rm(drive, { recursive: true, force: true }) + } + }) + + it('are the app\'s roots that are folders on this computer', () => { + const folder = join(tmpdir(), 'lesson') + expect(rootFolders([{ uri: pathToFileURL(folder).href }, { uri: 'https://example.com/repo' }])).toEqual([folder]) + }) +}) + +describe('a package\'s file name', () => { + it('is its title\'s letters and digits, in any script', () => { + expect(fileStem('Water cycle: 3 questions!')).toBe('water-cycle-3-questions') + expect(fileStem('Мій тест')).toBe('мій-тест') + expect(fileStem('Größe & Maß')).toBe('größe-maß') + }) + + it('is cut at 60 characters, and stands in for a title with none', () => { + expect(fileStem('a'.repeat(40) + ' ' + 'b'.repeat(40))).toBe(`${'a'.repeat(40)}-${'b'.repeat(19)}`) + // Characters, not halves of one: a letter outside the basic range is two. + expect(fileStem(`a${'𠀀'.repeat(70)}`)).toBe(`a${'𠀀'.repeat(59)}`) + expect(fileStem('?!')).toBe('h5p-content') + expect(fileStem(undefined)).toBe('h5p-content') + }) + + it('is never a name Windows keeps for a device', () => { + expect(fileStem('Con')).toBe('con-file') + expect(fileStem('LPT1')).toBe('lpt1-file') + expect(fileStem('Console')).toBe('console') + }) +}) diff --git a/packages/mcp/tests/server.test.ts b/packages/mcp/tests/server.test.ts new file mode 100644 index 0000000..aac5fd2 --- /dev/null +++ b/packages/mcp/tests/server.test.ts @@ -0,0 +1,170 @@ +import { access, mkdtemp, readFile, readdir, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { basename, join, resolve } from 'node:path' +import { Client } from '@modelcontextprotocol/client' +import { StdioClientTransport } from '@modelcontextprotocol/client/stdio' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' + +/** + * The server as an app runs it: the command the package ships, started over standard input and + * output, given one folder, asked through the SDK's own client. The build's rules are the author + * package's and tested there; these hold the server to calling them, to its folders, and to its + * answers. Each test builds what it needs, under a title of its own. + */ + +const COMMAND = resolve(import.meta.dirname, '../bin/h5p-mcp.mjs') +const SOURCE = { + type: 'H5P.TrueFalse', + title: 'Boiling point', + language: 'en', + license: 'U', + authors: [{ name: 'Unknown', role: 'Author' }], + params: { question: '

Water boils at 100 °C at sea level.

', correct: 'true' } +} + +type Content = { type: string, text?: string, data?: string, mimeType?: string } +type Answer = { content: Content[], isError?: boolean } + +let folder: string +/** A folder the server may not use. */ +let elsewhere: string +let client: Client + +const call = async (name: string, args: Record = {}) => (await client.callTool({ name, arguments: args })) as Answer +const textOf = (answer: Answer) => answer.content.filter((part) => part.type === 'text').map((part) => part.text).join('\n') +/** The path a build's answer names, if it built. */ +const builtOf = (answer: Answer) => /^Built (.+?\.h5p) \(/m.exec(textOf(answer))?.[1] +const build = async (title: string, args: Record = {}) => builtOf(await call('h5p_build', { source: { ...SOURCE, title }, verify: false, ...args })) + +beforeAll(async () => { + folder = await mkdtemp(join(tmpdir(), 'h5p-mcp-')) + elsewhere = await mkdtemp(join(tmpdir(), 'h5p-mcp-elsewhere-')) + client = new Client({ name: 'h5p-mcp-test', version: '0' }) + await client.connect(new StdioClientTransport({ command: process.execPath, args: [COMMAND, '--allow', folder, '--no-open'], stderr: 'pipe' })) +}) + +afterAll(async () => { + await client?.close() + await rm(folder, { recursive: true, force: true }) + await rm(elsewhere, { recursive: true, force: true }) +}) + +describe('the server', () => { + it('offers three tools and the flow, in few words', async () => { + const { tools } = await client.listTools() + expect(tools.map((tool) => tool.name).sort()).toEqual(['h5p_build', 'h5p_preview', 'h5p_types']) + expect(client.getInstructions()).toMatch(/h5p_types[\s\S]*h5p_build[\s\S]*h5p_preview/) + // A source's own fields as the author package declares them, before one is written (#230), + // with nothing required or forbidden, so no app refuses a source the build would read (#174). + const source = tools.find((tool) => tool.name === 'h5p_build')?.inputSchema.properties?.source as Record + expect(source.properties).toMatchObject({ license: { enum: expect.arrayContaining(['U', 'CC BY']) }, authors: { items: { required: ['name', 'role'] } } }) + expect(source).not.toHaveProperty('required') + expect(source.additionalProperties).not.toBe(false) + // What an app sends the model with every message: under about 1,500 tokens at four characters each. + expect(JSON.stringify(tools).length + (client.getInstructions()?.length ?? 0)).toBeLessThan(6_000) + }) +}) + +describe('h5p_types', () => { + it('lists the pack\'s content types, marking those with a type file, and how to write good content', async () => { + const answer = await call('h5p_types') + const text = textOf(answer) + expect(answer.isError).toBeFalsy() + expect(text).toContain('* H5P.QuestionSet: ') + expect(text).toContain('- H5P.AdvancedBlanks: ') + expect(text).toContain('# The brief, and good content') + }) + + it('answers a type named loosely with its file, and where the person\'s files are', async () => { + const text = textOf(await call('h5p_types', { type: 'true false' })) + expect(text).toContain('(H5P.TrueFalse)') + expect(text).toContain('"correct"') + expect(text).toContain(`This server reads files and writes packages only in ${folder}.`) + }) + + it('answers a type with no file with its fields', async () => { + const answer = await call('h5p_types', { type: 'H5P.AdvancedBlanks' }) + expect(answer.isError).toBeFalsy() + expect(textOf(answer)).toContain('H5P.AdvancedBlanks') + }) + + it('refuses a type the pack has not', async () => { + const answer = await call('h5p_types', { type: 'no such type' }) + expect(answer.isError).toBe(true) + expect(textOf(answer)).toContain('h5p_types with no type lists them') + }) +}) + +describe('h5p_build', () => { + it('writes the package and its source in its folder, checks it, and says what it holds', async () => { + const answer = await call('h5p_build', { source: SOURCE }) + const text = textOf(answer) + expect(answer.isError).toBeFalsy() + expect(text).toContain(`Built ${join(folder, 'boiling-point.h5p')}`) + expect(text).toContain('Water boils at 100 °C at sea level.') + expect(text).toMatch(/^pass {2}boiling-point\.h5p/m) + expect(text).not.toMatch(/screenshot:/) + expect(answer.content.some((part) => part.type === 'image' && part.mimeType === 'image/png')).toBe(true) + expect(JSON.parse(await readFile(join(folder, 'boiling-point.source.json'), 'utf8'))).toEqual(SOURCE) + }) + + it('takes the next number rather than write over a file', async () => { + expect(await build('Again')).toBe(join(folder, 'again.h5p')) + expect(await build('Again')).toBe(join(folder, 'again-2.h5p')) + await writeFile(join(folder, 'mine.h5p'), 'the person\'s own file') + expect(await build('Boiling point', { output: 'mine.h5p' })).toBe(join(folder, 'mine-2.h5p')) + expect(await readFile(join(folder, 'mine.h5p'), 'utf8')).toBe('the person\'s own file') + }) + + // A link to a file takes privileges Windows does not give by default. + it.skipIf(process.platform === 'win32')('takes the next number rather than write through a link', async () => { + // A link holds its name, even one that leads nowhere: written through, it would make a file + // outside the folder. + const outside = join(elsewhere, 'source.json') + await symlink(outside, join(folder, 'linked.source.json')) + expect(await build('Linked')).toBe(join(folder, 'linked-2.h5p')) + await expect(access(outside)).rejects.toThrow() + }) + + it('gives builds made at once names of their own', async () => { + const both = await Promise.all([build('Twice'), build('Twice')]) + expect(both.sort()).toEqual([join(folder, 'twice-2.h5p'), join(folder, 'twice.h5p')]) + }) + + it('refuses a source with problems, each by its path, and writes nothing', async () => { + const before = await readdir(folder) + const answer = await call('h5p_build', { source: { ...SOURCE, title: 'Broken', params: { ...SOURCE.params, correct: 'maybe' } }, verify: false }) + expect(answer.isError).toBe(true) + expect(textOf(answer)).toMatch(/params\.correct/) + // A source unlike the shape the app is shown reaches the build, which says all it finds at once (#230). + const loose = textOf(await call('h5p_build', { source: { ...SOURCE, title: 'Loose', authors: ['Unknown'], params: { ...SOURCE.params, correct: 'maybe' } }, verify: false })) + expect(loose).toContain('authors[0]: expected an author: write { "name": "Unknown", "role": "Author" }') + expect(loose).toMatch(/params\.correct/) + expect(await readdir(folder)).toEqual(before) + }) + + it('writes nowhere but its folders', async () => { + const answer = await call('h5p_build', { source: SOURCE, output: join(elsewhere, 'boiling-point.h5p'), verify: false }) + expect(answer.isError).toBe(true) + // A model cannot know the folders, so the refusal names them and the way out. + expect(textOf(answer)).toContain(`outside the folders this server may write in: ${folder}. Give a file name alone, or leave output out.`) + }) +}) + +describe('h5p_preview', () => { + it('serves a package in its folders, and answers with the address', async () => { + const file = await build('Preview') + expect(file).toBeTruthy() + const answer = await call('h5p_preview', { package: basename(file!) }) + expect(answer.isError).toBeFalsy() + const address = /http:\/\/127\.0\.0\.1:\d+\//.exec(textOf(answer))?.[0] + expect(address).toBeTruthy() + expect((await fetch(address!)).status).toBe(200) + }) + + it('refuses a file outside its folders', async () => { + const answer = await call('h5p_preview', { package: join(elsewhere, 'boiling-point.h5p') }) + expect(answer.isError).toBe(true) + expect(textOf(answer)).toContain('not in a folder this server may use') + }) +}) diff --git a/packages/mcp/tsconfig.json b/packages/mcp/tsconfig.json new file mode 100644 index 0000000..c310201 --- /dev/null +++ b/packages/mcp/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022"], + "types": ["node"], + "strict": true, + "noEmit": true, + "allowJs": true, + "isolatedModules": true, + "esModuleInterop": true, + "skipLibCheck": true, + "checkJs": true + }, + "include": ["bin/**/*.mjs", "lib/**/*.mjs", "tests/**/*.ts"] +} diff --git a/packages/mcp/vitest.config.ts b/packages/mcp/vitest.config.ts new file mode 100644 index 0000000..14391e5 --- /dev/null +++ b/packages/mcp/vitest.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from 'vitest/config' + +// The server runs as its user's app runs it: the command, started over standard input and output. +// A build with its check plays the package in Chromium, which takes seconds. +export default defineConfig({ + test: { + environment: 'node', + include: ['tests/**/*.test.ts'], + testTimeout: 120_000, + hookTimeout: 120_000 + } +}) diff --git a/packages/verify/README.md b/packages/verify/README.md index 55577af..b524211 100644 --- a/packages/verify/README.md +++ b/packages/verify/README.md @@ -117,6 +117,11 @@ if (report.verdict !== 'pass') process.exit(1) TypeScript declarations ship with the package: `VerifyReport` is `report.json`'s shape. +`previewPackage({ file, libraries, untrusted })` serves the preview as `--preview` does and gives +its `url`, `close()`, and a `closed` promise that settles with `closed` once its last tab has gone, +`unopened` when no tab came within ten minutes, or `stopped` after `close()`. `openBrowser(url)` +opens an address in the default browser, false where no opener started. + An [agent skill](https://agentskills.io) for it ships in the repository: `npx skills add missing-elements/h5p-offline-player --skill h5p-verify`. diff --git a/packages/verify/lib/preview.mjs b/packages/verify/lib/preview.mjs index a12e3cc..6b275d9 100644 --- a/packages/verify/lib/preview.mjs +++ b/packages/verify/lib/preview.mjs @@ -55,7 +55,6 @@ const HEARTBEAT_MS = 15_000 * Serves the package and its page until the preview is stopped or stops by itself: `closed` * settles with `closed` once its last tab has gone, `unopened` when no tab came within `openWait`, * and `stopped` after `close()`. - * @internal * @param {PreviewOptions} options * @returns {Promise<{ url: string, closed: Promise<'closed' | 'unopened' | 'stopped'>, close: () => void }>} */ @@ -214,7 +213,6 @@ export function byteRange(header, size) { /** * Opens `url` in the default browser. False when no opener could be started, `xdg-open` missing on * a server for one; the command prints the address either way. - * @internal * @param {string} url * @returns {Promise} */ diff --git a/packages/verify/lib/verify.mjs b/packages/verify/lib/verify.mjs index 92826b5..50c40d8 100644 --- a/packages/verify/lib/verify.mjs +++ b/packages/verify/lib/verify.mjs @@ -6,6 +6,7 @@ import { chromium, errors as playwrightErrors } from 'playwright-core' import { VerifyError, librarySources, packageFile, playerDist, sendFile, serve } from './serve.mjs' export { VerifyError } +export { openBrowser, previewPackage } from './preview.mjs' /** @import { DowngradedLibrary, H5PPlayerElement, PlayerErrorDetail, PlayerState, RefreshedLibrary } from '@missing-elements/h5p-offline-player' */ diff --git a/packages/verify/tests/package-types.ts b/packages/verify/tests/package-types.ts index bd6d465..7c85187 100644 --- a/packages/verify/tests/package-types.ts +++ b/packages/verify/tests/package-types.ts @@ -3,7 +3,7 @@ * of its `exports`, from the declarations `pnpm types` generates from the JSDoc. Type-checked by * `pnpm typecheck`; nothing here runs. */ -import { VerifyError, summarize, verifyPackage, type VerifyReport } from '@missing-elements/h5p-verify' +import { VerifyError, openBrowser, previewPackage, summarize, verifyPackage, type VerifyReport } from '@missing-elements/h5p-verify' // @ts-expect-error a helper the tests use, not part of the package's API (#60) import { contentChanges } from '@missing-elements/h5p-verify' @@ -17,6 +17,12 @@ export async function asACallerWould(): Promise { // @ts-expect-error an option the verifier does not take await verifyPackage({ file: 'course.h5p', timeout: 1_000 }) - void [passed, missing, changed, refreshed, contentChanges, new VerifyError('could not run') instanceof Error] + // The preview, as a tool beside the verifier opens one: its address, and when it ended. + const preview = await previewPackage({ file: 'course.h5p', untrusted: true }) + const opened: boolean = await openBrowser(`${preview.url}/`) + const ended: 'closed' | 'unopened' | 'stopped' = await preview.closed + preview.close() + + void [passed, missing, changed, refreshed, opened, ended, contentChanges, new VerifyError('could not run') instanceof Error] return summarize(report) } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d16385c..e18723a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -187,6 +187,34 @@ importers: specifier: ^2.24.0 version: 2.24.0 + packages/mcp: + dependencies: + '@missing-elements/h5p-author': + specifier: workspace:^ + version: link:../author + '@missing-elements/h5p-verify': + specifier: workspace:^ + version: link:../verify + '@modelcontextprotocol/server': + specifier: ^2.4.0 + version: 2.4.0 + zod: + specifier: ^4.6.7 + version: 4.6.7 + devDependencies: + '@modelcontextprotocol/client': + specifier: ^2.4.0 + version: 2.4.0 + '@types/node': + specifier: ^26.6.6 + version: 26.6.6 + typescript: + specifier: ^7.0.2 + version: 7.0.2 + vitest: + specifier: ^5.1.0 + version: 5.1.0(@types/node@26.6.6)(@vitest/browser-playwright@5.1.0)(@vitest/ui@5.1.0)(vite@8.3.6(@types/node@26.6.6)(esbuild@0.28.2)) + packages/normalize: dependencies: '@zip.js/zip.js': @@ -682,6 +710,18 @@ packages: resolution: {integrity: sha512-8/12nvkR9dlOZIrTKJhqFs0NLTZkJlQrA9hNP68mUmJwuVKJ1DicTDhW3S50OqefpYGFts/GhFpURbwllmEhvw==} engines: {node: '>=20'} + '@modelcontextprotocol/client@2.4.0': + resolution: {integrity: sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww==} + engines: {node: '>=20'} + + '@modelcontextprotocol/core@2.4.0': + resolution: {integrity: sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==} + engines: {node: '>=20'} + + '@modelcontextprotocol/server@2.4.0': + resolution: {integrity: sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==} + engines: {node: '>=20'} + '@napi-rs/keyring-darwin-arm64@1.3.0': resolution: {integrity: sha512-pl76hJvdYUBn6I24bXiOBMA9nbDapo3I5B+f3OorjDU4dUMSypXeKbOVehJe8fhgTiH24flMyTS3aAIy43xegQ==} engines: {node: '>= 10'} @@ -1394,6 +1434,10 @@ packages: engines: {node: '>=18'} hasBin: true + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + debug@4.4.3: resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} engines: {node: '>=6.0'} @@ -1478,6 +1522,14 @@ packages: estree-walker@3.0.3: resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + eventsource-parser@3.1.1: + resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} + engines: {node: '>=18.0.0'} + + eventsource@3.0.7: + resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==} + engines: {node: '>=18.0.0'} + expect-type@1.4.0: resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} engines: {node: '>=12.0.0'} @@ -1618,10 +1670,16 @@ packages: isarray@1.0.0: resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==} + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + istextorbinary@9.5.0: resolution: {integrity: sha512-5mbUj3SiZXCuRf9fT3ibzbSSEWiy63gFfksmGfdOzujPjW3k+z8WvIBxcJHBoQNlaZaiyB25deviif2+osLmLw==} engines: {node: '>=4'} + jose@6.2.17: + resolution: {integrity: sha512-wOuK9V1yujQFH5S0ZWmLcDZN7+IKh9bUCC2ZPCf2HDlol3WWHy+PPyNjEI75FXRLMp3vDKQcupP59xhVU95hcg==} + jsonc-parser@3.3.1: resolution: {integrity: sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==} @@ -1847,6 +1905,10 @@ packages: parse5@8.1.0: resolution: {integrity: sha512-sq3qBFpee5jeocbFbO48VHlGr8sT7mbXS0vxlKN6sottBtJzrOG3998sr0llSZcQAGgfpdmEYAIZE0P9z0dE8w==} + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + pathe@2.0.3: resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} @@ -1860,6 +1922,10 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} + pkce-challenge@5.0.1: + resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==} + engines: {node: '>=16.20.0'} + playwright-core@1.65.0: resolution: {integrity: sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA==} engines: {node: '>=20'} @@ -1949,6 +2015,14 @@ packages: setimmediate@1.0.5: resolution: {integrity: sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==} + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + shiki@4.6.0: resolution: {integrity: sha512-imjLsVHgPuWhvpU3P+zOekvMYqnel7QmKsFC4Sn0fCuAvaaalBsxwKEsrU8Ko5BdFnZA6Go/8a0RzahS634UgA==} engines: {node: '>=20'} @@ -2186,6 +2260,11 @@ packages: jsdom: optional: true + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true + why-is-node-running@3.2.1: resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==} engines: {node: '>=20.11'} @@ -2553,6 +2632,25 @@ snapshots: '@zip.js/zip.js': 2.24.0 h5p-standalone: 3.8.2 + '@modelcontextprotocol/client@2.4.0': + dependencies: + '@modelcontextprotocol/core': 2.4.0 + cross-spawn: 7.0.6 + eventsource: 3.0.7 + eventsource-parser: 3.1.1 + jose: 6.2.17 + pkce-challenge: 5.0.1 + zod: 4.6.7 + + '@modelcontextprotocol/core@2.4.0': + dependencies: + zod: 4.6.7 + + '@modelcontextprotocol/server@2.4.0': + dependencies: + '@modelcontextprotocol/core': 2.4.0 + zod: 4.6.7 + '@napi-rs/keyring-darwin-arm64@1.3.0': optional: true @@ -3111,6 +3209,12 @@ snapshots: transitivePeerDependencies: - '@types/node' + cross-spawn@7.0.6: + dependencies: + path-key: 3.1.1 + shebang-command: 2.0.0 + which: 2.0.2 + debug@4.4.3: dependencies: ms: 2.1.3 @@ -3207,6 +3311,12 @@ snapshots: dependencies: '@types/estree': 1.0.10 + eventsource-parser@3.1.1: {} + + eventsource@3.0.7: + dependencies: + eventsource-parser: 3.1.1 + expect-type@1.4.0: {} fdir@6.5.0(picomatch@4.0.7): @@ -3339,12 +3449,16 @@ snapshots: isarray@1.0.0: {} + isexe@2.0.0: {} + istextorbinary@9.5.0: dependencies: binaryextensions: 6.11.0 editions: 6.22.0 textextensions: 6.11.0 + jose@6.2.17: {} + jsonc-parser@3.3.1: {} jsonwebtoken@9.0.3: @@ -3570,6 +3684,8 @@ snapshots: dependencies: entities: 9.0.0 + path-key@3.1.1: {} + pathe@2.0.3: {} pend@1.2.0: {} @@ -3578,6 +3694,8 @@ snapshots: picomatch@4.0.7: {} + pkce-challenge@5.0.1: {} + playwright-core@1.65.0: {} playwright@1.65.0: @@ -3675,6 +3793,12 @@ snapshots: setimmediate@1.0.5: {} + shebang-command@2.0.0: + dependencies: + shebang-regex: 3.0.0 + + shebang-regex@3.0.0: {} + shiki@4.6.0: dependencies: '@shikijs/core': 4.6.0 @@ -3897,6 +4021,10 @@ snapshots: transitivePeerDependencies: - msw + which@2.0.2: + dependencies: + isexe: 2.0.0 + why-is-node-running@3.2.1: {} wrap-ansi@6.2.0: