@missing-elements/h5p-mcp 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -2
- package/bin/h5p-mcp-app.mjs +91 -0
- package/lib/answers.mjs +101 -0
- package/lib/app.mjs +178 -0
- package/lib/card.html +322 -0
- package/lib/server.mjs +12 -63
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -7,7 +7,8 @@ that it plays in a real H5P player, and opens it in your browser. It reads a `.h
|
|
|
7
7
|
into its source too, to change it and build it again. No H5P site, server or account.
|
|
8
8
|
|
|
9
9
|
It is a local [MCP](https://modelcontextprotocol.io) server: your app starts it on your computer,
|
|
10
|
-
and it sends nothing to a server of ours.
|
|
10
|
+
and it sends nothing to a server of ours. For a chat app on the web there is a second command,
|
|
11
|
+
[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
|
|
11
12
|
Edge; without either, run `npx playwright install chromium` once.
|
|
12
13
|
|
|
13
14
|
## Add it to your app
|
|
@@ -58,10 +59,39 @@ The build downloads each picture, video, recording or other file your content na
|
|
|
58
59
|
address, and refuses to download from an address on your local network: a guard against a mistaken
|
|
59
60
|
or planted address, not against a hostile network. A video on YouTube, Vimeo, Panopto or Echo360 is
|
|
60
61
|
not downloaded: it stays an address, which the player loads wherever it points, as H5P does
|
|
61
|
-
anywhere.
|
|
62
|
+
anywhere. A YouTube or Vimeo address is sent to that site's oEmbed, to ask whether it has the
|
|
63
|
+
video. Math is drawn by the package's own copy of MathJax, which loads nothing from elsewhere.
|
|
62
64
|
The check and the preview play the package from your computer. Your app
|
|
63
65
|
sends your conversation to its model, as it does without this server.
|
|
64
66
|
|
|
67
|
+
## The app server, for a chat app on the web
|
|
68
|
+
|
|
69
|
+
The package has a second command, `h5p-mcp-app`: an MCP server over HTTP for a chat app that shows
|
|
70
|
+
a card in its reply, ChatGPT first. The person asks for an activity, the reply plays it, and its
|
|
71
|
+
`.h5p` is saved from there. It is not a service we run yet: run it yourself to try it.
|
|
72
|
+
|
|
73
|
+
```sh
|
|
74
|
+
npx -y -p @missing-elements/h5p-mcp h5p-mcp-app --port 8787
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Its endpoint is `/mcp`, with no sign-in. It has two tools: `h5p_types`, as above, and `h5p_play`,
|
|
78
|
+
which checks an activity's source and shows the card. The card frames the play page of
|
|
79
|
+
[missing-elements.github.io](https://missing-elements.github.io/h5p/), which builds the activity in
|
|
80
|
+
the person's browser and plays it there.
|
|
81
|
+
|
|
82
|
+
What the server receives, and what it keeps:
|
|
83
|
+
|
|
84
|
+
- A call of `h5p_play` brings it the activity's source, which it checks. A call of `h5p_types`
|
|
85
|
+
brings it the name of a content type, or nothing.
|
|
86
|
+
- It never receives a file. For a file attached in the chat, the chat sends a reference, an
|
|
87
|
+
address and an id. The server does not ask that address and does not pass it on: it hands the
|
|
88
|
+
id to the card, which asks the chat for the file's address, and the person's browser fetches
|
|
89
|
+
the file from the chat's own store.
|
|
90
|
+
- It stores nothing and logs nothing of a request. Whoever hosts it may log requests on their own
|
|
91
|
+
side: that is the host's to say.
|
|
92
|
+
- A package up to about 8 MB is saved through the chat. A bigger one, with a video in it, is saved
|
|
93
|
+
by a tab of the play page, which fetches the video from the chat and builds the package again.
|
|
94
|
+
|
|
65
95
|
## Licence
|
|
66
96
|
|
|
67
97
|
MIT. The H5P libraries a package carries are under their own licences, listed in it.
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createServer } from 'node:http'
|
|
3
|
+
import { readFile } from 'node:fs/promises'
|
|
4
|
+
import { Readable } from 'node:stream'
|
|
5
|
+
import { parseArgs } from 'node:util'
|
|
6
|
+
|
|
7
|
+
const HELP = `Usage: h5p-mcp-app [--port <number>] [--host <address>] [--site <origin>]
|
|
8
|
+
|
|
9
|
+
The app server of H5P Author MCP by Missing Elements: an MCP server over HTTP for a chat app
|
|
10
|
+
that shows a card in its reply. Its endpoint is /mcp. It checks an activity's source and the
|
|
11
|
+
card builds and plays the activity in the person's browser. It stores nothing, logs nothing
|
|
12
|
+
of a request, and never asks for a file a person attached in the chat.
|
|
13
|
+
|
|
14
|
+
Options:
|
|
15
|
+
--port <number> the port to listen on; 8787 by default, or PORT from the environment
|
|
16
|
+
--host <address> the address to listen on; 127.0.0.1 by default, 0.0.0.0 for every interface
|
|
17
|
+
--site <origin> the site whose play page the card frames;
|
|
18
|
+
https://missing-elements.github.io by default
|
|
19
|
+
--version
|
|
20
|
+
-h, --help
|
|
21
|
+
`
|
|
22
|
+
|
|
23
|
+
let values
|
|
24
|
+
try {
|
|
25
|
+
;({ values } = parseArgs({
|
|
26
|
+
options: {
|
|
27
|
+
port: { type: 'string' },
|
|
28
|
+
host: { type: 'string' },
|
|
29
|
+
site: { type: 'string' },
|
|
30
|
+
version: { type: 'boolean' },
|
|
31
|
+
help: { type: 'boolean', short: 'h' }
|
|
32
|
+
}
|
|
33
|
+
}))
|
|
34
|
+
} catch (error) {
|
|
35
|
+
console.error(`h5p-mcp-app: ${error instanceof Error ? error.message : error}\n\n${HELP}`)
|
|
36
|
+
process.exit(2)
|
|
37
|
+
}
|
|
38
|
+
if (values.help) {
|
|
39
|
+
process.stdout.write(HELP)
|
|
40
|
+
process.exit(0)
|
|
41
|
+
}
|
|
42
|
+
if (values.version) {
|
|
43
|
+
const { version } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'))
|
|
44
|
+
process.stdout.write(`@missing-elements/h5p-mcp ${version}\n`)
|
|
45
|
+
process.exit(0)
|
|
46
|
+
}
|
|
47
|
+
const port = Number(values.port ?? process.env.PORT ?? 8787)
|
|
48
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
49
|
+
console.error(`h5p-mcp-app: ${values.port ?? process.env.PORT} is not a port`)
|
|
50
|
+
process.exit(2)
|
|
51
|
+
}
|
|
52
|
+
if (values.site !== undefined && !URL.canParse(values.site)) {
|
|
53
|
+
console.error(`h5p-mcp-app: ${values.site} is not an origin, as https://example.org`)
|
|
54
|
+
process.exit(2)
|
|
55
|
+
}
|
|
56
|
+
const host = values.host ?? '127.0.0.1'
|
|
57
|
+
|
|
58
|
+
// Loaded only now, so that --help and --version answer without loading the pack.
|
|
59
|
+
const { createApp } = await import('../lib/app.mjs')
|
|
60
|
+
const app = await createApp({ site: values.site })
|
|
61
|
+
|
|
62
|
+
// One HTTP request, as the web's Request and Response, to the app and back. Nothing of it is
|
|
63
|
+
// written anywhere: not its address, not its body, not how it was answered.
|
|
64
|
+
const listening = createServer(async (req, res) => {
|
|
65
|
+
try {
|
|
66
|
+
const body = req.method === 'GET' || req.method === 'HEAD' ? undefined : /** @type {ReadableStream<Uint8Array>} */ (Readable.toWeb(req))
|
|
67
|
+
const headers = new Headers()
|
|
68
|
+
for (const [name, value] of Object.entries(req.headers)) if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(', ') : value)
|
|
69
|
+
const request = new Request(new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`), { method: req.method, headers, body, duplex: 'half' })
|
|
70
|
+
const response = await app.fetch(request)
|
|
71
|
+
res.writeHead(response.status, Object.fromEntries(response.headers))
|
|
72
|
+
if (!response.body) return void res.end()
|
|
73
|
+
// A stream that is given up on, by either end, ends the other.
|
|
74
|
+
res.on('close', () => { void response.body?.cancel().catch(() => {}) })
|
|
75
|
+
for await (const chunk of response.body) res.write(chunk)
|
|
76
|
+
res.end()
|
|
77
|
+
} catch {
|
|
78
|
+
if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
|
|
79
|
+
res.end(res.writableEnded ? undefined : 'The request could not be answered\n')
|
|
80
|
+
}
|
|
81
|
+
})
|
|
82
|
+
listening.listen(port, host, () => {
|
|
83
|
+
const at = /** @type {import('node:net').AddressInfo} */ (listening.address())
|
|
84
|
+
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'}`)
|
|
85
|
+
})
|
|
86
|
+
const stop = () => {
|
|
87
|
+
listening.close()
|
|
88
|
+
void app.close().finally(() => process.exit(0))
|
|
89
|
+
}
|
|
90
|
+
process.on('SIGINT', stop)
|
|
91
|
+
process.on('SIGTERM', stop)
|
package/lib/answers.mjs
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { readdir, readFile } from 'node:fs/promises'
|
|
2
|
+
import { dirname, join } from 'node:path'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
4
|
+
import { z } from 'zod'
|
|
5
|
+
import { contentTypes, openPack, schemaOf, sourceSchema, sourceType } from '@missing-elements/h5p-author'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* What both servers of this package say alike: the local one over standard input and output
|
|
9
|
+
* (`server.mjs`) and the app server over HTTP (`app.mjs`). The content types and a type's file,
|
|
10
|
+
* a source's own fields, and a build's notes and outline. None of it is a rule of this package's:
|
|
11
|
+
* each is the author package's, put into an answer.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
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.`
|
|
15
|
+
|
|
16
|
+
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.`
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A source's own fields as the author package declares them (#230), shown to the app as the
|
|
20
|
+
* properties of `source`, and nothing more: no field is said to be required and none forbidden.
|
|
21
|
+
* The build is the check, which reads a source written another way as it is meant (#174) and says
|
|
22
|
+
* every problem at once, where the SDK, or an app holding a call to the schema, would refuse it
|
|
23
|
+
* before the build looked.
|
|
24
|
+
*/
|
|
25
|
+
export const SOURCE_PROPERTIES = z.toJSONSchema(sourceSchema, { io: 'input' }).properties
|
|
26
|
+
|
|
27
|
+
/** Lines of an outline past which an answer says how many more there are. */
|
|
28
|
+
const OUTLINE_LINES = 80
|
|
29
|
+
|
|
30
|
+
/** @param {string} text */
|
|
31
|
+
export const answer = (text) => ({ content: [{ type: /** @type {const} */ ('text'), text }] })
|
|
32
|
+
/** @param {string} text */
|
|
33
|
+
export const refusal = (text) => ({ content: [{ type: /** @type {const} */ ('text'), text }], isError: true })
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A build's notes, and what its content holds, as lines of an answer: the outline, 80 lines of it
|
|
37
|
+
* at most.
|
|
38
|
+
* @param {{ notes: { path: string, message: string }[], outline: string }} result
|
|
39
|
+
*/
|
|
40
|
+
export function heldLines(result) {
|
|
41
|
+
const lines = result.notes.map(({ path, message }) => `Note: ${path} ${message}`)
|
|
42
|
+
const outline = result.outline.split('\n')
|
|
43
|
+
lines.push('', 'What it holds:', ...outline.slice(0, OUTLINE_LINES))
|
|
44
|
+
if (outline.length > OUTLINE_LINES) lines.push(`… and ${outline.length - OUTLINE_LINES} more lines.`)
|
|
45
|
+
return lines
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* What `h5p_types` answers, for a server: the list with the skill's brief, and a type's file, or
|
|
50
|
+
* its fields where it has none.
|
|
51
|
+
* @param {{ libraries?: string }} [options] `libraries`, the pack's `parts/` folder; the installed pack by default
|
|
52
|
+
*/
|
|
53
|
+
export function typeAnswers(options = {}) {
|
|
54
|
+
const author = dirname(fileURLToPath(import.meta.resolve('@missing-elements/h5p-author/package.json')))
|
|
55
|
+
const typeFiles = join(author, 'references', 'types')
|
|
56
|
+
/** @type {Promise<{ name: string, title: string }[]> | undefined} */
|
|
57
|
+
let typeList
|
|
58
|
+
/** The pack's content types, read once: each needs its part opened. */
|
|
59
|
+
function types() {
|
|
60
|
+
typeList ??= (async () => {
|
|
61
|
+
const pack = await openPack(options.libraries)
|
|
62
|
+
try {
|
|
63
|
+
return (await contentTypes(pack)).map((part) => ({ name: part.library.machineName, title: part.library.title }))
|
|
64
|
+
} finally {
|
|
65
|
+
await pack.close()
|
|
66
|
+
}
|
|
67
|
+
})()
|
|
68
|
+
// A pack that could not be opened is opened again at the next question.
|
|
69
|
+
typeList.catch(() => { typeList = undefined })
|
|
70
|
+
return typeList
|
|
71
|
+
}
|
|
72
|
+
/** The content types the skill has a file for, as the author package carries them. */
|
|
73
|
+
async function filed() {
|
|
74
|
+
const names = await readdir(typeFiles).catch(() => [])
|
|
75
|
+
return new Set(names.filter((name) => name.endsWith('.md')).map((name) => name.slice(0, -3)))
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
/**
|
|
79
|
+
* The list, and how to write good content, with a server's own lines between them.
|
|
80
|
+
* @param {string[]} [between]
|
|
81
|
+
*/
|
|
82
|
+
async list(between = []) {
|
|
83
|
+
const [list, files] = await Promise.all([types(), filed()])
|
|
84
|
+
const lines = list.map(({ name, title }) => `${files.has(name) ? '*' : '-'} ${name}: ${title}`)
|
|
85
|
+
const brief = await readFile(join(author, 'references', 'authoring.md'), 'utf8').catch(() => '')
|
|
86
|
+
return [LIST_HEAD, ...lines, ...(between.length ? ['', ...between] : []), ...(brief ? ['', brief] : [])].join('\n')
|
|
87
|
+
},
|
|
88
|
+
/**
|
|
89
|
+
* A type's file, or its fields; `null` for a type the pack has not. Read as a build reads one,
|
|
90
|
+
* so "true false" works.
|
|
91
|
+
* @param {string} type
|
|
92
|
+
*/
|
|
93
|
+
async about(type) {
|
|
94
|
+
const [list, files] = await Promise.all([types(), filed()])
|
|
95
|
+
const name = sourceType({ type }, list.map((each) => each.name))
|
|
96
|
+
if (!name) return null
|
|
97
|
+
const text = files.has(name) ? await readFile(join(typeFiles, `${name}.md`), 'utf8') : await schemaOf(name, { markdown: true, libraries: options.libraries })
|
|
98
|
+
return text.trimEnd()
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
package/lib/app.mjs
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { readFile } from 'node:fs/promises'
|
|
3
|
+
import { McpServer, createMcpHandler } from '@modelcontextprotocol/server'
|
|
4
|
+
import { z } from 'zod'
|
|
5
|
+
import { SourceError, buildPackage } from '@missing-elements/h5p-author'
|
|
6
|
+
import { SOURCE_PROPERTIES, TYPES, answer, heldLines, refusal, typeAnswers } from './answers.mjs'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The app server (#210, #270): an MCP server over HTTP for a chat app that shows a card in its
|
|
10
|
+
* reply, ChatGPT first. Two tools and one card. `h5p_play` checks a source and answers as a build
|
|
11
|
+
* does; the card frames the play page of the site, which builds the activity in the person's
|
|
12
|
+
* browser and plays it there.
|
|
13
|
+
*
|
|
14
|
+
* It keeps nothing. Each request gets a fresh server, answers, and is gone; nothing of a request
|
|
15
|
+
* is stored and nothing of it is logged. A file the person attached in the chat never comes here:
|
|
16
|
+
* the chat sends its reference, an address and an id. The address is never asked and never
|
|
17
|
+
* passed on. The id is handed to the card, which asks the chat itself for the file's address,
|
|
18
|
+
* from the person's browser: an address the chat did not give is one nobody fetches.
|
|
19
|
+
*
|
|
20
|
+
* @typedef {object} AppOptions
|
|
21
|
+
* @property {string} [site] the origin of the site whose play page the card frames; `https://missing-elements.github.io` by default
|
|
22
|
+
* @property {string} [libraries] the pack's `parts/` folder to check with; the installed pack by default
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
const SITE = 'https://missing-elements.github.io'
|
|
26
|
+
|
|
27
|
+
/** A source is text: a body past this is refused before it is read whole. */
|
|
28
|
+
const MOST = 1024 * 1024
|
|
29
|
+
|
|
30
|
+
const INSTRUCTIONS = `Makes an H5P activity and plays it in the chat, built in the person's browser. Nothing is stored.
|
|
31
|
+
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.
|
|
32
|
+
2. Call h5p_types with the type and write the source from its notes, example and fields: only what differs from the defaults.
|
|
33
|
+
3. Call h5p_play with the source. Where it lists problems, fix each at its path and call it again.
|
|
34
|
+
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.
|
|
35
|
+
The author and the licence are what the person gave; otherwise the name you know them by, or "Unknown", and the licence "U".
|
|
36
|
+
The card has the download of the .h5p file: do not offer a link of your own.`
|
|
37
|
+
|
|
38
|
+
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.`
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* A file attached in the chat, as ChatGPT's reference writes a file input, to the letter: it puts
|
|
42
|
+
* the attachment's address and id here for an input named in `openai/fileParams`. Shown to the
|
|
43
|
+
* app as the field's schema and not held to: what comes in its place, a name where a model wrote
|
|
44
|
+
* one, is answered, where a schema would refuse the call unread.
|
|
45
|
+
*/
|
|
46
|
+
const FILE = {
|
|
47
|
+
type: 'object',
|
|
48
|
+
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.',
|
|
49
|
+
properties: { download_url: { type: 'string' }, file_id: { type: 'string' }, mime_type: { type: 'string' }, file_name: { type: 'string' } },
|
|
50
|
+
required: ['download_url', 'file_id'],
|
|
51
|
+
additionalProperties: false
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Where a chat keeps attached files, which the card asks from the person's browser: ChatGPT's, as seen in November 2026. */
|
|
55
|
+
const FILE_HOSTS = ['https://*.blob.core.windows.net', 'https://files.oaiusercontent.com', 'https://*.oaiusercontent.com']
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* What of the chat's reference to an attached file goes to the card: its id, and its name and
|
|
59
|
+
* type where they came. Not its address, which lets whoever has it read the file, and which a
|
|
60
|
+
* call could carry a made-up one of: the card asks the chat for the address by the id. Text in
|
|
61
|
+
* the reference's place, or one with no id, is none.
|
|
62
|
+
* @param {unknown} file
|
|
63
|
+
*/
|
|
64
|
+
function attached(file) {
|
|
65
|
+
if (!file || typeof file !== 'object') return null
|
|
66
|
+
const { file_id: id, mime_type: type, file_name: name } = /** @type {Record<string, unknown>} */ (file)
|
|
67
|
+
const text = (/** @type {unknown} */ value) => (typeof value === 'string' && value.trim() && value.length <= 512 ? value : undefined)
|
|
68
|
+
const fileId = text(id)
|
|
69
|
+
return fileId ? { file_id: fileId, mime_type: text(type), file_name: text(name) } : null
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The app server, as a web-standard handler: `fetch(request)` answers one HTTP request. The MCP
|
|
74
|
+
* endpoint is `/mcp`; every other path is a 404.
|
|
75
|
+
* @param {AppOptions} [options]
|
|
76
|
+
*/
|
|
77
|
+
export async function createApp(options = {}) {
|
|
78
|
+
const site = new URL(options.site ?? SITE).origin
|
|
79
|
+
const { version } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'))
|
|
80
|
+
const card = (await readFile(new URL('./card.html', import.meta.url), 'utf8')).replaceAll('__SITE__', site)
|
|
81
|
+
// A chat keeps a card by its address, so a card that changed has another.
|
|
82
|
+
const cardUri = `ui://h5p-play/card-${createHash('sha256').update(card).digest('hex').slice(0, 12)}.html`
|
|
83
|
+
const about = typeAnswers({ libraries: options.libraries })
|
|
84
|
+
// The card's policy: the one site it frames, and the chat's file store, which it asks for the
|
|
85
|
+
// attached file. Written twice, as the MCP Apps specification places it and as ChatGPT reads it.
|
|
86
|
+
const cardMeta = {
|
|
87
|
+
ui: { csp: { frameDomains: [site], connectDomains: FILE_HOSTS, resourceDomains: FILE_HOSTS }, prefersBorder: true },
|
|
88
|
+
'openai/widgetCSP': { frame_domains: [site], connect_domains: FILE_HOSTS, resource_domains: FILE_HOSTS, redirect_domains: [site] },
|
|
89
|
+
'openai/widgetDescription': 'Plays the H5P activity, built in the person\'s browser, with its download.'
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function server() {
|
|
93
|
+
const mcp = new McpServer({ name: 'h5p-mcp-app', title: 'H5P Author MCP by Missing Elements', version }, { instructions: INSTRUCTIONS })
|
|
94
|
+
|
|
95
|
+
mcp.registerTool('h5p_types', {
|
|
96
|
+
title: 'H5P content types',
|
|
97
|
+
description: TYPES,
|
|
98
|
+
inputSchema: z.object({ type: z.string().optional().describe('A content type, as H5P.MultiChoice or "multiple choice"') }),
|
|
99
|
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
|
100
|
+
}, async ({ type }) => {
|
|
101
|
+
if (!type) return answer(await about.list())
|
|
102
|
+
const text = await about.about(type)
|
|
103
|
+
return text === null ? refusal(`The library pack has no content type "${type}". h5p_types with no type lists them.`) : answer(text)
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
mcp.registerTool('h5p_play', {
|
|
107
|
+
title: 'Play an H5P activity',
|
|
108
|
+
description: PLAY,
|
|
109
|
+
inputSchema: z.object({
|
|
110
|
+
source: z.record(z.string(), z.unknown()).meta({ properties: SOURCE_PROPERTIES, description: 'The source, as h5p_types describes it for its type' }),
|
|
111
|
+
file: z.unknown().optional().meta(FILE)
|
|
112
|
+
}),
|
|
113
|
+
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
|
|
114
|
+
_meta: {
|
|
115
|
+
ui: { resourceUri: cardUri },
|
|
116
|
+
'openai/outputTemplate': cardUri,
|
|
117
|
+
'openai/fileParams': ['file'],
|
|
118
|
+
'openai/toolInvocation/invoking': 'Preparing the activity…',
|
|
119
|
+
'openai/toolInvocation/invoked': 'Ready to play'
|
|
120
|
+
}
|
|
121
|
+
}, async ({ source, file }) => {
|
|
122
|
+
let result
|
|
123
|
+
try {
|
|
124
|
+
// The author package's check of the source alone: no file is looked for and none
|
|
125
|
+
// downloaded, here or anywhere, so a problem names nothing of this computer.
|
|
126
|
+
result = await buildPackage(source, undefined, { check: true, unread: true, libraries: options.libraries })
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (error instanceof SourceError) return refusal(`${error.message}\nFix each at its path and call h5p_play again.`)
|
|
129
|
+
// Not a problem of the source's, and its words may be of this computer: none are passed on.
|
|
130
|
+
return refusal('The check could not be run, through no fault of the source. Call h5p_play again in a moment.')
|
|
131
|
+
}
|
|
132
|
+
const files = result.unread
|
|
133
|
+
const came = attached(file)
|
|
134
|
+
// An attachment goes to the card only for a source that names a file: one it does not name is not used.
|
|
135
|
+
const given = files.length ? came : null
|
|
136
|
+
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.`]
|
|
137
|
+
if (files.length) {
|
|
138
|
+
lines.push(given
|
|
139
|
+
? `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'}.`
|
|
140
|
+
: `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.`)
|
|
141
|
+
} else if (came) {
|
|
142
|
+
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.')
|
|
143
|
+
}
|
|
144
|
+
lines.push(...heldLines(result))
|
|
145
|
+
return {
|
|
146
|
+
...answer(lines.join('\n')),
|
|
147
|
+
structuredContent: { files: files.length, ...(given ? { fileId: given.file_id } : {}), ...(given?.file_name ? { fileName: given.file_name } : {}) },
|
|
148
|
+
// For the card, as a chat hands a card either part of an answer.
|
|
149
|
+
...(given ? { _meta: { 'h5p/file': given } } : {})
|
|
150
|
+
}
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
mcp.registerResource('h5p-play-card', cardUri, { title: 'H5P activity', mimeType: 'text/html;profile=mcp-app', _meta: cardMeta },
|
|
154
|
+
async (uri) => ({ contents: [{ uri: uri.href, mimeType: 'text/html;profile=mcp-app', text: card, _meta: cardMeta }] }))
|
|
155
|
+
return mcp
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Nothing is said of an error either: a message of the protocol's may quote what was sent.
|
|
159
|
+
const handler = createMcpHandler(() => server(), { maxRequestBodySize: MOST })
|
|
160
|
+
return {
|
|
161
|
+
version,
|
|
162
|
+
cardUri,
|
|
163
|
+
/**
|
|
164
|
+
* @param {Request} request
|
|
165
|
+
* @returns {Promise<Response>}
|
|
166
|
+
*/
|
|
167
|
+
async fetch(request) {
|
|
168
|
+
const { pathname } = new URL(request.url)
|
|
169
|
+
// For whoever opens the address, and for a host that asks whether the server is up.
|
|
170
|
+
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' } })
|
|
171
|
+
if (pathname !== '/mcp') return new Response('Not found\n', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
172
|
+
// Said before a body is read, where its length is given; the handler holds one that gives none to the same bound.
|
|
173
|
+
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' } })
|
|
174
|
+
return handler.fetch(request)
|
|
175
|
+
},
|
|
176
|
+
close: () => handler.close()
|
|
177
|
+
}
|
|
178
|
+
}
|
package/lib/card.html
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
+
<title>H5P activity</title>
|
|
7
|
+
<style>
|
|
8
|
+
:root { color-scheme: light dark; --border: light-dark(#d9d6d0, #3a3833); --surface: light-dark(#f1eeea, #24231f); --text: light-dark(#1c1b19, #f2f0ec); --muted: light-dark(#6b6862, #a8a49c); --accent: light-dark(#2f6db5, #7fb0ea); }
|
|
9
|
+
/* A root of its own for the margins inside: a height short by one left a scroller in the card. */
|
|
10
|
+
body { display: flow-root; margin: 0; font: 14px/1.4 system-ui, sans-serif; color: var(--text); background: transparent; }
|
|
11
|
+
[hidden] { display: none !important; }
|
|
12
|
+
/* The page loads under the card's loader, laid out but not seen, and is shown once it has drawn. */
|
|
13
|
+
.stage { display: grid; }
|
|
14
|
+
.stage > * { grid-area: 1 / 1; min-width: 0; }
|
|
15
|
+
iframe { display: block; width: 100%; height: 100%; min-height: 150px; border: 0; visibility: hidden; }
|
|
16
|
+
iframe.on { visibility: visible; }
|
|
17
|
+
/* Before the activity's page is framed: its place, drawn, so the reply does not jump. */
|
|
18
|
+
.wait { z-index: 1; display: grid; place-items: center; align-content: center; gap: 12px; margin: 8px; padding: 0 16px; aspect-ratio: 16 / 9; border: 1px solid var(--border); border-radius: 12px; background: var(--surface); text-align: center; }
|
|
19
|
+
.wait p { margin: 0; font-weight: 600; }
|
|
20
|
+
.wait small { color: var(--muted); font-size: 13px; }
|
|
21
|
+
.spinner { width: 28px; height: 28px; border: 3px solid var(--border); border-top-color: var(--accent); border-radius: 50%; }
|
|
22
|
+
@media (prefers-reduced-motion: no-preference) { .spinner { animation: turn 0.8s linear infinite; } }
|
|
23
|
+
@keyframes turn { to { rotate: 1turn; } }
|
|
24
|
+
</style>
|
|
25
|
+
</head>
|
|
26
|
+
<body>
|
|
27
|
+
<div class="stage">
|
|
28
|
+
<div class="wait" id="wait" role="status"><div class="spinner" id="spinner"></div><p id="wait-title">Opening the activity…</p><small id="wait-note">It is built in your browser.</small></div>
|
|
29
|
+
<iframe id="page" title="The H5P activity" allow="fullscreen; clipboard-write"></iframe>
|
|
30
|
+
</div>
|
|
31
|
+
<script>
|
|
32
|
+
// Runs whatever happens to the script below: a card that cannot go on says so, in place of a
|
|
33
|
+
// loader that turns for good.
|
|
34
|
+
window.addEventListener('error', () => {
|
|
35
|
+
const wait = document.getElementById('wait')
|
|
36
|
+
if (!wait || wait.hidden) return
|
|
37
|
+
document.getElementById('spinner').hidden = true
|
|
38
|
+
document.getElementById('wait-title').textContent = 'The activity could not be opened'
|
|
39
|
+
document.getElementById('wait-note').textContent = 'Ask the chat to show it again.'
|
|
40
|
+
})
|
|
41
|
+
</script>
|
|
42
|
+
<script>
|
|
43
|
+
// The card of the app server (h5p-toolkit #210, #270), shown by a chat in its reply. It frames the
|
|
44
|
+
// play page of the site, which builds the activity in the person's browser and plays it, and is
|
|
45
|
+
// that page's way to what only the chat has: the file the person attached, a save, an open tab.
|
|
46
|
+
// It sends nothing to the server it came from, and writes nothing down.
|
|
47
|
+
//
|
|
48
|
+
// In a function of its own: a chat puts names of its own on the card's window.
|
|
49
|
+
(() => {
|
|
50
|
+
// The site whose play page is framed: the server writes its origin in.
|
|
51
|
+
const SITE = '__SITE__'
|
|
52
|
+
const PLAY = SITE + '/h5p/play/'
|
|
53
|
+
const $ = (id) => document.getElementById(id)
|
|
54
|
+
const frame = $('page')
|
|
55
|
+
const openai = () => window.openai
|
|
56
|
+
const toHost = (message) => window.parent.postMessage({ jsonrpc: '2.0', ...message }, '*')
|
|
57
|
+
const toPage = (message) => frame.contentWindow?.postMessage({ source: 'h5p-play-host', ...message }, SITE)
|
|
58
|
+
|
|
59
|
+
// The card's height, told the chat whatever changes it. The whole document's, whichever is more.
|
|
60
|
+
let told = 0
|
|
61
|
+
function sizeToContent() {
|
|
62
|
+
const height = Math.ceil(Math.max(document.body.getBoundingClientRect().height, document.documentElement.scrollHeight === document.documentElement.clientHeight ? 0 : document.body.scrollHeight))
|
|
63
|
+
if (height === told) return
|
|
64
|
+
told = height
|
|
65
|
+
try { openai()?.notifyIntrinsicHeight?.(height) } catch { /* not this chat's way */ }
|
|
66
|
+
if (window.parent !== window) toHost({ method: 'ui/notifications/size-changed', params: { height } })
|
|
67
|
+
}
|
|
68
|
+
sizeToContent()
|
|
69
|
+
|
|
70
|
+
// The chat's theme, for the card and for the page it frames.
|
|
71
|
+
let theme = null
|
|
72
|
+
let revealed = false
|
|
73
|
+
function themed() {
|
|
74
|
+
const now = openai()?.theme
|
|
75
|
+
if ((now !== 'light' && now !== 'dark') || now === theme) return
|
|
76
|
+
theme = now
|
|
77
|
+
document.documentElement.style.colorScheme = now
|
|
78
|
+
if (revealed) toPage({ type: 'theme', theme: now })
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// The source as the play page's #source= takes it: its JSON, raw-deflated where that is shorter, in base64url.
|
|
82
|
+
async function fragmentOf(source) {
|
|
83
|
+
let bytes = new TextEncoder().encode(JSON.stringify(source))
|
|
84
|
+
try {
|
|
85
|
+
const deflated = new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(new CompressionStream('deflate-raw'))).arrayBuffer())
|
|
86
|
+
if (deflated.length < bytes.length) bytes = deflated
|
|
87
|
+
} catch { /* nothing here compresses: the JSON as it is */ }
|
|
88
|
+
let binary = ''
|
|
89
|
+
for (const byte of bytes) binary += String.fromCharCode(byte)
|
|
90
|
+
return `#source=${btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}`
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// The tool's input, which is the source: the page is framed with it, once.
|
|
94
|
+
let shown = false
|
|
95
|
+
async function show(input) {
|
|
96
|
+
if (shown || !input || typeof input !== 'object') return
|
|
97
|
+
const source = input.source ?? input
|
|
98
|
+
if (!source || typeof source !== 'object' || !source.type) return
|
|
99
|
+
shown = true
|
|
100
|
+
const fragment = await fragmentOf(source)
|
|
101
|
+
themed()
|
|
102
|
+
// The page loads behind the card's own loader, and takes its place once it has something drawn
|
|
103
|
+
// to show: its first word, or its load at the latest. Nothing is blank in between.
|
|
104
|
+
frame.addEventListener('load', () => setTimeout(reveal, 300), { once: true })
|
|
105
|
+
frame.src = PLAY + (theme ? `?theme=${theme}` : '') + fragment
|
|
106
|
+
sizeToContent()
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function reveal() {
|
|
110
|
+
if (revealed) return
|
|
111
|
+
revealed = true
|
|
112
|
+
// Until the page says its own height, it keeps the loader's: the reply does not shrink and grow again.
|
|
113
|
+
if (!frame.style.height) frame.style.height = `${Math.round($('wait').getBoundingClientRect().height + 16)}px`
|
|
114
|
+
$('wait').hidden = true
|
|
115
|
+
frame.classList.add('on')
|
|
116
|
+
if (theme) toPage({ type: 'theme', theme })
|
|
117
|
+
sayWhatTheChatDoes()
|
|
118
|
+
sizeToContent()
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// The file the person attached, as the server handed it on in the tool's result: its id in the
|
|
122
|
+
// chat's store, and its name and type. Never its address: the card asks the chat for that.
|
|
123
|
+
let attached = null
|
|
124
|
+
function fromResult(meta, output) {
|
|
125
|
+
if (attached) return
|
|
126
|
+
const file = meta?.['h5p/file']
|
|
127
|
+
if (file && typeof file === 'object' && typeof file.file_id === 'string') attached = { id: file.file_id, name: file.file_name, mime: file.mime_type }
|
|
128
|
+
else if (typeof output?.fileId === 'string') attached = { id: output.fileId, name: output.fileName }
|
|
129
|
+
if (attached) void answer()
|
|
130
|
+
}
|
|
131
|
+
// An address of the file that is good now, asked of the chat by the file's id: no address comes
|
|
132
|
+
// from anywhere else, so none is fetched that the chat did not give for a file of the person's.
|
|
133
|
+
async function linkNow() {
|
|
134
|
+
try {
|
|
135
|
+
const fresh = await openai()?.getFileDownloadUrl?.({ fileId: attached.id })
|
|
136
|
+
const href = typeof fresh === 'string' ? fresh : fresh?.downloadUrl ?? fresh?.url
|
|
137
|
+
return typeof href === 'string' && /^https?:\/\//i.test(href) ? href : null
|
|
138
|
+
} catch { return null }
|
|
139
|
+
}
|
|
140
|
+
const plays = (name) => /\.(mp4|webm|ogv|mov|mp3|m4a|wav|ogg|oga)$/i.test(name)
|
|
141
|
+
|
|
142
|
+
// The page asked for a file, and the attachment is known: a video or a recording goes as its
|
|
143
|
+
// address and plays from there at once; anything else is brought whole, as the page needs its bytes.
|
|
144
|
+
let needed = null
|
|
145
|
+
let answered = false
|
|
146
|
+
async function answer() {
|
|
147
|
+
if (answered || !attached || !needed?.length) return
|
|
148
|
+
// One file needed is the attachment, whatever each is called. Of several, it is the one of its
|
|
149
|
+
// own name, where it has one; the page asks the person for the rest, and for it where it has none.
|
|
150
|
+
const name = needed.length === 1 ? needed[0] : attached.name
|
|
151
|
+
if (typeof name !== 'string' || !name) return
|
|
152
|
+
answered = true
|
|
153
|
+
if (!plays(name)) return void bring(name)
|
|
154
|
+
const href = await linkNow()
|
|
155
|
+
if (!href) { answered = false; return }
|
|
156
|
+
toPage({ type: 'links', links: { [name]: href } })
|
|
157
|
+
// What the file weighs, from the answer's head, the request dropped before its body comes: the
|
|
158
|
+
// page then opens a tab at once for a package the chat could not save.
|
|
159
|
+
const bytes = await sizeOf(href)
|
|
160
|
+
if (bytes) toPage({ type: 'links', links: { [name]: href }, sizes: { [name]: bytes } })
|
|
161
|
+
}
|
|
162
|
+
async function sizeOf(href) {
|
|
163
|
+
const dropped = new AbortController()
|
|
164
|
+
try {
|
|
165
|
+
const response = await fetch(href, { signal: dropped.signal })
|
|
166
|
+
const total = Number(response.headers.get('content-length')) || 0
|
|
167
|
+
dropped.abort()
|
|
168
|
+
return total
|
|
169
|
+
} catch { return 0 }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// The whole file, counted for the page as it comes, and given to it. Kept by the browser as a
|
|
173
|
+
// Blob, which it may hold on disk: never in this script's own memory.
|
|
174
|
+
let bringing = false
|
|
175
|
+
let stop = null
|
|
176
|
+
async function bring(name, again = false) {
|
|
177
|
+
if (bringing && !again) return
|
|
178
|
+
bringing = true
|
|
179
|
+
try {
|
|
180
|
+
const href = attached && await linkNow()
|
|
181
|
+
if (!href) throw new Error('no address')
|
|
182
|
+
stop = new AbortController()
|
|
183
|
+
const response = await fetch(href, { signal: stop.signal })
|
|
184
|
+
if (!response.ok || !response.body) throw new Error(`status ${response.status}`)
|
|
185
|
+
const total = Number(response.headers.get('content-length')) || 0
|
|
186
|
+
let seen = 0
|
|
187
|
+
let last = 0
|
|
188
|
+
const counted = response.body.pipeThrough(new TransformStream({ transform(chunk, controller) {
|
|
189
|
+
seen += chunk.byteLength
|
|
190
|
+
const now = performance.now()
|
|
191
|
+
if (now - last > 150) { last = now; toPage({ type: 'progress', name, received: seen, total }) }
|
|
192
|
+
controller.enqueue(chunk)
|
|
193
|
+
} }))
|
|
194
|
+
const blob = await new Response(counted, { headers: { 'content-type': response.headers.get('content-type') ?? '' } }).blob()
|
|
195
|
+
toPage({ type: 'progress', name, received: blob.size, total: total || blob.size })
|
|
196
|
+
toPage({ type: 'files', files: [new File([blob], name, { type: attached.mime ?? blob.type })] })
|
|
197
|
+
} catch {
|
|
198
|
+
// Once more with a new address: the first may have run out. Not where the fetch was given up.
|
|
199
|
+
if (!again && !stop?.signal.aborted) return bring(name, true)
|
|
200
|
+
// It did not come: the page is told, so that it asks the person in place of waiting on.
|
|
201
|
+
if (!stop?.signal.aborted) toPage({ type: 'failed', name })
|
|
202
|
+
}
|
|
203
|
+
bringing = false
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// What the play page says from inside the frame: its height, what it needs, the package it
|
|
207
|
+
// built, and what it asks the chat to do.
|
|
208
|
+
window.addEventListener('message', (event) => {
|
|
209
|
+
const message = event.data
|
|
210
|
+
if (event.source !== frame.contentWindow || event.origin !== SITE || message?.source !== 'h5p-play') return
|
|
211
|
+
reveal()
|
|
212
|
+
if (message.type === 'height' && Number.isFinite(message.height)) {
|
|
213
|
+
frame.style.height = `${Math.max(120, Math.min(message.height, 2000))}px`
|
|
214
|
+
sizeToContent()
|
|
215
|
+
} else if (message.type === 'needs-files' && Array.isArray(message.names)) {
|
|
216
|
+
needed = message.names.filter((name) => typeof name === 'string')
|
|
217
|
+
void answer()
|
|
218
|
+
} else if (message.type === 'needs-bytes') {
|
|
219
|
+
void bring(message.names?.[0] ?? needed?.[0] ?? attached?.name ?? 'file')
|
|
220
|
+
} else if (message.type === 'built') {
|
|
221
|
+
// The package is here: a file still on its way from the chat for it is not needed.
|
|
222
|
+
if (bringing) stop?.abort()
|
|
223
|
+
} else if (message.type === 'save') {
|
|
224
|
+
void save(message.file, message.id)
|
|
225
|
+
} else if (message.type === 'open') {
|
|
226
|
+
open(message.href)
|
|
227
|
+
}
|
|
228
|
+
})
|
|
229
|
+
|
|
230
|
+
// A chat's frame saves no file and opens no tab on a press (ChatGPT, November 2026), and the chat
|
|
231
|
+
// does both for the card. So the card tells the page what the chat does, and passes on what the
|
|
232
|
+
// page asks. A save takes a file up to MOST: of what ChatGPT was handed, 8 MB was saved and
|
|
233
|
+
// 16 MB refused, with nothing said why (2026-11-24). A bigger package the page saves its own way.
|
|
234
|
+
const MOST = 8 * 1048576
|
|
235
|
+
let capabilities = null
|
|
236
|
+
let saidSaves = false
|
|
237
|
+
let saidOpens = false
|
|
238
|
+
function sayWhatTheChatDoes() {
|
|
239
|
+
if (!revealed) return
|
|
240
|
+
if (!saidOpens && (typeof openai()?.openExternal === 'function' || capabilities?.openLinks)) {
|
|
241
|
+
saidOpens = true
|
|
242
|
+
toPage({ type: 'opens' })
|
|
243
|
+
}
|
|
244
|
+
if (!saidSaves && capabilities?.downloadFile) {
|
|
245
|
+
saidSaves = true
|
|
246
|
+
toPage({ type: 'saves', max: MOST })
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
// A link of the page's, opened by the chat: an address of the site, and nothing else.
|
|
250
|
+
let asked = 100
|
|
251
|
+
function open(href) {
|
|
252
|
+
if (typeof href !== 'string' || !URL.canParse(href) || new URL(href).origin !== SITE) return
|
|
253
|
+
try {
|
|
254
|
+
if (typeof openai()?.openExternal === 'function') void Promise.resolve(openai().openExternal({ href })).catch(() => {})
|
|
255
|
+
else toHost({ id: ++asked, method: 'ui/open-link', params: { url: href } })
|
|
256
|
+
} catch { /* the page keeps its link, for the browser's own menu */ }
|
|
257
|
+
}
|
|
258
|
+
// A package handed to the chat to save, as one message. How the chat answers is passed back to
|
|
259
|
+
// the page under the number the page gave the save, and the page says it.
|
|
260
|
+
const saving = new Map()
|
|
261
|
+
async function save(file, id) {
|
|
262
|
+
if (!(file instanceof File) || file.size > MOST) return toPage({ type: 'saved', id, ok: false })
|
|
263
|
+
try {
|
|
264
|
+
const dataUrl = await new Promise((resolve, reject) => {
|
|
265
|
+
const reader = new FileReader()
|
|
266
|
+
reader.onload = () => resolve(String(reader.result))
|
|
267
|
+
reader.onerror = () => reject(reader.error)
|
|
268
|
+
reader.readAsDataURL(file)
|
|
269
|
+
})
|
|
270
|
+
const request = ++asked
|
|
271
|
+
saving.set(request, id)
|
|
272
|
+
toHost({ id: request, method: 'ui/download-file', params: { contents: [{ type: 'resource', resource: { uri: `file:///${file.name}`, mimeType: file.type || 'application/zip', blob: dataUrl.slice(dataUrl.indexOf(',') + 1) } }] } })
|
|
273
|
+
} catch {
|
|
274
|
+
toPage({ type: 'saved', id, ok: false })
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// ChatGPT's own way: the tool's input and result as values on the window, there now or set later.
|
|
279
|
+
function globals() {
|
|
280
|
+
const chat = openai()
|
|
281
|
+
if (!chat) return
|
|
282
|
+
themed()
|
|
283
|
+
if (chat.toolInput) void show(chat.toolInput)
|
|
284
|
+
fromResult(chat.toolResponseMetadata, chat.toolOutput)
|
|
285
|
+
}
|
|
286
|
+
window.addEventListener('openai:set_globals', globals)
|
|
287
|
+
globals()
|
|
288
|
+
|
|
289
|
+
// The MCP Apps way: the handshake, the tool's input and result as messages, and the chat's answers.
|
|
290
|
+
window.addEventListener('message', (event) => {
|
|
291
|
+
if (event.source !== window.parent || window.parent === window) return
|
|
292
|
+
const message = event.data
|
|
293
|
+
if (!message || message.jsonrpc !== '2.0') return
|
|
294
|
+
if (message.method === 'ui/notifications/tool-input') void show(message.params?.arguments)
|
|
295
|
+
else if (message.method === 'ui/notifications/tool-result') fromResult(message.params?._meta, message.params?.structuredContent)
|
|
296
|
+
else if (message.id === 1 && !message.method) {
|
|
297
|
+
if (message.result) capabilities = message.result.hostCapabilities ?? null
|
|
298
|
+
if (!message.error) toHost({ method: 'ui/notifications/initialized', params: {} })
|
|
299
|
+
sayWhatTheChatDoes()
|
|
300
|
+
} else if (saving.has(message.id) && !message.method) {
|
|
301
|
+
const id = saving.get(message.id)
|
|
302
|
+
saving.delete(message.id)
|
|
303
|
+
toPage({ type: 'saved', id, ok: !message.error && message.result?.isError !== true })
|
|
304
|
+
} else if (message.method && message.id !== undefined) {
|
|
305
|
+
// A question of the chat's is answered, with nothing: none is one the card has more to say to.
|
|
306
|
+
toHost({ id: message.id, result: {} })
|
|
307
|
+
}
|
|
308
|
+
})
|
|
309
|
+
if (window.parent !== window) toHost({ id: 1, method: 'ui/initialize', params: { protocolVersion: '2026-01-26', appInfo: { name: 'h5p-mcp-app', version: '1' }, appCapabilities: {} } })
|
|
310
|
+
|
|
311
|
+
// No activity came: said, in place of a loader that turns for good.
|
|
312
|
+
setTimeout(() => {
|
|
313
|
+
if (shown) return
|
|
314
|
+
$('spinner').hidden = true
|
|
315
|
+
$('wait-title').textContent = 'No activity arrived'
|
|
316
|
+
$('wait-note').textContent = 'Ask the chat to show it again.'
|
|
317
|
+
}, 6000)
|
|
318
|
+
new ResizeObserver(sizeToContent).observe(document.body)
|
|
319
|
+
})()
|
|
320
|
+
</script>
|
|
321
|
+
</body>
|
|
322
|
+
</html>
|
package/lib/server.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { lstat, mkdtemp,
|
|
1
|
+
import { lstat, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
|
|
2
2
|
import { tmpdir } from 'node:os'
|
|
3
3
|
import { basename, dirname, join, resolve } from 'node:path'
|
|
4
|
-
import { fileURLToPath } from 'node:url'
|
|
5
4
|
import { McpServer } from '@modelcontextprotocol/server'
|
|
6
5
|
import { z } from 'zod'
|
|
7
|
-
import { SourceError, buildPackage,
|
|
6
|
+
import { SourceError, buildPackage, coreApiLine, inside, publicFetch, readPackage } from '@missing-elements/h5p-author'
|
|
8
7
|
import { VerifyError, openBrowser, previewPackage, summarize, verifyPackage } from '@missing-elements/h5p-verify'
|
|
8
|
+
import { SOURCE_PROPERTIES, TYPES, answer, heldLines, refusal, typeAnswers } from './answers.mjs'
|
|
9
9
|
import { defaultFolders, fileStem, rootFolders } from './folders.mjs'
|
|
10
10
|
|
|
11
11
|
/**
|
|
@@ -28,28 +28,10 @@ To change a .h5p the person has, h5p_read it, change its source as asked, and h5
|
|
|
28
28
|
|
|
29
29
|
const READ = `Reads a .h5p package back into its source, to change it and build it again with h5p_build: its type, title, language, licence, authors, and the params that differ from the defaults. Writes the source and the package's media into a new folder beside it, and answers with the source, each file named where it was written. Reads content made for the library pack's versions of its libraries.`
|
|
30
30
|
|
|
31
|
-
const TYPES = `The H5P content types and how to write a source for one. With no type: the list, and how to write good content. With a type: its notes, a tested example and its fields. Read the type's answer before writing its source.`
|
|
32
|
-
|
|
33
31
|
const BUILD = `Builds a .h5p package from a source, its params holding only what differs from the type's defaults. A file is { "path": ... }, in a folder this server may use or at a web address. Writes the package and its source (.source.json) to output, or under a new name in the first folder it may use. A source with problems is refused, each problem named by its path. With verify (the default), plays the package in a headless browser and reports whether it works.`
|
|
34
32
|
|
|
35
33
|
const PREVIEW = `Opens a .h5p package in the person's browser in the real player, served from this computer until its tab is closed. Answers with the address.`
|
|
36
34
|
|
|
37
|
-
const LIST_HEAD = `The content types the library pack has, by the name a source's "type" takes. Those marked * have notes and a tested example; for the rest h5p_types gives their fields.`
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* A source's own fields as the author package declares them (#230), shown to the app as the
|
|
41
|
-
* properties of `source`, and nothing more: no field is said to be required and none forbidden.
|
|
42
|
-
* The build is the check, which reads a source written another way as it is meant (#174) and says
|
|
43
|
-
* every problem at once, where the SDK, or an app holding a call to the schema, would refuse it
|
|
44
|
-
* before the build looked.
|
|
45
|
-
*/
|
|
46
|
-
const SOURCE_PROPERTIES = z.toJSONSchema(sourceSchema, { io: 'input' }).properties
|
|
47
|
-
|
|
48
|
-
/** @param {string} text */
|
|
49
|
-
const answer = (text) => ({ content: [{ type: /** @type {const} */ ('text'), text }] })
|
|
50
|
-
/** @param {string} text */
|
|
51
|
-
const refusal = (text) => ({ content: [{ type: /** @type {const} */ ('text'), text }], isError: true })
|
|
52
|
-
|
|
53
35
|
/** @param {number} bytes */
|
|
54
36
|
const sized = (bytes) => (bytes < 1e6 ? `${Math.max(1, Math.round(bytes / 1e3))} kB` : `${(bytes / 1e6).toFixed(1)} MB`)
|
|
55
37
|
|
|
@@ -61,9 +43,6 @@ const whereFiles = (folders) => folders.length
|
|
|
61
43
|
? `This server reads files and writes packages only in ${folders.join(', ')}. A file's path written alone, as { "path": "picture.png" }, is read from ${folders[0]}.`
|
|
62
44
|
: 'This server has no folder to read or write in: start it with --allow <folder>.'
|
|
63
45
|
|
|
64
|
-
/** Lines of an outline past which an answer says how many more there are. */
|
|
65
|
-
const OUTLINE_LINES = 80
|
|
66
|
-
|
|
67
46
|
/** @param {string} path a package's */
|
|
68
47
|
const sourceBeside = (path) => path.replace(/\.h5p$/i, '.source.json')
|
|
69
48
|
|
|
@@ -92,8 +71,7 @@ function located(value, folder) {
|
|
|
92
71
|
export async function createServer(options = {}) {
|
|
93
72
|
const { version } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'))
|
|
94
73
|
const server = new McpServer({ name: 'h5p-mcp', title: 'H5P Author MCP by Missing Elements', version }, { instructions: INSTRUCTIONS })
|
|
95
|
-
const
|
|
96
|
-
const typeFiles = join(author, 'references', 'types')
|
|
74
|
+
const about = typeAnswers({ libraries: options.libraries })
|
|
97
75
|
/** @type {Set<{ close: () => void }>} */
|
|
98
76
|
const previews = new Set()
|
|
99
77
|
|
|
@@ -111,27 +89,6 @@ export async function createServer(options = {}) {
|
|
|
111
89
|
return defaultFolders()
|
|
112
90
|
}
|
|
113
91
|
|
|
114
|
-
/** @type {Promise<{ name: string, title: string }[]> | undefined} */
|
|
115
|
-
let typeList
|
|
116
|
-
/** The pack's content types, read once: each needs its part opened. */
|
|
117
|
-
function types() {
|
|
118
|
-
typeList ??= (async () => {
|
|
119
|
-
const pack = await openPack(options.libraries)
|
|
120
|
-
try {
|
|
121
|
-
return (await contentTypes(pack)).map((part) => ({ name: part.library.machineName, title: part.library.title }))
|
|
122
|
-
} finally {
|
|
123
|
-
await pack.close()
|
|
124
|
-
}
|
|
125
|
-
})()
|
|
126
|
-
return typeList
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
/** The content types the skill has a file for, as the author package carries them. */
|
|
130
|
-
async function filed() {
|
|
131
|
-
const names = await readdir(typeFiles).catch(() => [])
|
|
132
|
-
return new Set(names.filter((name) => name.endsWith('.md')).map((name) => name.slice(0, -3)))
|
|
133
|
-
}
|
|
134
|
-
|
|
135
92
|
/** The packages being built, lower-cased, as macOS and Windows match a name in any case. */
|
|
136
93
|
const building = new Set()
|
|
137
94
|
|
|
@@ -176,20 +133,13 @@ export async function createServer(options = {}) {
|
|
|
176
133
|
inputSchema: z.object({ type: z.string().optional().describe('A content type, as H5P.MultiChoice or "multiple choice"') }),
|
|
177
134
|
annotations: { readOnlyHint: true, openWorldHint: false }
|
|
178
135
|
}, async ({ type }) => {
|
|
179
|
-
const list = await types()
|
|
180
|
-
const files = await filed()
|
|
181
136
|
// Said with every answer, before a source is written: a model cannot know the folders, and a
|
|
182
137
|
// path it guesses is refused.
|
|
183
138
|
const where = whereFiles(await folders())
|
|
184
|
-
if (!type)
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
}
|
|
189
|
-
const name = sourceType({ type }, list.map((each) => each.name))
|
|
190
|
-
if (!name) return refusal(`The library pack has no content type "${type}". h5p_types with no type lists them.`)
|
|
191
|
-
const text = files.has(name) ? await readFile(join(typeFiles, `${name}.md`), 'utf8') : await schemaOf(name, { markdown: true, libraries: options.libraries })
|
|
192
|
-
return answer(`${text.trimEnd()}\n\n${where}`)
|
|
139
|
+
if (!type) return answer(await about.list([where]))
|
|
140
|
+
const text = await about.about(type)
|
|
141
|
+
if (text === null) return refusal(`The library pack has no content type "${type}". h5p_types with no type lists them.`)
|
|
142
|
+
return answer(`${text}\n\n${where}`)
|
|
193
143
|
})
|
|
194
144
|
|
|
195
145
|
server.registerTool('h5p_build', {
|
|
@@ -217,7 +167,9 @@ export async function createServer(options = {}) {
|
|
|
217
167
|
try {
|
|
218
168
|
result = await buildPackage(source, target, { base: dirname(target), within: allowed, fetch: publicFetch, libraries: options.libraries })
|
|
219
169
|
// Made new: a file or a link put at its name since the name was found free is not written through.
|
|
220
|
-
|
|
170
|
+
// As the build took it, naming the content type's version it was built with (author's #219):
|
|
171
|
+
// for a quiz in the quiz format, the source it was built as, which has the field for it.
|
|
172
|
+
unwritten = await writeFile(sourceFile, `${JSON.stringify(result.source, null, 2)}\n`, { flag: 'wx' }).then(() => undefined, (error) => error)
|
|
221
173
|
} catch (error) {
|
|
222
174
|
if (error instanceof SourceError) return refusal(`${error.message}\nFix each at its path and build again.${/outside the folders/.test(error.message) ? ` ${whereFiles(allowed)}` : ''}`)
|
|
223
175
|
return refusal(error instanceof Error ? error.message : String(error))
|
|
@@ -233,10 +185,7 @@ export async function createServer(options = {}) {
|
|
|
233
185
|
? `Its source was not written beside it: ${unwritten.message}`
|
|
234
186
|
: `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.`
|
|
235
187
|
]
|
|
236
|
-
|
|
237
|
-
const outline = result.outline.split('\n')
|
|
238
|
-
lines.push('', 'What it holds:', ...outline.slice(0, OUTLINE_LINES))
|
|
239
|
-
if (outline.length > OUTLINE_LINES) lines.push(`… and ${outline.length - OUTLINE_LINES} more lines.`)
|
|
188
|
+
lines.push(...heldLines(result))
|
|
240
189
|
/** @type {{ type: 'image', data: string, mimeType: string }[]} */
|
|
241
190
|
const images = []
|
|
242
191
|
if (verify) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@missing-elements/h5p-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "H5P Author MCP by Missing Elements: a local MCP server that builds playable H5P packages of any content type from a short source, checks them in a real player and opens them in the person's browser. No H5P server needed.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -17,7 +17,8 @@
|
|
|
17
17
|
},
|
|
18
18
|
"type": "module",
|
|
19
19
|
"bin": {
|
|
20
|
-
"h5p-mcp": "./bin/h5p-mcp.mjs"
|
|
20
|
+
"h5p-mcp": "./bin/h5p-mcp.mjs",
|
|
21
|
+
"h5p-mcp-app": "./bin/h5p-mcp-app.mjs"
|
|
21
22
|
},
|
|
22
23
|
"exports": {
|
|
23
24
|
"./package.json": "./package.json"
|
|
@@ -38,7 +39,7 @@
|
|
|
38
39
|
"dependencies": {
|
|
39
40
|
"@modelcontextprotocol/server": "^2.4.0",
|
|
40
41
|
"zod": "^4.6.7",
|
|
41
|
-
"@missing-elements/h5p-author": "^0.
|
|
42
|
+
"@missing-elements/h5p-author": "^0.18.0",
|
|
42
43
|
"@missing-elements/h5p-verify": "^1.6.1"
|
|
43
44
|
},
|
|
44
45
|
"devDependencies": {
|
|
@@ -52,6 +53,6 @@
|
|
|
52
53
|
},
|
|
53
54
|
"scripts": {
|
|
54
55
|
"test": "pnpm --filter @missing-elements/h5p-offline-player build && pnpm --filter @missing-elements/h5p-author exec node scripts/copy-skill.mjs && vitest run",
|
|
55
|
-
"typecheck": "tsc -p tsconfig.json"
|
|
56
|
+
"typecheck": "pnpm --filter @missing-elements/h5p-verify --filter @missing-elements/h5p-author run types && tsc -p tsconfig.json"
|
|
56
57
|
}
|
|
57
58
|
}
|