From a0e01a5384f1df487a197f870bfb7feaca3f7f9e Mon Sep 17 00:00:00 2001 From: Aleksandr Shevchuk Date: Tue, 24 Nov 2026 13:36:03 +0200 Subject: [PATCH 1/3] feat(mcp): the app server and its card for a chat app, and a check in h5p-author that reads no file (#270) --- AGENTS.md | 2 +- design/author.md | 6 + design/mcp.md | 62 ++++- packages/author/README.md | 9 +- packages/author/lib/media.mjs | 36 ++- packages/author/lib/node.mjs | 20 +- packages/author/tests/confine.test.ts | 59 +++++ packages/mcp/README.md | 29 ++- packages/mcp/bin/h5p-mcp-app.mjs | 91 ++++++++ packages/mcp/lib/answers.mjs | 101 ++++++++ packages/mcp/lib/app.mjs | 173 ++++++++++++++ packages/mcp/lib/card.html | 317 ++++++++++++++++++++++++++ packages/mcp/lib/server.mjs | 71 +----- packages/mcp/package.json | 3 +- packages/mcp/tests/app.test.ts | 204 +++++++++++++++++ 15 files changed, 1103 insertions(+), 80 deletions(-) create mode 100755 packages/mcp/bin/h5p-mcp-app.mjs create mode 100644 packages/mcp/lib/answers.mjs create mode 100644 packages/mcp/lib/app.mjs create mode 100644 packages/mcp/lib/card.html create mode 100644 packages/mcp/tests/app.test.ts diff --git a/AGENTS.md b/AGENTS.md index 5954d29c..d703dc37 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -51,7 +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, and a package back to one | [author](design/author.md) | -| `packages/mcp/` | the local MCP server: builds, reads, checks and previews in an app with no shell | [mcp](design/mcp.md) | +| `packages/mcp/` | the local MCP server: builds, reads, checks and previews in an app with no shell; and the app server, which plays an activity in a chat app's reply | [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/design/author.md b/design/author.md index 6a704bc6..e7be5f68 100644 --- a/design/author.md +++ b/design/author.md @@ -137,6 +137,12 @@ text to the content check's rules, and `apps/skills` plays every example untrust - `check` (`build --check`) runs a build's checks, `checkContent` being `composePackage`'s, and writes no package; a media file named by web address is still downloaded, to a temporary folder removed after, and a video on the four hosts stays an address. + - `unread`, with `check`, checks a source whose files are elsewhere (#270): the app server's + `h5p_play` gets a source and never the file a person attached in the chat, which only their + browser reads. No file is looked for, none downloaded and no site asked; a file named by a + path is judged by its name, which must be of a type its field takes, and listed in the + result's `unread`; one named by a web address is left as written. A picture then has no size + and a video no length, so what a build says of those is not said. - `publicFetch`, passed as `fetch`, refuses every network that is not the public internet on every hop, through `net.BlockList`, which matches an IPv4 address however IPv6 writes it (`[::ffff:7f00:1]` is loopback). The local IPv4 ranges are refused behind NAT64 and 6to4 too, diff --git a/design/mcp.md b/design/mcp.md index 8f6fafce..bdb9dffd 100644 --- a/design/mcp.md +++ b/design/mcp.md @@ -3,10 +3,12 @@ `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, or reads one back to change it. 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. +shell, Claude Desktop first; in an app with a shell, the skill and `npx` build already. The +package's second command, `h5p-mcp-app`, is the server for a chat app on the web: *The app server*, +below. -- **It holds no rules of its own.** The build, the read, their checks, the outline and the +- **It holds no rules of its own.** What both servers say alike, the content types, a source's + fields, a build's notes and outline, is `lib/answers.mjs`. The build, the read, their checks, the outline and the confinement to folders (`buildPackage`, `readPackage`, `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 @@ -75,3 +77,57 @@ server, for ChatGPT or Claude on the web, is #210 and not this. the skill's type files into the author package, as the author's `prepack` does. Not built yet: the MCP registry's `server.json` and Claude Desktop's one-click bundle. + +## The app server + +`h5p-mcp-app` (`lib/app.mjs`, #210, #270) is an MCP server over HTTP for a chat app that shows a +card in its reply, ChatGPT first: the person asks for an activity, the reply plays it, and its +`.h5p` is saved from there. `createApp()` is a web-standard handler, `fetch(request)`, so a host +that runs Node, or one that takes such a handler, serves it; the command is that handler on a +port. Its endpoint is `/mcp`. + +- **No server of ours processes a person's file** (the owner's rule, 2026-11-24, and a goal of the + whole toolkit). The chat sends the tool a reference to an attached file, an address and an id, + never its bytes. The server never asks that address: it hands the reference back to the card in + the result's `_meta`, which the model does not see, and only the person's browser asks it. What + the server cannot avoid is receiving the call, with the activity's source in it; it checks the + source and keeps nothing. Each request gets a fresh server and no session; nothing of a request + is stored and nothing is logged, not its body, not its address, not how it was answered, and no + error of the protocol's, which may quote what was sent. `app.test.ts` holds it to this: a file + store that counts is never asked, and all the command ever writes is where it listens. +- **Two tools, in the local server's words.** `h5p_types` answers from `answers.mjs` as the local + one does, without the lines on folders, which it has none of. `h5p_play` takes a source and + checks it with the author package's check that reads no file (`check` with `unread`), since a + source's files are in the chat's store: it answers with the problems by their paths, or with + the type, the files not checked, the notes and the outline, as `h5p_build` does, so a chat that + changed an activity reads back what it holds (#268). The instructions say to pass an attachment + as it is and not to open it: a reply that began with the chat's own analysis of the file drew + no card, twice, and without it the card came (ChatGPT, 2026-11-23 and 11-24; one cause is not + proven). +- **The file input is ChatGPT's, to the letter, and not held to.** `file` is named in + `openai/fileParams` and its schema is the reference's: `download_url` and `file_id` required, + `mime_type` and `file_name`, nothing else. It is shown and not enforced, as `source` is: a + model that writes the file's name there is answered that no attachment came, where a schema + would refuse the call unread. A reference is passed on only where its address is https. +- **The card is the play page's way to the chat, and holds nothing of the activity.** + `lib/card.html` frames `/h5p/play/` of the org site with the source in its fragment; the page + builds and plays in the person's browser, and its rules are that site's. The card gives it + what only the chat has, by the page's messages: the attached file's address (a new one by its + id, `getFileDownloadUrl`) and what it weighs, its bytes where the page needs them, the chat's + theme, a save (`ui/download-file`), and an open tab for a link of the site's and no other + (`openExternal`). It sends nothing to the server it came from and calls no tool. Its policy + names the one site it frames and the chat's file store. A chat keeps a card by its address, so + the address carries the card's hash. +- **What ChatGPT's frame was found to do is written in the card, with its date.** A card's frame + saves no file and opens no tab on a press; the chat saves a file handed to it of 8 MB and + refuses one of 16 MB, downloads from no address, and takes no package into its own files; its + file store answers any site (all 2026-11-24). So the card says it saves up to 8 MB, and a + bigger package is saved by a tab of the play page, which the page asks the card to open. The + card's script is one function: a chat puts names of its own on the card's window. +- **Tested as a host runs it.** `tests/app.test.ts` starts the command on a free port and asks it + over HTTP with the SDK's own client: the two tools and their words, the file input's schema, + the card and its policy, a source checked, one refused, an attachment handed to the card alone, + a call whose file is no reference, a body over 1 MB, and that nothing was written. The card in + a chat's frame is checked by hand, in ChatGPT and in a page that stands in for one. + +Not built yet: where the server is hosted, the app's privacy policy and its listing (#210). diff --git a/packages/author/README.md b/packages/author/README.md index 76cdbb25..1467226b 100644 --- a/packages/author/README.md +++ b/packages/author/README.md @@ -229,16 +229,19 @@ Set's 2.6 MB, a container's up to 8.4 MB. `--all ` writes one per conten ```js import { buildPackage, schemaOf, SourceError } from '@missing-elements/h5p-author' -const { output, source: built, builtWith, manifest, content, libraries, install, coreApi, translations, notes, media, outline } = +const { output, source: built, builtWith, manifest, content, libraries, install, coreApi, translations, notes, media, unread, outline } = await buildPackage(source, 'rivers.h5p', { base: process.cwd() }) ``` -`buildPackage(source, output, { libraries, base, fetch, within, check })` refuses an existing output, +`buildPackage(source, output, { libraries, base, fetch, within, check, unread })` refuses an existing output, and throws a `SourceError` whose `problems` are `{ path, message }`; with `check` it builds and writes no package and takes no output (`buildPackage(source, undefined, { check: true })`), though a media file named by web address is still downloaded, to a temporary folder removed after; a video on YouTube, Vimeo, Panopto or Echo360 stays an address, as in a build, a YouTube or Vimeo one asked -of the site with the same `fetch`. For a build run +of the site with the same `fetch`. With `unread` beside `check`, for a source whose files are +elsewhere, as an attachment in a chat is, no file is looked for, none downloaded and no site asked: +a file named by a path is judged by its name alone, and the result's `unread` lists those names. +For a build run on what a model wrote: `within` is a list of the folders the output and every local file the source names must be inside, on their real paths, and its problems then name no path but the one the source wrote. It does not cover a file named by web address, which is downloaded with the `fetch` diff --git a/packages/author/lib/media.mjs b/packages/author/lib/media.mjs index b068ebaa..fd3807b2 100644 --- a/packages/author/lib/media.mjs +++ b/packages/author/lib/media.mjs @@ -188,12 +188,15 @@ const IDLE_MS = 60_000 * local(source: string): Promise<{ file: F } | { missing: string }>, * keep(body: ReadableStream, extension: string): Promise, * open(file: F): Promise<{ size: number, read(offset: number, length: number): Promise, close(): Promise }>, - * linked?(source: string): string | undefined + * linked?(source: string): string | undefined, + * unread?: boolean * }} MediaAccess * `what`, what a source's path names, for problems; `name`, the file's own name it names; * `local`, that file, or why there is none; `keep`, a download's bytes kept; `open`, a kept * file's length, and its bytes read from an offset, fewer at its end; `linked`, the web address - * a file the source names stays at and is played from, where it has one (#263) + * a file the source names stays at and is played from, where it has one (#263); `unread`, for + * a check of a source whose files are elsewhere (#270): none is looked for, none downloaded and + * no host asked, and each is judged by its name alone */ /** @@ -319,6 +322,8 @@ export class MediaStore { this.unanswered = new Set() /** @type {string[]} the files left at an address and played from there, as the source names them (#263) */ this.linked = [] + /** @type {string[]} the files not looked at, as the source names them, where none is read (#270) */ + this.unread = [] } /** @@ -350,7 +355,7 @@ export class MediaStore { const address = short ? `https://www.youtube.com/watch?v=${short[1]}` : source const hosted = HOSTED.find(({ plays }) => plays.test(address)) if (hosted) { - await this.#there(hosted, address, source, `${at}.path`, report, note) + if (!this.access.unread) await this.#there(hosted, address, source, `${at}.path`, report, note) return { path: address, mime: hosted.mime, copyright } } const url = URL.canParse(address) ? new URL(address) : null @@ -365,6 +370,7 @@ export class MediaStore { return { path: source, copyright } } const types = /** @type {Record} */ (TYPES[kind]) + if (this.access.unread) return { ...this.#unread(source, web, types, at, report), copyright } const address = web ? undefined : this.access.linked?.(source) if (address !== undefined) return { ...this.#linked(kind, source, address, types, at, report), copyright } const key = `${kind} ${source}` @@ -493,6 +499,30 @@ export class MediaStore { return { from: found.file, extension, stem: name.slice(0, name.length - extension.length - 1) } } + /** + * A file that is not looked at (#270): a check of a source whose files are elsewhere, as an + * attachment in a chat is, which only the person's browser reads. One named by a path is judged + * by its name, which must be of a type the field takes, and listed in `unread`; one named by a + * web address is left as written, since its type is what its host says it is. Nothing of + * either is read, so a picture has no size and a video no length. + * @param {string} source + * @param {boolean} web + * @param {Record} types + * @param {string} at + * @param {(path: string, message: string) => void} report + * @returns {{ path: string, mime?: string }} + */ + #unread(source, web, types, at, report) { + if (web) return { path: source } + const extension = extensionOf(this.access.name(source)) + if (!Object.hasOwn(types, extension)) { + report(`${at}.path`, `${source}: this field takes ${Object.keys(types).map((each) => `.${each}`).join(', ')}`) + return { path: source } + } + if (!this.unread.includes(source)) this.unread.push(source) + return { path: source, mime: types[extension] } + } + /** * A file left at a web address of its own and played from there (#263), as a video on YouTube * is: a video or a recording only, since a picture's size is read from its bytes, its type taken diff --git a/packages/author/lib/node.mjs b/packages/author/lib/node.mjs index 0587ebc6..98a4b3da 100644 --- a/packages/author/lib/node.mjs +++ b/packages/author/lib/node.mjs @@ -27,14 +27,15 @@ import { SourceError } from './source-error.mjs' * @typedef {import('./translate.mjs').TranslationReport} TranslationReport * @typedef {{ * output: string, source: import('./build.mjs').Source, builtWith: string, manifest: Record, content: Record, - * libraries: string[], install: string[], coreApi: import('./install.mjs').CoreApi, translations: TranslationReport[], notes: Problem[], media: string[], outline: string + * libraries: string[], install: string[], coreApi: import('./install.mjs').CoreApi, translations: TranslationReport[], notes: Problem[], media: string[], unread: string[], outline: string * }} BuildResult what was written, and what is worth telling about it: `libraries`, the folders the * package plays with; `install`, those carried for an H5P site's upload check; `coreApi`, the * newest H5P core they ask for, which a site needs to take the package (`coreApiLine` says it); * `outline`, the content as text for a review (`outlineOf`); `builtWith`, the content type and * the pack's version of it, "H5P.Blanks 1.14", and `source`, the source as built, naming it: what - * to keep with the package, so that a build with a later pack can say the type has moved - * @typedef {{ libraries?: string, base?: string, fetch?: typeof fetch, within?: string[], check?: boolean }} BuildOptions + * to keep with the package, so that a build with a later pack can say the type has moved; + * `unread`, the files a check with `unread` did not look at, as the source names them + * @typedef {{ libraries?: string, base?: string, fetch?: typeof fetch, within?: string[], check?: boolean, unread?: boolean }} BuildOptions * `libraries`, a library pack's parts folder in place of the pinned pack; `base`, the folder a * source's file paths are read from; `fetch`, for media named by web address; `within`, the * folders the output and every local file a source names must be inside, on their real paths, a @@ -42,7 +43,10 @@ import { SourceError } from './source-error.mjs' * the result's `output` is empty, but a media file named by web address is still downloaded, to a * temporary folder removed after, as the build checks it; a video on YouTube, Vimeo, Panopto or * Echo360 stays an address, as in a build, a YouTube or Vimeo one asked of the site's oEmbed with - * `fetch` as a build asks it + * `fetch` as a build asks it; `unread`, with `check`, for a source whose files are elsewhere, as + * an attachment in a chat is (#270): no file is looked for, none downloaded and no site asked, + * one named by a path is judged by its name alone and listed in the result's `unread`, and + * `base`, `within` and `fetch` are not used * @typedef {{ output: string, source: import('./build.mjs').Source, files: string[], notes: Problem[] }} ReadResult * `output`, the source's path; `files`, the media written beside it, by the paths the source * names them by, from its folder; `notes`, what was left out or could not be read back as it is @@ -369,8 +373,9 @@ function foldersOf(within) { * @returns {Promise} */ export async function buildPackage(input, output, options = {}) { - const { check = false } = options + const { check = false, unread = false } = options const within = foldersOf(options.within) + if (unread && !check) throw new TypeError('unread goes with a check (check: true): a package needs its files') if (!check && (typeof output !== 'string' || !output.trim())) throw new TypeError('a build takes the path to write its package to, and a check (check: true) none') // A check writes nothing, so where a package would go is not looked at. const target = check ? '' : resolve(/** @type {string} */ (output)) @@ -388,7 +393,8 @@ export async function buildPackage(input, output, options = {}) { const read = sourceOf(input, typeNames(pack)) if (!read.typed) throw new SourceError(read.problems) temporary = await mkdtemp(join(check ? tmpdir() : dirname(target), '.h5p-author-')) - const media = new MediaStore(nodeMedia({ base: options.base ?? process.cwd(), temporary, within }), { fetch: options.fetch }) + const access = nodeMedia({ base: options.base ?? process.cwd(), temporary, within }) + const media = new MediaStore(unread ? { ...access, unread } : access, { fetch: options.fetch }) const built = await composePackage(read.source, pack, media, read.problems) if (check) { return { @@ -403,6 +409,7 @@ export async function buildPackage(input, output, options = {}) { translations: built.translations, notes: built.notes, media: media.files.map((item) => item.name), + unread: [...media.unread], get outline() { return built.outline } } } @@ -443,6 +450,7 @@ export async function buildPackage(input, output, options = {}) { translations: built.translations, notes: built.notes, media: media.files.map((item) => item.name), + unread: [], get outline() { return built.outline } } } finally { diff --git a/packages/author/tests/confine.test.ts b/packages/author/tests/confine.test.ts index db78e132..a3098fd3 100644 --- a/packages/author/tests/confine.test.ts +++ b/packages/author/tests/confine.test.ts @@ -400,3 +400,62 @@ describe('outline', () => { } }) }) + +describe('a check that reads no file (#270)', () => { + const video = (path: string, more: Record = {}) => ({ + ...META, + type: 'H5P.InteractiveVideo', + params: { interactiveVideo: { + video: { files: [{ path }] }, + assets: { interactions: [{ duration: { from: 2.5, to: 66 }, label: 'Where does it go?', action: { library: 'H5P.Text', params: { text: 'To the sea.' } } }] }, + ...more + } } + }) + /** A `fetch` that counts what it is asked, and answers nothing. */ + const counting = () => { + const asked: string[] = [] + const fetch = (async (input: RequestInfo | URL) => { asked.push(String(input)); throw new Error('asked') }) as typeof globalThis.fetch + return { asked, fetch } + } + + it('checks a source whose files are elsewhere, and names them', async () => { + const { asked, fetch } = counting() + // No such file anywhere, and a folder that would refuse it: neither is looked at. + const result = await buildPackage(video('holiday.mp4'), undefined, { check: true, unread: true, base: outside, within: [allowed], fetch }) + expect(result.unread).toEqual(['holiday.mp4']) + expect(result.media).toEqual([]) + expect(result.outline).toBe('Video: holiday.mp4\n 0:02.5–1:06 Label: Where does it go?\n To the sea.') + expect(asked).toEqual([]) + }) + + it('names a file once, a picture among them, and asks no address', async () => { + const { asked, fetch } = counting() + const result = await buildPackage({ + ...META, + type: 'H5P.Column', + params: { content: [ + { content: { library: 'H5P.Image', params: { file: { path: 'site.png' }, alt: 'The site' } } }, + { content: { library: 'H5P.Image', params: { file: { path: 'site.png' }, alt: 'The site again' } } }, + { content: { library: 'H5P.Image', params: { file: { path: 'https://example.com/river.png' }, alt: 'A river' } } }, + { content: { library: 'H5P.Video', params: { sources: [{ path: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ' }] } } } + ] } + }, undefined, { check: true, unread: true, fetch }) + expect(result.unread).toEqual(['site.png']) + expect(asked).toEqual([]) + }) + + it('refuses a file by its name where the field takes no such type, and the rest of the source as any check does', async () => { + const wrong = await buildPackage(video('notes.txt'), undefined, { check: true, unread: true }).catch((error) => error) + expect(wrong).toBeInstanceOf(SourceError) + expect(wrong.problems).toEqual([{ path: 'params.interactiveVideo.video.files[0].path', message: 'notes.txt: this field takes .mp4, .webm, .ogg' }]) + const untitled = await buildPackage({ ...video('holiday.mp4'), title: undefined }, undefined, { check: true, unread: true }).catch((error) => error) + expect(untitled.problems.map(({ path }: { path: string }) => path)).toEqual(['title']) + }) + + it('goes with a check only, and a check without it still reads its files', async () => { + await expect(buildPackage(video('holiday.mp4'), join(allowed, 'unread.h5p'), { unread: true })).rejects.toThrow(/unread goes with a check/) + const read = await buildPackage(video('clip.mp4'), undefined, { check: true, base: allowed }) + expect(read.unread).toEqual([]) + expect(read.media).toEqual(['videos/clip.mp4']) + }) +}) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 95557185..3ebc37e1 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -7,7 +7,8 @@ that it plays in a real H5P player, and opens it in your browser. It reads a `.h into its source too, to change it and build it again. 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 +and it sends nothing to a server of ours. For a chat app on the web there is a second command, +[the app server](#the-app-server-for-a-chat-app-on-the-web). 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 @@ -63,6 +64,32 @@ video. Math is drawn by the package's own copy of MathJax, which loads nothing f 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. +## The app server, for a chat app on the web + +The package has a second command, `h5p-mcp-app`: an MCP server over HTTP for a chat app that shows +a card in its reply, ChatGPT first. The person asks for an activity, the reply plays it, and its +`.h5p` is saved from there. It is not a service we run yet: run it yourself to try it. + +```sh +npx -y -p @missing-elements/h5p-mcp h5p-mcp-app --port 8787 +``` + +Its endpoint is `/mcp`, with no sign-in. It has two tools: `h5p_types`, as above, and `h5p_play`, +which checks an activity's source and shows the card. The card frames the play page of +[missing-elements.github.io](https://missing-elements.github.io/h5p/), which builds the activity in +the person's browser and plays it there. + +What the server receives, and what it keeps: + +- It receives each tool call, with the activity's source in it, and checks the source. +- It never receives a file. For a file attached in the chat, the chat sends a reference, an + address and an id; the server does not ask that address, and hands the reference to the card, + where the person's browser fetches the file from the chat's own store. +- It stores nothing and logs nothing of a request. Whoever hosts it may log requests on their own + side: that is the host's to say. +- A package up to about 8 MB is saved through the chat. A bigger one, with a video in it, is saved + by a tab of the play page, which fetches the video from the chat and builds the package again. + ## Licence MIT. The H5P libraries a package carries are under their own licences, listed in it. diff --git a/packages/mcp/bin/h5p-mcp-app.mjs b/packages/mcp/bin/h5p-mcp-app.mjs new file mode 100755 index 00000000..d39df49b --- /dev/null +++ b/packages/mcp/bin/h5p-mcp-app.mjs @@ -0,0 +1,91 @@ +#!/usr/bin/env node +import { createServer } from 'node:http' +import { readFile } from 'node:fs/promises' +import { Readable } from 'node:stream' +import { parseArgs } from 'node:util' + +const HELP = `Usage: h5p-mcp-app [--port ] [--host
] [--site ] + +The app server of H5P Author MCP by Missing Elements: an MCP server over HTTP for a chat app +that shows a card in its reply. Its endpoint is /mcp. It checks an activity's source and the +card builds and plays the activity in the person's browser. It stores nothing, logs nothing +of a request, and never asks for a file a person attached in the chat. + +Options: + --port the port to listen on; 8787 by default, or PORT from the environment + --host
the address to listen on; 127.0.0.1 by default, 0.0.0.0 for every interface + --site the site whose play page the card frames; + https://missing-elements.github.io by default + --version + -h, --help +` + +let values +try { + ;({ values } = parseArgs({ + options: { + port: { type: 'string' }, + host: { type: 'string' }, + site: { type: 'string' }, + version: { type: 'boolean' }, + help: { type: 'boolean', short: 'h' } + } + })) +} catch (error) { + console.error(`h5p-mcp-app: ${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) +} +const port = Number(values.port ?? process.env.PORT ?? 8787) +if (!Number.isInteger(port) || port < 0 || port > 65535) { + console.error(`h5p-mcp-app: ${values.port ?? process.env.PORT} is not a port`) + process.exit(2) +} +if (values.site !== undefined && !URL.canParse(values.site)) { + console.error(`h5p-mcp-app: ${values.site} is not an origin, as https://example.org`) + process.exit(2) +} +const host = values.host ?? '127.0.0.1' + +// Loaded only now, so that --help and --version answer without loading the pack. +const { createApp } = await import('../lib/app.mjs') +const app = await createApp({ site: values.site }) + +// One HTTP request, as the web's Request and Response, to the app and back. Nothing of it is +// written anywhere: not its address, not its body, not how it was answered. +const listening = createServer(async (req, res) => { + try { + const body = req.method === 'GET' || req.method === 'HEAD' ? undefined : /** @type {ReadableStream} */ (Readable.toWeb(req)) + const headers = new Headers() + for (const [name, value] of Object.entries(req.headers)) if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(', ') : value) + const request = new Request(new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`), { method: req.method, headers, body, duplex: 'half' }) + const response = await app.fetch(request) + res.writeHead(response.status, Object.fromEntries(response.headers)) + if (!response.body) return void res.end() + // A stream that is given up on, by either end, ends the other. + res.on('close', () => { void response.body?.cancel().catch(() => {}) }) + for await (const chunk of response.body) res.write(chunk) + res.end() + } catch { + if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }) + res.end(res.writableEnded ? undefined : 'The request could not be answered\n') + } +}) +listening.listen(port, host, () => { + const at = /** @type {import('node:net').AddressInfo} */ (listening.address()) + console.log(`h5p-mcp-app ${app.version} on http://${at.address.includes(':') ? `[${at.address}]` : at.address}:${at.port}/mcp, framing ${values.site ?? 'https://missing-elements.github.io'}`) +}) +const stop = () => { + listening.close() + void app.close().finally(() => process.exit(0)) +} +process.on('SIGINT', stop) +process.on('SIGTERM', stop) diff --git a/packages/mcp/lib/answers.mjs b/packages/mcp/lib/answers.mjs new file mode 100644 index 00000000..232cf7d8 --- /dev/null +++ b/packages/mcp/lib/answers.mjs @@ -0,0 +1,101 @@ +import { readdir, readFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { z } from 'zod' +import { contentTypes, openPack, schemaOf, sourceSchema, sourceType } from '@missing-elements/h5p-author' + +/** + * What both servers of this package say alike: the local one over standard input and output + * (`server.mjs`) and the app server over HTTP (`app.mjs`). The content types and a type's file, + * a source's own fields, and a build's notes and outline. None of it is a rule of this package's: + * each is the author package's, put into an answer. + */ + +export 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 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. + */ +export const SOURCE_PROPERTIES = z.toJSONSchema(sourceSchema, { io: 'input' }).properties + +/** Lines of an outline past which an answer says how many more there are. */ +const OUTLINE_LINES = 80 + +/** @param {string} text */ +export const answer = (text) => ({ content: [{ type: /** @type {const} */ ('text'), text }] }) +/** @param {string} text */ +export const refusal = (text) => ({ content: [{ type: /** @type {const} */ ('text'), text }], isError: true }) + +/** + * A build's notes, and what its content holds, as lines of an answer: the outline, 80 lines of it + * at most. + * @param {{ notes: { path: string, message: string }[], outline: string }} result + */ +export function heldLines(result) { + const lines = result.notes.map(({ path, message }) => `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.`) + return lines +} + +/** + * What `h5p_types` answers, for a server: the list with the skill's brief, and a type's file, or + * its fields where it has none. + * @param {{ libraries?: string }} [options] `libraries`, the pack's `parts/` folder; the installed pack by default + */ +export function typeAnswers(options = {}) { + const author = dirname(fileURLToPath(import.meta.resolve('@missing-elements/h5p-author/package.json'))) + const typeFiles = join(author, 'references', 'types') + /** @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() + } + })() + // A pack that could not be opened is opened again at the next question. + typeList.catch(() => { typeList = undefined }) + 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))) + } + return { + /** + * The list, and how to write good content, with a server's own lines between them. + * @param {string[]} [between] + */ + async list(between = []) { + const [list, files] = await Promise.all([types(), filed()]) + const lines = list.map(({ name, title }) => `${files.has(name) ? '*' : '-'} ${name}: ${title}`) + const brief = await readFile(join(author, 'references', 'authoring.md'), 'utf8').catch(() => '') + return [LIST_HEAD, ...lines, ...(between.length ? ['', ...between] : []), ...(brief ? ['', brief] : [])].join('\n') + }, + /** + * A type's file, or its fields; `null` for a type the pack has not. Read as a build reads one, + * so "true false" works. + * @param {string} type + */ + async about(type) { + const [list, files] = await Promise.all([types(), filed()]) + const name = sourceType({ type }, list.map((each) => each.name)) + if (!name) return null + const text = files.has(name) ? await readFile(join(typeFiles, `${name}.md`), 'utf8') : await schemaOf(name, { markdown: true, libraries: options.libraries }) + return text.trimEnd() + } + } +} diff --git a/packages/mcp/lib/app.mjs b/packages/mcp/lib/app.mjs new file mode 100644 index 00000000..ee72e165 --- /dev/null +++ b/packages/mcp/lib/app.mjs @@ -0,0 +1,173 @@ +import { createHash } from 'node:crypto' +import { readFile } from 'node:fs/promises' +import { McpServer, createMcpHandler } from '@modelcontextprotocol/server' +import { z } from 'zod' +import { SourceError, buildPackage } from '@missing-elements/h5p-author' +import { SOURCE_PROPERTIES, TYPES, answer, heldLines, refusal, typeAnswers } from './answers.mjs' + +/** + * The app server (#210, #270): an MCP server over HTTP for a chat app that shows a card in its + * reply, ChatGPT first. Two tools and one card. `h5p_play` checks a source and answers as a build + * does; the card frames the play page of the site, which builds the activity in the person's + * browser and plays it there. + * + * It keeps nothing. Each request gets a fresh server, answers, and is gone; nothing of a request + * is stored and nothing of it is logged. A file the person attached in the chat never comes here: + * the chat sends its reference (an address and an id), which is handed back to the card in the + * part of the answer the model does not see, and only the person's browser asks that address. + * + * @typedef {object} AppOptions + * @property {string} [site] the origin of the site whose play page the card frames; `https://missing-elements.github.io` by default + * @property {string} [libraries] the pack's `parts/` folder to check with; the installed pack by default + */ + +const SITE = 'https://missing-elements.github.io' + +/** A source is text: a body past this is refused before it is read whole. */ +const MOST = 1024 * 1024 + +const INSTRUCTIONS = `Makes an H5P activity and plays it in the chat, built in the person's browser. Nothing is stored. +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_play with the source. Where it lists problems, fix each at its path and call it again. +A file the person attached (a video, a recording, a picture): name it in the source by its file name, and pass the attachment in file. Do not open, read or analyse it yourself, with code or otherwise: pass it as it is, since nothing here needs what is in it. +The author and the licence are what the person gave; otherwise the name you know them by, or "Unknown", and the licence "U". +The card has the download of the .h5p file: do not offer a link of your own.` + +const PLAY = `Checks an H5P activity's source and plays the activity in the chat, built in the person's browser, with a download of the .h5p file. The source is as h5p_types describes it for its type, its params holding only what differs from the type's defaults. A source with problems is refused, each problem named by its path. Nothing is stored.` + +/** + * A file attached in the chat, as ChatGPT's reference writes a file input, to the letter: it puts + * the attachment's address and id here for an input named in `openai/fileParams`. Shown to the + * app as the field's schema and not held to: what comes in its place, a name where a model wrote + * one, is answered, where a schema would refuse the call unread. + */ +const FILE = { + type: 'object', + description: 'The file attached in the chat that the source names (a video, a recording or a picture): give the attachment itself, by its file id. Leave it out where there is none.', + properties: { download_url: { type: 'string' }, file_id: { type: 'string' }, mime_type: { type: 'string' }, file_name: { type: 'string' } }, + required: ['download_url', 'file_id'], + additionalProperties: false +} + +/** Where a chat keeps attached files, which the card asks from the person's browser: ChatGPT's, as seen in November 2026. */ +const FILE_HOSTS = ['https://*.blob.core.windows.net', 'https://files.oaiusercontent.com', 'https://*.oaiusercontent.com'] + +/** + * The chat's reference to an attached file, as far as it is one: an http(s) address, and what + * came with it. Text in its place is none. + * @param {unknown} file + */ +function attached(file) { + if (!file || typeof file !== 'object') return null + const { download_url: address, file_id: id, mime_type: type, file_name: name } = /** @type {Record} */ (file) + if (typeof address !== 'string' || !/^https:\/\//i.test(address) || !URL.canParse(address)) return null + const text = (/** @type {unknown} */ value) => (typeof value === 'string' && value.length <= 512 ? value : undefined) + return { download_url: address, file_id: text(id), mime_type: text(type), file_name: text(name) } +} + +/** + * The app server, as a web-standard handler: `fetch(request)` answers one HTTP request. The MCP + * endpoint is `/mcp`; every other path is a 404. + * @param {AppOptions} [options] + */ +export async function createApp(options = {}) { + const site = new URL(options.site ?? SITE).origin + const { version } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')) + const card = (await readFile(new URL('./card.html', import.meta.url), 'utf8')).replaceAll('__SITE__', site) + // A chat keeps a card by its address, so a card that changed has another. + const cardUri = `ui://h5p-play/card-${createHash('sha256').update(card).digest('hex').slice(0, 12)}.html` + const about = typeAnswers({ libraries: options.libraries }) + // The card's policy: the one site it frames, and the chat's file store, which it asks for the + // attached file. Written twice, as the MCP Apps specification places it and as ChatGPT reads it. + const cardMeta = { + ui: { csp: { frameDomains: [site], connectDomains: FILE_HOSTS, resourceDomains: FILE_HOSTS }, prefersBorder: true }, + 'openai/widgetCSP': { frame_domains: [site], connect_domains: FILE_HOSTS, resource_domains: FILE_HOSTS, redirect_domains: [site] }, + 'openai/widgetDescription': 'Plays the H5P activity, built in the person\'s browser, with its download.' + } + + function server() { + const mcp = new McpServer({ name: 'h5p-mcp-app', title: 'H5P Author MCP by Missing Elements', version }, { instructions: INSTRUCTIONS }) + + mcp.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 }) => { + if (!type) return answer(await about.list()) + const text = await about.about(type) + return text === null ? refusal(`The library pack has no content type "${type}". h5p_types with no type lists them.`) : answer(text) + }) + + mcp.registerTool('h5p_play', { + title: 'Play an H5P activity', + description: PLAY, + 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' }), + file: z.unknown().optional().meta(FILE) + }), + annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, + _meta: { + ui: { resourceUri: cardUri }, + 'openai/outputTemplate': cardUri, + 'openai/fileParams': ['file'], + 'openai/toolInvocation/invoking': 'Preparing the activity…', + 'openai/toolInvocation/invoked': 'Ready to play' + } + }, async ({ source, file }) => { + let result + try { + // The author package's check of the source alone: no file is looked for and none + // downloaded, here or anywhere, so a problem names nothing of this computer. + result = await buildPackage(source, undefined, { check: true, unread: true, libraries: options.libraries }) + } catch (error) { + if (error instanceof SourceError) return refusal(`${error.message}\nFix each at its path and call h5p_play again.`) + // Not a problem of the source's, and its words may be of this computer: none are passed on. + return refusal('The check could not be run, through no fault of the source. Call h5p_play again in a moment.') + } + const given = attached(file) + const files = result.unread + const lines = [`The activity is checked and plays in the card: ${result.manifest.mainLibrary}, ${result.libraries.length} libraries. It is built in the person's browser; nothing was stored.`] + if (files.length) { + lines.push(given + ? `Its file${files.length === 1 ? '' : 's'}, ${files.join(', ')}, ${files.length === 1 ? 'is' : 'are'} not checked here: the card gets the attachment in the person's browser${files.length === 1 ? '' : ', and asks the person for any other'}.` + : `Its file${files.length === 1 ? '' : 's'}, ${files.join(', ')}, ${files.length === 1 ? 'is' : 'are'} not checked here, and no attachment came with the call: the card asks the person to choose ${files.length === 1 ? 'it' : 'them'}. Where the person attached ${files.length === 1 ? 'it' : 'one'} in the chat, call h5p_play again with the attachment in file.`) + } else if (given) { + lines.push('An attachment came with the call, and the source names no file, so it is not used: name it in the source, as the type\'s notes say, to use it.') + } + lines.push(...heldLines(result)) + return { + ...answer(lines.join('\n')), + structuredContent: { files: files.length, ...(given?.file_id ? { fileId: given.file_id } : {}), ...(given?.file_name ? { fileName: given.file_name } : {}) }, + // To the card alone, which the model does not see: the attachment's address is a key to the file. + ...(given ? { _meta: { 'h5p/file': given } } : {}) + } + }) + + mcp.registerResource('h5p-play-card', cardUri, { title: 'H5P activity', mimeType: 'text/html;profile=mcp-app', _meta: cardMeta }, + async (uri) => ({ contents: [{ uri: uri.href, mimeType: 'text/html;profile=mcp-app', text: card, _meta: cardMeta }] })) + return mcp + } + + // Nothing is said of an error either: a message of the protocol's may quote what was sent. + const handler = createMcpHandler(() => server(), { maxRequestBodySize: MOST }) + return { + version, + cardUri, + /** + * @param {Request} request + * @returns {Promise} + */ + async fetch(request) { + const { pathname } = new URL(request.url) + // For whoever opens the address, and for a host that asks whether the server is up. + if (pathname === '/' && (request.method === 'GET' || request.method === 'HEAD')) return new Response('H5P Author MCP by Missing Elements: the MCP endpoint is /mcp\n', { headers: { 'content-type': 'text/plain; charset=utf-8' } }) + if (pathname !== '/mcp') return new Response('Not found\n', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } }) + // Said before a body is read, where its length is given; the handler holds one that gives none to the same bound. + if (Number(request.headers.get('content-length')) > MOST) return new Response('A request takes 1 MB at most\n', { status: 413, headers: { 'content-type': 'text/plain; charset=utf-8' } }) + return handler.fetch(request) + }, + close: () => handler.close() + } +} diff --git a/packages/mcp/lib/card.html b/packages/mcp/lib/card.html new file mode 100644 index 00000000..ecc5cc63 --- /dev/null +++ b/packages/mcp/lib/card.html @@ -0,0 +1,317 @@ + + + + + +H5P activity + + + +
+

