Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ packages/vscode/NOTICE.txt
# h5p-verify writes its report and screenshot to <package>.verify/ beside the package by default.
*.verify/

# The app server's Worker: what it carries, gathered by its `stage` script, and wrangler's own
# state on this computer.
apps/mcp-worker/staged/
.wrangler/

# Incremental build state
*.tsbuildinfo

Expand Down
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ by assumption, and asks a page for what only a page can do through the frame:

## Where things are, and whose rules

A pnpm workspace of ten packages and two apps. [`design/layout.md`](design/layout.md) maps the
A pnpm workspace of ten packages and three apps. [`design/layout.md`](design/layout.md) maps the
folders; in `design/`, `src/…` and `scripts/…` mean the player's unless a file says otherwise.

| Part | What it is | Rules |
Expand All @@ -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; and the app server, which plays an activity in a chat app's reply | [mcp](design/mcp.md) |
| `packages/mcp/`, `apps/mcp-worker/` | 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, with the Cloudflare Worker that hosts it | [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) |
Expand Down
23 changes: 23 additions & 0 deletions apps/mcp-worker/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "@missing-elements/h5p-mcp-worker",
"private": true,
"type": "module",
"scripts": {
"stage": "pnpm --filter @missing-elements/h5p-offline-player build:plan && pnpm --filter @missing-elements/h5p-author exec node scripts/copy-skill.mjs && node scripts/stage.mjs",
"dev": "pnpm stage && wrangler dev",
"deploy:worker": "pnpm stage && wrangler deploy",
"test": "pnpm stage && vitest run",
"typecheck": "pnpm --filter @missing-elements/h5p-author run types && tsc -p tsconfig.json"
},
"dependencies": {
"@missing-elements/h5p-author": "workspace:*",
"@missing-elements/h5p-libraries": "workspace:*",
"@missing-elements/h5p-mcp": "workspace:*"
},
"devDependencies": {
"@types/node": "^26.6.6",
"typescript": "^7.0.2",
"vitest": "^5.1.0",
"wrangler": "^4.167.0"
}
}
32 changes: 32 additions & 0 deletions apps/mcp-worker/scripts/stage.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Gathers what the Worker carries beside its code into staged/, which wrangler.jsonc attaches
// to it as modules: the library pack's parts, the author package's brief and type files (copied
// into that package from the skill first, by this package's `stage` script), and the card. Only
// what the server reads; the folder is written anew each time and is not in git.
import { cp, mkdir, readdir, rm, stat } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'

const staged = fileURLToPath(new URL('../staged/', import.meta.url))
/** Where an installed package's file is. @param {string} specifier */
const at = (specifier) => fileURLToPath(import.meta.resolve(specifier))

const parts = dirname(at('@missing-elements/h5p-libraries/parts/index.json'))
const references = dirname(at('@missing-elements/h5p-author/references/authoring.md'))
const card = join(dirname(at('@missing-elements/h5p-mcp/package.json')), 'lib', 'card.html')

await rm(staged, { recursive: true, force: true })
await mkdir(join(staged, 'references'), { recursive: true })
await cp(parts, join(staged, 'parts'), { recursive: true })
await cp(join(references, 'authoring.md'), join(staged, 'references', 'authoring.md'))
await cp(join(references, 'types'), join(staged, 'references', 'types'), { recursive: true })
await cp(card, join(staged, 'card.html'))

const names = async (/** @type {string} */ folder, /** @type {string} */ ending) => (await readdir(join(staged, folder))).filter((name) => name.endsWith(ending))
const [libraries, types] = [await names('parts', '.h5p'), await names(join('references', 'types'), '.md')]
if (!libraries.length || !types.length) throw new Error(`Nothing to carry: ${libraries.length} parts and ${types.length} type files in ${staged}`)
let bytes = 0
for (const name of await readdir(staged, { recursive: true })) {
const file = await stat(join(staged, name))
if (file.isFile()) bytes += file.size
}
console.log(`Staged ${libraries.length} parts, ${types.length} type files, the brief and the card: ${(bytes / 1048576).toFixed(1)} MB`)
46 changes: 46 additions & 0 deletions apps/mcp-worker/src/worker.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { readFileSync } from 'node:fs'
import { createApp } from '@missing-elements/h5p-mcp/app'
import mcp from '@missing-elements/h5p-mcp/package.json' with { type: 'json' }

