Repository navigation
feat(mcp): the app server as a Cloudflare Worker at an address of ours (#272) #273
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
ee0b607
feat(mcp): the app server as a Cloudflare Worker at an address of our…
alekswebnet dad4a36
fix(mcp): a references folder that is not the author package's is ref…
alekswebnet e0cd5be
docs(mcp): what a route's fail mode does over the free plan's limit, …
alekswebnet File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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`) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.