Opening the activity…

It is built in your browser.
+ +
+ + + + diff --git a/packages/mcp/lib/server.mjs b/packages/mcp/lib/server.mjs index 0295dd9d..36f0e7ed 100644 --- a/packages/mcp/lib/server.mjs +++ b/packages/mcp/lib/server.mjs @@ -1,11 +1,11 @@ -import { lstat, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises' +import { lstat, mkdtemp, 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, coreApiLine, inside, openPack, publicFetch, readPackage, schemaOf, sourceSchema, sourceType } from '@missing-elements/h5p-author' +import { SourceError, buildPackage, coreApiLine, inside, publicFetch, readPackage } from '@missing-elements/h5p-author' import { VerifyError, openBrowser, previewPackage, summarize, verifyPackage } from '@missing-elements/h5p-verify' +import { SOURCE_PROPERTIES, TYPES, answer, heldLines, refusal, typeAnswers } from './answers.mjs' import { defaultFolders, fileStem, rootFolders } from './folders.mjs' /** @@ -28,28 +28,10 @@ To change a .h5p the person has, h5p_read it, change its source as asked, and h5 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.` -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`) @@ -61,9 +43,6 @@ 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') @@ -92,8 +71,7 @@ function located(value, folder) { 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') + const about = typeAnswers({ libraries: options.libraries }) /** @type {Set<{ close: () => void }>} */ const previews = new Set() @@ -111,27 +89,6 @@ export async function createServer(options = {}) { 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() @@ -176,20 +133,13 @@ export async function createServer(options = {}) { 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}`) + if (!type) return answer(await about.list([where])) + const text = await about.about(type) + if (text === null) return refusal(`The library pack has no content type "${type}". h5p_types with no type lists them.`) + return answer(`${text}\n\n${where}`) }) server.registerTool('h5p_build', { @@ -235,10 +185,7 @@ export async function createServer(options = {}) { ? `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.`) + lines.push(...heldLines(result)) /** @type {{ type: 'image', data: string, mimeType: string }[]} */ const images = [] if (verify) { diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 0198e6eb..cd0f6253 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -17,7 +17,8 @@ }, "type": "module", "bin": { - "h5p-mcp": "./bin/h5p-mcp.mjs" + "h5p-mcp": "./bin/h5p-mcp.mjs", + "h5p-mcp-app": "./bin/h5p-mcp-app.mjs" }, "exports": { "./package.json": "./package.json" diff --git a/packages/mcp/tests/app.test.ts b/packages/mcp/tests/app.test.ts new file mode 100644 index 00000000..c8c3b3cc --- /dev/null +++ b/packages/mcp/tests/app.test.ts @@ -0,0 +1,204 @@ +import { spawn, type ChildProcess } from 'node:child_process' +import { createServer, type Server } from 'node:http' +import type { AddressInfo } from 'node:net' +import { resolve } from 'node:path' +import { Client } from '@modelcontextprotocol/client' +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/client' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { createApp } from '../lib/app.mjs' + +/** + * The app server as a host runs it: the command the package ships, listening on a port, asked + * over HTTP through the SDK's own client, as a chat app asks it. The check's rules are the author + * package's and tested there; these hold the server to its two tools, its card, and to what it + * may hold of a request: nothing. + */ + +const COMMAND = resolve(import.meta.dirname, '../bin/h5p-mcp-app.mjs') +const META = { language: 'en', license: 'U', authors: [{ name: 'Unknown', role: 'Author' }] } +const QUIZ = { ...META, type: 'H5P.TrueFalse', title: 'Boiling point', params: { question: '

Water boils at 100 °C at sea level.

', correct: 'true' } } +const VIDEO = { + ...META, + type: 'H5P.InteractiveVideo', + title: 'Site walkthrough', + params: { interactiveVideo: { + video: { files: [{ path: 'IMG_0042.mp4' }] }, + assets: { interactions: [{ duration: { from: 1, to: 3 }, pause: true, label: 'Check', action: { library: 'H5P.TrueFalse', params: { question: 'It is a river.', correct: 'true' } } }] } + } } +} + +type Content = { type: string, text?: string } +type Answer = { content: Content[], isError?: boolean, structuredContent?: Record, _meta?: Record } + +let command: ChildProcess +/** All the command wrote, to either stream. */ +let written = '' +let address: string +let client: Client +/** A store of a chat's files, which the server must never ask: it counts what it is asked. */ +let store: Server +let asked = 0 +let fileAddress: string + +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') + +beforeAll(async () => { + store = createServer((_request, response) => { asked++; response.end('never') }).listen(0, '127.0.0.1') + await new Promise((done) => store.once('listening', done)) + // An address as a chat gives one: https, with a key in it. Nothing listens there for https, and nothing should ask. + fileAddress = `https://127.0.0.1:${(store.address() as AddressInfo).port}/files/abc?sig=KEY-TO-THE-FILE` + command = spawn(process.execPath, [COMMAND, '--port', '0'], { stdio: ['ignore', 'pipe', 'pipe'] }) + address = await new Promise((found, failed) => { + const read = (chunk: Buffer) => { + written += chunk.toString() + const at = /on (http:\/\/\S+\/mcp)/.exec(written) + if (at) found(at[1]!) + } + command.stdout!.on('data', read) + command.stderr!.on('data', read) + command.once('exit', (code) => failed(new Error(`the command ended with ${code}: ${written}`))) + }) + client = new Client({ name: 'h5p-mcp-app-test', version: '0' }) + await client.connect(new StreamableHTTPClientTransport(new URL(address))) +}) + +afterAll(async () => { + await client?.close() + command?.kill() + await new Promise((done) => store.close(done)) +}) + +describe('the app server', () => { + it('offers two tools and the flow, in few words', async () => { + const { tools } = await client.listTools() + expect(tools.map((tool) => tool.name).sort()).toEqual(['h5p_play', 'h5p_types']) + expect(client.getInstructions()).toMatch(/h5p_types[\s\S]*h5p_play/) + // A chat sends these with every message. + const words = (client.getInstructions() ?? '') + tools.map((tool) => `${tool.description}${JSON.stringify(tool.inputSchema)}`).join('') + expect(words.length).toBeLessThan(6000) + // Nothing of the local server's, which reads and writes a person's folders. + expect(words).not.toMatch(/folder|h5p_build|h5p_read|h5p_preview/) + const play = tools.find((tool) => tool.name === 'h5p_play')! + // A source's own fields as the author package declares them, with nothing required of it (#230, #174). + const source = play.inputSchema.properties?.source as Record + expect(source.properties).toMatchObject({ license: { enum: expect.arrayContaining(['U', 'CC BY']) }, authors: { items: { required: ['name', 'role'] } } }) + expect(source.required).toBeUndefined() + // The file input as ChatGPT's reference writes one, to the letter, and named as one. + expect(play.inputSchema.properties?.file).toEqual({ + type: 'object', + description: expect.stringContaining('attached in the chat'), + properties: { download_url: { type: 'string' }, file_id: { type: 'string' }, mime_type: { type: 'string' }, file_name: { type: 'string' } }, + required: ['download_url', 'file_id'], + additionalProperties: false + }) + expect(play.inputSchema.required).toEqual(['source']) + expect(play._meta).toMatchObject({ 'openai/fileParams': ['file'], 'openai/outputTemplate': expect.stringMatching(/^ui:\/\/h5p-play\/card-[0-9a-f]{12}\.html$/) }) + expect((play._meta as any).ui.resourceUri).toBe(play._meta!['openai/outputTemplate']) + // Neither tool keeps or changes anything. + for (const tool of tools) expect(tool.annotations).toMatchObject({ readOnlyHint: true, openWorldHint: false }) + }) + + it('serves one card, which frames the site and nothing else, and calls no tool', async () => { + const { tools } = await client.listTools() + const uri = tools.find((tool) => tool.name === 'h5p_play')!._meta!['openai/outputTemplate'] as string + const { contents } = await client.readResource({ uri }) + const card = contents[0] as { mimeType: string, text: string, _meta: Record } + expect(card.mimeType).toBe('text/html;profile=mcp-app') + expect(card.text).toContain("const SITE = 'https://missing-elements.github.io'") + expect(card.text).not.toContain('__SITE__') + expect(card._meta.ui.csp.frameDomains).toEqual(['https://missing-elements.github.io']) + expect(card._meta['openai/widgetCSP']).toMatchObject({ frame_domains: ['https://missing-elements.github.io'], redirect_domains: ['https://missing-elements.github.io'] }) + // It asks the chat's file store, and no address of ours. + expect(card._meta.ui.csp.connectDomains).toEqual(card._meta['openai/widgetCSP'].connect_domains) + expect(card._meta.ui.csp.connectDomains.join(' ')).not.toMatch(/missing-elements|localhost|127\.0\.0\.1/) + // It sends nothing back to this server: no tool is called from it, and nothing is reported. + expect(card.text).not.toMatch(/callTool|h5p_card_log|Test report|console\./) + // A card that changed has another address, which a chat keeps it by; the same card, the same. + const other = await createApp({ site: 'https://example.org' }) + const same = await createApp() + expect(other.cardUri).not.toBe(uri) + expect(same.cardUri).toBe(uri) + }) + + it('lists the content types and answers for one, with no word of folders', async () => { + const list = textOf(await call('h5p_types')) + expect(list).toMatch(/^\* H5P\.MultiChoice: /m) + expect(list).not.toMatch(/This server reads files|--allow/) + const one = await call('h5p_types', { type: 'true false' }) + expect(textOf(one)).toMatch(/^# .*\(H5P\.TrueFalse\)/) + expect(textOf(one)).not.toMatch(/This server reads files/) + const none = await call('h5p_types', { type: 'no such type' }) + expect(none.isError).toBe(true) + }) + + it('checks a source and says what it holds, as a build does', async () => { + const played = await call('h5p_play', { source: QUIZ }) + expect(played.isError).toBeFalsy() + expect(textOf(played)).toMatch(/^The activity is checked and plays in the card: H5P\.TrueFalse, \d+ libraries\./) + expect(textOf(played)).toContain('What it holds:\nWater boils at 100 °C at sea level.\nCorrect answer: True') + expect(played.structuredContent).toEqual({ files: 0 }) + expect(played._meta?.['h5p/file']).toBeUndefined() + }) + + it('refuses a source with problems, each by its path', async () => { + const refused = await call('h5p_play', { source: { ...QUIZ, params: { question: 'Q?', correct: 'maybe' } } }) + expect(refused.isError).toBe(true) + expect(textOf(refused)).toMatch(/params\.correct: "maybe" is not an option/) + expect(textOf(refused)).toMatch(/call h5p_play again/) + const draw = await call('h5p_play', { source: { ...META, type: 'H5P.QuestionSet', title: 'Rivers', params: { poolSize: 1, questions: [ + { library: 'H5P.TrueFalse', params: { question: 'The Volga is in Europe.', correct: 'true' } }, + { library: 'H5P.TrueFalse', params: { question: 'The Nile is in Asia.', correct: 'false' } } + ] } } }) + // What a learner gets, said first: a chat that changed the content reads it back (#268). + expect(textOf(draw)).toMatch(/What it holds:\nShows 1 of the 2 questions each time/) + }) + + it('hands an attached file\'s reference to the card alone, and never asks for the file', async () => { + const before = asked + const played = await call('h5p_play', { source: VIDEO, file: { download_url: fileAddress, file_id: 'file_abc', mime_type: 'video/mp4', file_name: 'IMG_0042.mp4' } }) + expect(played.isError).toBeFalsy() + // The source is checked without its file, which is named. + expect(textOf(played)).toContain('Its file, IMG_0042.mp4, is not checked here: the card gets the attachment in the person\'s browser.') + expect(textOf(played)).toContain('What it holds:\nVideo: IMG_0042.mp4') + // The reference goes back as it came, in the part of the answer the model does not see. + expect(played._meta?.['h5p/file']).toEqual({ download_url: fileAddress, file_id: 'file_abc', mime_type: 'video/mp4', file_name: 'IMG_0042.mp4' }) + expect(textOf(played) + JSON.stringify(played.structuredContent)).not.toContain('KEY-TO-THE-FILE') + expect(played.structuredContent).toEqual({ files: 1, fileId: 'file_abc', fileName: 'IMG_0042.mp4' }) + expect(asked).toBe(before) + }) + + it('answers a call whose file is not a reference, and passes none on', async () => { + // A model that wrote the file's name where the attachment goes: said, not refused unread. + const named = await call('h5p_play', { source: VIDEO, file: 'IMG_0042.mp4' }) + expect(named.isError).toBeFalsy() + expect(textOf(named)).toContain('no attachment came with the call') + expect(named._meta?.['h5p/file']).toBeUndefined() + // An address that is not https, or not an address, is no reference. + for (const address of ['http://files.example/abc', 'file:///etc/passwd', 'not an address']) { + const other = await call('h5p_play', { source: VIDEO, file: { download_url: address, file_id: 'file_abc' } }) + expect(other._meta?.['h5p/file']).toBeUndefined() + expect(textOf(other)).toContain('no attachment came with the call') + } + // An attachment the source does not name is said, so the model names it. + const unused = await call('h5p_play', { source: QUIZ, file: { download_url: fileAddress, file_id: 'file_abc' } }) + expect(textOf(unused)).toContain('the source names no file, so it is not used') + // A file of a type the field does not take is a problem of the source's, by its name alone. + const wrong = await call('h5p_play', { source: { ...VIDEO, params: { interactiveVideo: { video: { files: [{ path: 'notes.txt' }] } } } } }) + expect(wrong.isError).toBe(true) + expect(textOf(wrong)).toMatch(/notes\.txt: this field takes \.mp4/) + }) + + it('answers the endpoint and nothing else, and no body over 1 MB', async () => { + const origin = new URL(address).origin + expect((await fetch(`${origin}/`)).status).toBe(200) + expect((await fetch(`${origin}/h5p/play/`)).status).toBe(404) + expect((await fetch(`${origin}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'h5p_play', arguments: { source: { ...QUIZ, title: 'x'.repeat(1024 * 1024) } } } }) })).status).toBe(413) + }) + + it('writes down nothing of what it was asked', () => { + // Every call above was made: all the command ever wrote is where it listens. + expect(written.trim().split('\n')).toHaveLength(1) + expect(written).toMatch(/^h5p-mcp-app \S+ on http:\/\/127\.0\.0\.1:\d+\/mcp, framing https:\/\/missing-elements\.github\.io\n$/) + }) +}) From 9751800034c4e19742e05c662be56dd4e9c874f9 Mon Sep 17 00:00:00 2001 From: Aleksandr Shevchuk Date: Tue, 24 Nov 2026 14:01:51 +0200 Subject: [PATCH 2/3] fix(mcp): the app server hands the card a file's id and never its address, the card says when a file did not come and guesses no name, and the test counts connections (#270) --- design/mcp.md | 26 +++++++++++++++---------- packages/author/lib/media.mjs | 3 ++- packages/mcp/README.md | 8 +++++--- packages/mcp/lib/app.mjs | 23 ++++++++++++---------- packages/mcp/lib/card.html | 25 ++++++++++++++---------- packages/mcp/tests/app.test.ts | 35 ++++++++++++++++++++++------------ 6 files changed, 74 insertions(+), 46 deletions(-) diff --git a/design/mcp.md b/design/mcp.md index bdb9dffd..8196e480 100644 --- a/design/mcp.md +++ b/design/mcp.md @@ -88,13 +88,17 @@ port. Its endpoint is `/mcp`. - **No server of ours processes a person's file** (the owner's rule, 2026-11-24, and a goal of the whole toolkit). The chat sends the tool a reference to an attached file, an address and an id, - never its bytes. The server never asks that address: it hands the reference back to the card in - the result's `_meta`, which the model does not see, and only the person's browser asks it. What + never its bytes. The server never asks that address and never passes it on: it hands the id to + the card, which asks the chat for the file's address (`getFileDownloadUrl`), and only the + person's browser fetches from it. So an address that came in a call, which a model can be made + to write, is one nobody fetches: the card fetches what the chat itself gives for a file of the + person's. What the server cannot avoid is receiving the call, with the activity's source in it; it checks the source and keeps nothing. Each request gets a fresh server and no session; nothing of a request is stored and nothing is logged, not its body, not its address, not how it was answered, and no error of the protocol's, which may quote what was sent. `app.test.ts` holds it to this: a file - store that counts is never asked, and all the command ever writes is where it listens. + store that counts every connection gets none, an answer carries the address nowhere, and all + the command ever writes is where it listens. - **Two tools, in the local server's words.** `h5p_types` answers from `answers.mjs` as the local one does, without the lines on folders, which it has none of. `h5p_play` takes a source and checks it with the author package's check that reads no file (`check` with `unread`), since a @@ -108,14 +112,15 @@ port. Its endpoint is `/mcp`. `openai/fileParams` and its schema is the reference's: `download_url` and `file_id` required, `mime_type` and `file_name`, nothing else. It is shown and not enforced, as `source` is: a model that writes the file's name there is answered that no attachment came, where a schema - would refuse the call unread. A reference is passed on only where its address is https. + would refuse the call unread. One file is taken: a source that names several gets the + attachment under its own name, and the page asks the person for the rest. - **The card is the play page's way to the chat, and holds nothing of the activity.** `lib/card.html` frames `/h5p/play/` of the org site with the source in its fragment; the page builds and plays in the person's browser, and its rules are that site's. The card gives it - what only the chat has, by the page's messages: the attached file's address (a new one by its - id, `getFileDownloadUrl`) and what it weighs, its bytes where the page needs them, the chat's - theme, a save (`ui/download-file`), and an open tab for a link of the site's and no other - (`openExternal`). It sends nothing to the server it came from and calls no tool. Its policy + what only the chat has, by the page's messages: the attached file's address, asked of the chat + by the file's id, and what it weighs, its bytes where the page needs them or that they did not + come, the chat's theme, a save (`ui/download-file`), and an open tab for a link of the site's + and no other (`openExternal`). It sends nothing to the server it came from and calls no tool. Its policy names the one site it frames and the chat's file store. A chat keeps a card by its address, so the address carries the card's hash. - **What ChatGPT's frame was found to do is written in the card, with its date.** A card's frame @@ -127,7 +132,8 @@ port. Its endpoint is `/mcp`. - **Tested as a host runs it.** `tests/app.test.ts` starts the command on a free port and asks it over HTTP with the SDK's own client: the two tools and their words, the file input's schema, the card and its policy, a source checked, one refused, an attachment handed to the card alone, - a call whose file is no reference, a body over 1 MB, and that nothing was written. The card in - a chat's frame is checked by hand, in ChatGPT and in a page that stands in for one. + a call whose file is no reference, a body over 1 MB, and that nothing was written. The card is + checked by hand in a page that stands in for a chat, its frame sandboxed as ChatGPT's was found + to be; in ChatGPT itself ran the probe's card, which this one is without its test parts. Not built yet: where the server is hosted, the app's privacy policy and its listing (#210). diff --git a/packages/author/lib/media.mjs b/packages/author/lib/media.mjs index fd3807b2..67d5d3c5 100644 --- a/packages/author/lib/media.mjs +++ b/packages/author/lib/media.mjs @@ -196,7 +196,8 @@ const IDLE_MS = 60_000 * file's length, and its bytes read from an offset, fewer at its end; `linked`, the web address * a file the source names stays at and is played from, where it has one (#263); `unread`, for * a check of a source whose files are elsewhere (#270): none is looked for, none downloaded and - * no host asked, and each is judged by its name alone + * no host asked; one named by a path is judged by its name alone and listed, and one named by + * a web address is left as written */ /** diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 3ebc37e1..dd943729 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -81,10 +81,12 @@ the person's browser and plays it there. What the server receives, and what it keeps: -- It receives each tool call, with the activity's source in it, and checks the source. +- A call of `h5p_play` brings it the activity's source, which it checks. A call of `h5p_types` + brings it the name of a content type, or nothing. - It never receives a file. For a file attached in the chat, the chat sends a reference, an - address and an id; the server does not ask that address, and hands the reference to the card, - where the person's browser fetches the file from the chat's own store. + address and an id. The server does not ask that address and does not pass it on: it hands the + id to the card, which asks the chat for the file's address, and the person's browser fetches + the file from the chat's own store. - It stores nothing and logs nothing of a request. Whoever hosts it may log requests on their own side: that is the host's to say. - A package up to about 8 MB is saved through the chat. A bigger one, with a video in it, is saved diff --git a/packages/mcp/lib/app.mjs b/packages/mcp/lib/app.mjs index ee72e165..76bfe694 100644 --- a/packages/mcp/lib/app.mjs +++ b/packages/mcp/lib/app.mjs @@ -13,8 +13,9 @@ import { SOURCE_PROPERTIES, TYPES, answer, heldLines, refusal, typeAnswers } fro * * It keeps nothing. Each request gets a fresh server, answers, and is gone; nothing of a request * is stored and nothing of it is logged. A file the person attached in the chat never comes here: - * the chat sends its reference (an address and an id), which is handed back to the card in the - * part of the answer the model does not see, and only the person's browser asks that address. + * the chat sends its reference, an address and an id. The address is never asked and never + * passed on. The id is handed to the card, which asks the chat itself for the file's address, + * from the person's browser: an address the chat did not give is one nobody fetches. * * @typedef {object} AppOptions * @property {string} [site] the origin of the site whose play page the card frames; `https://missing-elements.github.io` by default @@ -54,16 +55,18 @@ const FILE = { const FILE_HOSTS = ['https://*.blob.core.windows.net', 'https://files.oaiusercontent.com', 'https://*.oaiusercontent.com'] /** - * The chat's reference to an attached file, as far as it is one: an http(s) address, and what - * came with it. Text in its place is none. + * What of the chat's reference to an attached file goes to the card: its id, and its name and + * type where they came. Not its address, which lets whoever has it read the file, and which a + * call could carry a made-up one of: the card asks the chat for the address by the id. Text in + * the reference's place, or one with no id, is none. * @param {unknown} file */ function attached(file) { if (!file || typeof file !== 'object') return null - const { download_url: address, file_id: id, mime_type: type, file_name: name } = /** @type {Record} */ (file) - if (typeof address !== 'string' || !/^https:\/\//i.test(address) || !URL.canParse(address)) return null - const text = (/** @type {unknown} */ value) => (typeof value === 'string' && value.length <= 512 ? value : undefined) - return { download_url: address, file_id: text(id), mime_type: text(type), file_name: text(name) } + const { file_id: id, mime_type: type, file_name: name } = /** @type {Record} */ (file) + const text = (/** @type {unknown} */ value) => (typeof value === 'string' && value.trim() && value.length <= 512 ? value : undefined) + const fileId = text(id) + return fileId ? { file_id: fileId, mime_type: text(type), file_name: text(name) } : null } /** @@ -139,8 +142,8 @@ export async function createApp(options = {}) { lines.push(...heldLines(result)) return { ...answer(lines.join('\n')), - structuredContent: { files: files.length, ...(given?.file_id ? { fileId: given.file_id } : {}), ...(given?.file_name ? { fileName: given.file_name } : {}) }, - // To the card alone, which the model does not see: the attachment's address is a key to the file. + structuredContent: { files: files.length, ...(given ? { fileId: given.file_id } : {}), ...(given?.file_name ? { fileName: given.file_name } : {}) }, + // For the card, as a chat hands a card either part of an answer. ...(given ? { _meta: { 'h5p/file': given } } : {}) } }) diff --git a/packages/mcp/lib/card.html b/packages/mcp/lib/card.html index ecc5cc63..8057861c 100644 --- a/packages/mcp/lib/card.html +++ b/packages/mcp/lib/card.html @@ -118,24 +118,24 @@ sizeToContent() } -// The file the person attached, as the server was given it and handed it back in the part of the -// tool's result the model does not see: its id, its name, and its address in the chat's store. +// The file the person attached, as the server handed it on in the tool's result: its id in the +// chat's store, and its name and type. Never its address: the card asks the chat for that. let attached = null function fromResult(meta, output) { if (attached) return const file = meta?.['h5p/file'] - if (file && typeof file === 'object' && (file.file_id || file.download_url)) attached = { id: file.file_id, name: file.file_name, link: file.download_url, mime: file.mime_type } - else if (output?.fileId) attached = { id: output.fileId, name: output.fileName } + if (file && typeof file === 'object' && typeof file.file_id === 'string') attached = { id: file.file_id, name: file.file_name, mime: file.mime_type } + else if (typeof output?.fileId === 'string') attached = { id: output.fileId, name: output.fileName } if (attached) void answer() } -// An address of the file that is good now: a new one by its id, or the one the tool was given. +// An address of the file that is good now, asked of the chat by the file's id: no address comes +// from anywhere else, so none is fetched that the chat did not give for a file of the person's. async function linkNow() { try { - const fresh = attached.id && await openai()?.getFileDownloadUrl?.({ fileId: attached.id }) + const fresh = await openai()?.getFileDownloadUrl?.({ fileId: attached.id }) const href = typeof fresh === 'string' ? fresh : fresh?.downloadUrl ?? fresh?.url - if (href) return href - } catch { /* the address the tool was given, then */ } - return attached.link ?? null + return typeof href === 'string' && /^https?:\/\//i.test(href) ? href : null + } catch { return null } } const plays = (name) => /\.(mp4|webm|ogv|mov|mp3|m4a|wav|ogg|oga)$/i.test(name) @@ -145,8 +145,11 @@ let answered = false async function answer() { if (answered || !attached || !needed?.length) return + // One file needed is the attachment, whatever each is called. Of several, it is the one of its + // own name, where it has one; the page asks the person for the rest, and for it where it has none. + const name = needed.length === 1 ? needed[0] : attached.name + if (typeof name !== 'string' || !name) return answered = true - const name = needed.length === 1 ? needed[0] : attached.name ?? needed[0] if (!plays(name)) return void bring(name) const href = await linkNow() if (!href) { answered = false; return } @@ -194,6 +197,8 @@ } catch { // Once more with a new address: the first may have run out. Not where the fetch was given up. if (!again && !stop?.signal.aborted) return bring(name, true) + // It did not come: the page is told, so that it asks the person in place of waiting on. + if (!stop?.signal.aborted) toPage({ type: 'failed', name }) } bringing = false } diff --git a/packages/mcp/tests/app.test.ts b/packages/mcp/tests/app.test.ts index c8c3b3cc..3ef44560 100644 --- a/packages/mcp/tests/app.test.ts +++ b/packages/mcp/tests/app.test.ts @@ -1,6 +1,5 @@ import { spawn, type ChildProcess } from 'node:child_process' -import { createServer, type Server } from 'node:http' -import type { AddressInfo } from 'node:net' +import { createServer, type AddressInfo, type Server } from 'node:net' import { resolve } from 'node:path' import { Client } from '@modelcontextprotocol/client' import { StreamableHTTPClientTransport } from '@modelcontextprotocol/client' @@ -35,7 +34,10 @@ let command: ChildProcess let written = '' let address: string let client: Client -/** A store of a chat's files, which the server must never ask: it counts what it is asked. */ +/** + * A store of a chat's files, which the server must never ask. It counts every connection made to + * it, whatever is said on one: an address of https is asked by a connection first. + */ let store: Server let asked = 0 let fileAddress: string @@ -44,9 +46,9 @@ const call = async (name: string, args: Record = {}) => (await const textOf = (answer: Answer) => answer.content.filter((part) => part.type === 'text').map((part) => part.text).join('\n') beforeAll(async () => { - store = createServer((_request, response) => { asked++; response.end('never') }).listen(0, '127.0.0.1') + store = createServer((socket) => { asked++; socket.destroy() }).listen(0, '127.0.0.1') await new Promise((done) => store.once('listening', done)) - // An address as a chat gives one: https, with a key in it. Nothing listens there for https, and nothing should ask. + // An address as a chat gives one: https, with a key in it. fileAddress = `https://127.0.0.1:${(store.address() as AddressInfo).port}/files/abc?sig=KEY-TO-THE-FILE` command = spawn(process.execPath, [COMMAND, '--port', '0'], { stdio: ['ignore', 'pipe', 'pipe'] }) address = await new Promise((found, failed) => { @@ -154,17 +156,20 @@ describe('the app server', () => { expect(textOf(draw)).toMatch(/What it holds:\nShows 1 of the 2 questions each time/) }) - it('hands an attached file\'s reference to the card alone, and never asks for the file', async () => { + it('hands an attached file\'s id to the card, and neither asks its address nor passes it on', async () => { + // The store does count whoever asks that address: this test's own asking, here. + await fetch(fileAddress).catch(() => {}) + expect(asked).toBe(1) const before = asked const played = await call('h5p_play', { source: VIDEO, file: { download_url: fileAddress, file_id: 'file_abc', mime_type: 'video/mp4', file_name: 'IMG_0042.mp4' } }) expect(played.isError).toBeFalsy() // The source is checked without its file, which is named. expect(textOf(played)).toContain('Its file, IMG_0042.mp4, is not checked here: the card gets the attachment in the person\'s browser.') expect(textOf(played)).toContain('What it holds:\nVideo: IMG_0042.mp4') - // The reference goes back as it came, in the part of the answer the model does not see. - expect(played._meta?.['h5p/file']).toEqual({ download_url: fileAddress, file_id: 'file_abc', mime_type: 'video/mp4', file_name: 'IMG_0042.mp4' }) - expect(textOf(played) + JSON.stringify(played.structuredContent)).not.toContain('KEY-TO-THE-FILE') + // The id goes to the card, with the name and the type; the address goes nowhere. + expect(played._meta?.['h5p/file']).toEqual({ file_id: 'file_abc', mime_type: 'video/mp4', file_name: 'IMG_0042.mp4' }) expect(played.structuredContent).toEqual({ files: 1, fileId: 'file_abc', fileName: 'IMG_0042.mp4' }) + expect(JSON.stringify(played)).not.toMatch(/KEY-TO-THE-FILE|127\.0\.0\.1/) expect(asked).toBe(before) }) @@ -174,15 +179,21 @@ describe('the app server', () => { expect(named.isError).toBeFalsy() expect(textOf(named)).toContain('no attachment came with the call') expect(named._meta?.['h5p/file']).toBeUndefined() - // An address that is not https, or not an address, is no reference. - for (const address of ['http://files.example/abc', 'file:///etc/passwd', 'not an address']) { - const other = await call('h5p_play', { source: VIDEO, file: { download_url: address, file_id: 'file_abc' } }) + // A reference with no id is none: an address alone is passed to nobody. + for (const file of [{ download_url: fileAddress }, { download_url: fileAddress, file_id: '' }, { download_url: fileAddress, file_id: 7 }]) { + const other = await call('h5p_play', { source: VIDEO, file }) expect(other._meta?.['h5p/file']).toBeUndefined() expect(textOf(other)).toContain('no attachment came with the call') + expect(JSON.stringify(other)).not.toContain('KEY-TO-THE-FILE') } + // Whatever address comes with an id, it is the id that is handed on. + const made = await call('h5p_play', { source: VIDEO, file: { download_url: 'https://attacker.example/any.mp4', file_id: 'file_abc' } }) + expect(made._meta?.['h5p/file']).toEqual({ file_id: 'file_abc' }) + expect(JSON.stringify(made)).not.toContain('attacker.example') // An attachment the source does not name is said, so the model names it. const unused = await call('h5p_play', { source: QUIZ, file: { download_url: fileAddress, file_id: 'file_abc' } }) expect(textOf(unused)).toContain('the source names no file, so it is not used') + expect(asked).toBe(1) // A file of a type the field does not take is a problem of the source's, by its name alone. const wrong = await call('h5p_play', { source: { ...VIDEO, params: { interactiveVideo: { video: { files: [{ path: 'notes.txt' }] } } } } }) expect(wrong.isError).toBe(true) From ed795ce3967bbb5885e3e7044737062e94ce382a Mon Sep 17 00:00:00 2001 From: Aleksandr Shevchuk Date: Tue, 24 Nov 2026 14:11:02 +0200 Subject: [PATCH 3/3] fix(mcp): an attachment the source does not name is handed to nobody, and the note on unread says when a file is listed (#270) --- packages/author/lib/media.mjs | 5 +++-- packages/mcp/lib/app.mjs | 6 ++++-- packages/mcp/tests/app.test.ts | 2 ++ 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/author/lib/media.mjs b/packages/author/lib/media.mjs index 67d5d3c5..4bc66408 100644 --- a/packages/author/lib/media.mjs +++ b/packages/author/lib/media.mjs @@ -196,8 +196,9 @@ const IDLE_MS = 60_000 * file's length, and its bytes read from an offset, fewer at its end; `linked`, the web address * a file the source names stays at and is played from, where it has one (#263); `unread`, for * a check of a source whose files are elsewhere (#270): none is looked for, none downloaded and - * no host asked; one named by a path is judged by its name alone and listed, and one named by - * a web address is left as written + * no host asked; one named by a path is judged by its name alone, a problem where its field + * takes no such type and listed where it does, and one named by a web address is left as + * written */ /** diff --git a/packages/mcp/lib/app.mjs b/packages/mcp/lib/app.mjs index 76bfe694..288bb26a 100644 --- a/packages/mcp/lib/app.mjs +++ b/packages/mcp/lib/app.mjs @@ -129,14 +129,16 @@ export async function createApp(options = {}) { // Not a problem of the source's, and its words may be of this computer: none are passed on. return refusal('The check could not be run, through no fault of the source. Call h5p_play again in a moment.') } - const given = attached(file) const files = result.unread + const came = attached(file) + // An attachment goes to the card only for a source that names a file: one it does not name is not used. + const given = files.length ? came : null const lines = [`The activity is checked and plays in the card: ${result.manifest.mainLibrary}, ${result.libraries.length} libraries. It is built in the person's browser; nothing was stored.`] if (files.length) { lines.push(given ? `Its file${files.length === 1 ? '' : 's'}, ${files.join(', ')}, ${files.length === 1 ? 'is' : 'are'} not checked here: the card gets the attachment in the person's browser${files.length === 1 ? '' : ', and asks the person for any other'}.` : `Its file${files.length === 1 ? '' : 's'}, ${files.join(', ')}, ${files.length === 1 ? 'is' : 'are'} not checked here, and no attachment came with the call: the card asks the person to choose ${files.length === 1 ? 'it' : 'them'}. Where the person attached ${files.length === 1 ? 'it' : 'one'} in the chat, call h5p_play again with the attachment in file.`) - } else if (given) { + } else if (came) { lines.push('An attachment came with the call, and the source names no file, so it is not used: name it in the source, as the type\'s notes say, to use it.') } lines.push(...heldLines(result)) diff --git a/packages/mcp/tests/app.test.ts b/packages/mcp/tests/app.test.ts index 3ef44560..a3e46ff0 100644 --- a/packages/mcp/tests/app.test.ts +++ b/packages/mcp/tests/app.test.ts @@ -193,6 +193,8 @@ describe('the app server', () => { // An attachment the source does not name is said, so the model names it. const unused = await call('h5p_play', { source: QUIZ, file: { download_url: fileAddress, file_id: 'file_abc' } }) expect(textOf(unused)).toContain('the source names no file, so it is not used') + expect(unused.structuredContent).toEqual({ files: 0 }) + expect(unused._meta?.['h5p/file']).toBeUndefined() expect(asked).toBe(1) // A file of a type the field does not take is a problem of the source's, by its name alone. const wrong = await call('h5p_play', { source: { ...VIDEO, params: { interactiveVideo: { video: { files: [{ path: 'notes.txt' }] } } } } })