/**
* The app server (`h5p-mcp-app`, design/mcp.md) as a Cloudflare Worker: the same handler, in a
* runtime with no package folders. What the server reads as it runs rides in the Worker and
* shows in its file system under `/bundle` (`wrangler.jsonc`, `scripts/stage.mjs`): the library
* pack's parts, the author package's type files and brief, and the card.
*
* It receives a chat's tool calls, an activity's source among them, and never a file. The server
* stores and logs nothing of a call, this file adds nothing, and the Worker's own logs are off
* in its config.
*/

/** Where a Worker's modules are files. */
const CARRIED = '/bundle'

/** @type {ReturnType<typeof createApp> | undefined} */
let app

export default {
/**
* @param {Request} request
* @returns {Promise<Response>}
*/
async fetch(request) {
let server
try {
// Started by the first call and kept while the Worker lives. One that failed to start is
// started again by the next call.
app ??= createApp({
version: mcp.version,
card: readFileSync(`${CARRIED}/card.html`, 'utf8'),
libraries: `${CARRIED}/parts`,
references: `${CARRIED}/references`
})
server = await app
} catch {
app = undefined
// Said plainly and with nothing of the failure in it: it is the Worker's, not the caller's.
return new Response('The server could not start\n', { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
}
return server.fetch(request)
}
}
104 changes: 104 additions & 0 deletions apps/mcp-worker/tests/worker.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { resolve } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { unstable_readConfig, unstable_startWorker } from 'wrangler'
import { createApp } from '@missing-elements/h5p-mcp/app'

/**
* The Worker as Cloudflare runs it: bundled by wrangler with what it carries, started in the
* Workers runtime on this computer, and asked over HTTP. The server's own rules are tested in
* the MCP package; these hold the Worker to answering as the server on a computer does, word for
* word, from files it reads in another runtime's file system, and its config to its logs off.
*/

const CONFIG = resolve(import.meta.dirname, '../wrangler.jsonc')
const META = { language: 'en', license: 'U', authors: [{ name: 'Unknown', role: 'Author' }] }
const QUIZ = { ...META, type: 'H5P.TrueFalse', title: 'Boiling point', params: { question: '<p>Water boils at 100 °C at sea level.</p>', correct: 'true' } }

type Asked = (request: Request) => Promise<Response>

let worker: Awaited<ReturnType<typeof unstable_startWorker>>
/** The Worker, and the server as Node runs it, each asked the same way. */
let hosted: Asked
let local: Asked
let server: Awaited<ReturnType<typeof createApp>>

/** One call of the protocol's, answered: its result, or the error it came back with. */
async function ask(asked: Asked, method: string, params: unknown = {}) {
const response = await asked(new Request('https://host.example/mcp', {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params })
}))
const text = await response.text()
return JSON.parse(text.split('\n').find((line) => line.startsWith('data: '))?.slice(6) ?? text).result
}

beforeAll(async () => {
worker = await unstable_startWorker({ config: CONFIG, dev: { server: { hostname: '127.0.0.1', port: 0 }, inspector: false, logLevel: 'error', watch: false } })
await worker.ready
const origin = await worker.url
hosted = (request) => fetch(new Request(new URL(new URL(request.url).pathname, origin), request))
server = await createApp()
local = (request) => server.fetch(request)
})

afterAll(async () => {
await worker?.dispose()
await server?.close()
})

describe('the app server as a Worker', () => {
it('names itself and its tools as the server on a computer does', async () => {
const hello = { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '0' } }
expect(await ask(hosted, 'initialize', hello)).toEqual(await ask(local, 'initialize', hello))
const { tools } = await ask(hosted, 'tools/list')
expect(tools.map((tool: { name: string }) => tool.name)).toEqual(['h5p_types', 'h5p_play'])
expect(tools).toEqual((await ask(local, 'tools/list')).tools)
})

it('reads the pack, the type files and the brief it carries', async () => {
// The list opens every content type's part, and carries the brief; a type with a file
// answers from it, and one without from the fields in its part.
for (const args of [{}, { type: 'H5P.TrueFalse' }, { type: 'H5P.Crossword' }]) {
const answer = await ask(hosted, 'tools/call', { name: 'h5p_types', arguments: args })
expect(answer.isError).toBeUndefined()
expect(answer).toEqual(await ask(local, 'tools/call', { name: 'h5p_types', arguments: args }))
}
})

it('checks a source, and refuses one, in the same words', async () => {
for (const source of [QUIZ, { type: 'H5P.TrueFalse' }]) {
const answer = await ask(hosted, 'tools/call', { name: 'h5p_play', arguments: { source } })
expect(answer).toEqual(await ask(local, 'tools/call', { name: 'h5p_play', arguments: { source } }))
}
expect((await ask(hosted, 'tools/call', { name: 'h5p_play', arguments: { source: QUIZ } })).content[0].text).toContain('The activity is checked and plays in the card: H5P.TrueFalse')
})

it('serves the same card at the same address, so a chat keeps one', async () => {
const { resources } = await ask(hosted, 'resources/list')
expect(resources[0].uri).toBe(server.cardUri)
expect(await ask(hosted, 'resources/read', { uri: server.cardUri })).toEqual(await ask(local, 'resources/read', { uri: server.cardUri }))
})

it('answers the endpoint and nothing else, and no body over 1 MB', async () => {
const at = (path: string, init?: RequestInit) => hosted(new Request(`https://host.example${path}`, init))
expect((await at('/')).status).toBe(200)
// What it carries is not served: the files are the Worker's own.
for (const path of ['/card.html', '/parts/index.json', '/bundle/card.html', '/references/authoring.md']) expect((await at(path)).status).toBe(404)
const big = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'h5p_play', arguments: { source: { pad: 'x'.repeat(1100_000) } } } })
expect((await at('/mcp', { method: 'POST', headers: { 'content-type': 'application/json' }, body: big })).status).toBe(413)
})

it('is configured to write no log of a call, with no store and one address', () => {
const config = unstable_readConfig({ config: CONFIG })
expect(config.observability).toMatchObject({ enabled: false })
expect(config.workers_dev).toBe(false)
expect(config.preview_urls).toBe(false)
expect(config.routes).toEqual([{ pattern: 'mcp.embed-my.org', custom_domain: true }])
// No store is bound to it: nothing it could keep a call in.
for (const store of ['kv_namespaces', 'r2_buckets', 'd1_databases', 'queues', 'durable_objects', 'analytics_engine_datasets', 'tail_consumers'] as const) {
const bound = (config as unknown as Record<string, unknown>)[store]
expect(Array.isArray(bound) ? bound : Object.values((bound ?? {}) as object).flat(), store).toHaveLength(0)
}
})
})
18 changes: 18 additions & 0 deletions apps/mcp-worker/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022"],
"types": ["node"],
"strict": true,
"noEmit": true,
"allowJs": true,
"checkJs": true,
"isolatedModules": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"skipLibCheck": true
},
"include": ["src/**/*.mjs", "scripts/**/*.mjs", "tests/**/*.ts", "vitest.config.ts"]
}
12 changes: 12 additions & 0 deletions apps/mcp-worker/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { defineConfig } from 'vitest/config'

// The Worker runs as Cloudflare runs it, in its runtime on this computer, which wrangler starts:
// a bundle of the server and the 15 MB it carries, built once for the file's tests.
export default defineConfig({
test: {
environment: 'node',
include: ['tests/**/*.test.ts'],
testTimeout: 120_000,
hookTimeout: 120_000
}
})
24 changes: 24 additions & 0 deletions apps/mcp-worker/wrangler.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "h5p-mcp",
"main": "src/worker.mjs",
"compatibility_date": "2026-11-01",
// The server's entry is Node's: it reads the files below with node:fs.
"compatibility_flags": ["nodejs_compat"],
// What the server reads as it runs rides in the Worker as modules, which its file system
// shows under /bundle: scripts/stage.mjs gathers them into staged/.
"find_additional_modules": true,
"base_dir": "staged",
"rules": [
{ "type": "Data", "globs": ["parts/*.h5p"], "fallthrough": true },
{ "type": "Text", "globs": ["parts/index.json", "references/**/*.md"], "fallthrough": true }
],
// Workers Logs off: no invocation log and no trace of a call is stored. The test holds the
// file to it. What Cloudflare counts for any Worker is not this setting's (design/mcp.md).
"observability": { "enabled": false },
"send_metrics": false,
// One address, ours: no workers.dev name beside it, and no preview addresses.
"workers_dev": false,
"preview_urls": false,
"routes": [{ "pattern": "mcp.embed-my.org", "custom_domain": true }]
}
2 changes: 2 additions & 0 deletions design/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ pnpm --filter @missing-elements/h5p-author sync:skill # the h5p-author skill's
pnpm --filter h5p-preview package # the VS Code extension's .vsix, from the player as pnpm build left it
pnpm --filter h5p-preview test:vscode # its suite in a VS Code it downloads; under xvfb-run on Linux
pnpm --filter h5p-preview screenshot # its listing's screenshot, images/preview.png, in that VS Code
pnpm --filter @missing-elements/h5p-mcp-worker dev # the app server's Worker in the Workers runtime, on this computer
pnpm --filter @missing-elements/h5p-mcp-worker deploy:worker # deploys it; after `pnpm --filter @missing-elements/h5p-mcp-worker exec wrangler login`
pnpm build:demo # the hosted demo into apps/demo/dist-demo/, what Vercel runs
pnpm demo:content # rebuild apps/demo/demo/content/*.h5p from their sources; needs the H5P hub
pnpm demo:og # re-render the social card, apps/demo/demo/og-image.png
Expand Down
7 changes: 5 additions & 2 deletions design/layout.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Layout

A pnpm workspace of ten packages and two apps. Nine packages are published to npm; the VS Code
A pnpm workspace of ten packages and three apps. Nine packages are published to npm; the VS Code
extension is a `.vsix`. Paths in `design/` are relative to their part: `src/…` and `scripts/…`
mean the player's unless a file says otherwise. `dist/`, `types/`, the player's `public/` and the
runtime's `index.js` are generated and not in git.
Expand Down Expand Up @@ -36,7 +36,8 @@ packages/author/ a playable .h5p from a short source: lib/build.mjs both b
scripts/ the skill's sync and copy, and build-tool.mjs the command line
as one file (dist/)
packages/mcp/ the local MCP server: bin/h5p-mcp.mjs the command, lib/server.mjs its four
tools, lib/folders.mjs the folders it may use
tools, lib/folders.mjs the folders it may use; and the app server:
bin/h5p-mcp-app.mjs, lib/app.mjs the handler, lib/card.html its card
packages/cmi5/ the element as a cmi5 AU: src/index.ts startCmi5, src/client.ts the protocol
packages/embed/ site/ the embed page and the SCORM page; lib/build.mjs the site,
lib/scorm*.mjs the SCORM zip in Node and in a page; scorm/ its launch page
Expand All @@ -47,6 +48,8 @@ apps/demo/ the dev server and the hosted site: index.html the player
partials/ the shared markup, scripts/ the builds and the sweep, sweep/ its files
apps/skills/ the skills' test project: author-verify, author-playback, to-scorm,
front-matter
apps/mcp-worker/ the app server as a Cloudflare Worker: src/worker.mjs, wrangler.jsonc its
Comment thread
alekswebnet marked this conversation as resolved.
Resolved
config, scripts/stage.mjs what it carries, gathered into staged/
skills/ the agent skills, at the root, where `npx skills add` looks
docs/ the README's longer sections, for integrators
scripts/ published.mjs, the check before a package is published that npm serves the
Expand Down
Loading