diff --git a/pkgs/mcpx/docs/home-example.md b/pkgs/mcpx/docs/home-example.md new file mode 100644 index 0000000000..afdce2a24a --- /dev/null +++ b/pkgs/mcpx/docs/home-example.md @@ -0,0 +1,40 @@ +# The home-page example: copy it or run it in the page + +The example on the home page is not a picture of code. It is the working +script from [`home-example/example.ts`](home-example/example.ts), and a +reader can do two things with it before installing anything is required +of them — and a third once it is. + +**Copy as mcpx exec.** One click puts a command on the clipboard that +runs the example against your own daemon and your own servers: + +```sh +mcpx exec "$(cat <<'MCPX_EOF' +const echoed = await tools.demo.echo({ message: "hello from a script" }); + +console.log("demo.echo:", String(echoed)); +MCPX_EOF +)" +``` + +The heredoc is quoted, which is the whole trick: an example full of +apostrophes, `$` signs and backticks arrives at `mcpx exec` byte for +byte, because `mcpx exec` takes its source as an argument and its stdin +belongs to the script. *Copy as script* puts the source itself on the +clipboard instead, for a file under `.mcpx/scripts/` and `mcpx run`. + +**Run it in the page.** The example is editable, and Run executes the +edited version in the browser tab. This is a simulation and the page +labels it as one: the script runs through the real generated client, but +its `POST /v1/call` is answered by a fake daemon in the page whose only +namespace is a mock `demo` server. It is the right tool for "what does +this code do" — change a line, see the output change — and the wrong one +for "what will this do against my servers", which is what the copy +button is for. + +What the simulation does not have: real MCP servers, the launcher, and +the runtime APIs (`Deno.*`, `node:fs`) a real run provides. Running an +example against your own daemon from the page is a later, opt-in stage; +running strangers' code on a hosted daemon is not planned at all. The +component, its mocks, and its regeneration script live in +[`home-example/`](home-example/README.md). diff --git a/pkgs/mcpx/docs/home-example/README.md b/pkgs/mcpx/docs/home-example/README.md new file mode 100644 index 0000000000..cf36d63923 --- /dev/null +++ b/pkgs/mcpx/docs/home-example/README.md @@ -0,0 +1,57 @@ +# The home-page example component + +Issue #1876, Approach C, stages 1–2. This directory is the example slot of +the mcpx home page, landed in the docs source because the page itself +(#1874) and the site build/deploy (#1941) have not landed yet — when they +do, the generator includes `component.html` where the example goes and +runs `generate-client.sh` as part of the build. Nothing here is a parallel +site. + +## What a reader gets + +- **Stage 1 — copy-as-command** (`copy-command.js`). Every docs example + can be copied two ways: *Copy as mcpx exec* (a quoted-heredoc command + that runs the snippet against the reader's real daemon; see the file + header for why the quoting has to be a heredoc) and *Copy as script* + (the source itself, plus `scriptCommands()` for the save-and-`mcpx run` + two-liner). +- **Stage 2 — run it in the page** (`component.html`, `run-example.js`). + The example is editable; Run executes it in the tab. The label says + **"Simulated — runs in your browser"**, because it is one: + - the script runs through a strip-only TypeScript transform + (`strip-types.js`) and is imported as a blob module; + - it talks to the **real generated client** — `client.ts`, emitted by + `mcpx client --ns demo` against the deterministic fixture server + (`internal/testsupport/fakemcp`), and `client.browser.js`, that same + file after Node's strip-only transform. Neither is hand-written; + regenerate both with `./generate-client.sh`; + - the client's one hot route, `POST /v1/call`, is answered by a fake + daemon (`fake-daemon.js`) from in-page mocks (`mocks.js`). `/v1/batch`, + `/v1/resource` and `/v1/artifacts` are not simulated and answer with + an honest error. +- **No-JS fallback**: the static highlighted example, unchanged. + +## Fidelity gaps (also stated on the page) + +- The only namespace is the mock `demo` fixture; its deterministic tools + are mirrored, the rest return an error naming the limitation. No real + MCP servers, no launcher placeholders, no `Deno.*`/`node:fs`. +- Mocks are computed from the same rules as the fixture where the fixture + is deterministic (echo, open/state/wipe, structured, boom, fancy-name). + +## Stage 3 is not here + +Running against the reader's own daemon (a `daemon.cors` allow-list +setting, a fixed `daemon.port`, Chrome Local Network Access handling) is +excluded — a separate later follow-on. A hosted public daemon is rejected +in the issue, permanently. This component makes no daemon changes. + +## Verify + +```sh +node smoke-test.mjs # shell round-trip for stage 1; end-to-end run for stage 2 +./generate-client.sh # regenerate client.ts / client.browser.js from the fixture +``` + +#1941 should wire `smoke-test.mjs` into the docs CI pipeline; until then +it is the recorded smoke check for this component. diff --git a/pkgs/mcpx/docs/home-example/client.browser.js b/pkgs/mcpx/docs/home-example/client.browser.js new file mode 100644 index 0000000000..1ddef8e49f --- /dev/null +++ b/pkgs/mcpx/docs/home-example/client.browser.js @@ -0,0 +1,1422 @@ +// Generated from client.ts by strip-client.mjs (strip-only). Do not edit; +// regenerate with generate-client.sh. +// Generated by mcpx. Do not edit; regenerated whenever tool schemas change. +// +// Each function posts one tools/call to the local mcpx daemon, which owns the +// MCP server processes. Results are returned already unwrapped: a text-only +// result becomes a string, a structured result becomes the parsed object. +// Reach for .raw on the returned value when you need the full MCP envelope. + +const DEFAULT_ENDPOINT = "http://127.0.0.1:41591"; +const DEFAULT_SESSION = ""; + +function env(name ) { + // Works on Deno, Bun and Node without assuming any of them. + try { + const d = (globalThis ).Deno; + if (d?.env?.get) return d.env.get(name) ?? ""; + } catch { /* permission denied: fall through */ } + try { + const p = (globalThis ).process; + if (p?.env) return p.env[name] ?? ""; + } catch { /* not Node-like */ } + return ""; +} + +// The session and endpoint are read at run time rather than baked in, so that +// concurrent runs sharing one generated client file still get their own +// session. That isolation is what gives each run its own browser in +// session-mode pools. +const ENDPOINT = env("MCPX_ENDPOINT") || DEFAULT_ENDPOINT; +const SESSION = env("MCPX_SESSION") || DEFAULT_SESSION; + +/** + * The daemon's unix socket, when one is available. + * + * Measured against the same daemon: a warm socket answers in about 0.17ms, + * loopback TCP in about 0.65ms. Small per call, but a script making a + * thousand calls spends half a second on it, and the socket's filesystem + * permissions are a better access control than an open port. + * + * Each runtime spells a unix-socket fetch differently -- Deno a custom HTTP + * client, Bun an option on fetch, Node an agent on http -- so the choice is + * made once here and every call goes through it. When none works, or no + * socket is named, it falls back to the TCP endpoint every runtime supports. + */ +const SOCKET = env("MCPX_SOCKET"); + + + +const makeFetcher = () => { + const g = globalThis ; + if (!SOCKET) return { fetch: (u, i) => fetch(u, i), via: "tcp" }; + + // Deno: a client whose transport is the socket. + if (g.Deno?.createHttpClient) { + try { + const client = g.Deno.createHttpClient({ proxy: { transport: "unix", path: SOCKET } }); + return { fetch: (u, i) => fetch(u, { ...i, client } ), via: "unix" }; + } catch { + /* an older Deno; fall through to TCP */ + } + } + // Bun: fetch takes the socket directly. + if (g.Bun) { + return { fetch: (u, i) => fetch(u, { ...i, unix: SOCKET } ), via: "unix" }; + } + // Node's fetch cannot address a socket without undici, which is not + // guaranteed to be importable here. TCP is correct and nearly as fast. + return { fetch: (u, i) => fetch(u, i), via: "tcp" }; +}; + +const TRANSPORT = makeFetcher(); + +/** Where calls are going, for a script that wants to know. */ +export const transport = () => TRANSPORT.via; + +/** The base URL to put in front of a path, given the transport. */ +const base = () => (TRANSPORT.via === "unix" ? "http://mcpx" : ENDPOINT); + +/** A filesystem location, as given and as fully resolved. */ + + + + + + + +function realpath(p ) { + if (!p) return p; + try { + const d = (globalThis ).Deno; + if (d?.realPathSync) return d.realPathSync(p); + } catch { /* not Deno, or denied */ } + try { + // Bun and Node both expose node:fs; require is available in Bun/CJS and + // createRequire covers the rest without a static import. + const req = (globalThis ).require ?? + (globalThis ).process?.getBuiltinModule?.bind((globalThis ).process); + const fs = req ? req("node:fs") : undefined; + if (fs?.realpathSync) return fs.realpathSync(p); + } catch { /* fall through */ } + return p; +} + +function pair(p ) { + return { path: p, real: realpath(p) }; +} + +function builtin(name ) { + try { + const g = globalThis ; + const req = g.require ?? g.process?.getBuiltinModule?.bind(g.process); + return req ? req(name) : undefined; + } catch { + return undefined; + } +} + +function permissionDenied(kind , path ) { + const target = path ? " " + String(path) : ""; + const err = new Error("Requires " + kind + " access" + target); + (err ).name = "PermissionDenied"; + return err; +} + +function installDenoCompat() { + const g = globalThis ; + const d = g.Deno ??= {}; + d.args ??= g.process?.argv?.slice(2) ?? []; + if (typeof d.exit !== "function" && typeof g.process?.exit === "function") { + d.exit = (code ) => g.process.exit(code); + } + if (!d.env?.get) { + d.env = { + get(name ) { + return g.process?.env?.[name]; + }, + }; + } + if (typeof d.inspect !== "function") { + if (typeof g.Bun?.inspect === "function") { + d.inspect = (v , opts ) => + g.Bun.inspect(v, opts); + } else { + const util = builtin("node:util"); + if (typeof util?.inspect === "function") { + d.inspect = (v , opts ) => + util.inspect(v, { colors: false, depth: 4, ...opts }); + } + } + } + if (typeof d.readTextFileSync !== "function") { + d.readTextFileSync = (path ) => { + if (env("MCPX_ALLOW_READ") !== "1") throw permissionDenied("read", path); + const fs = builtin("node:fs"); + if (!fs?.readFileSync) throw new Error("readTextFileSync is unavailable in this runtime"); + return fs.readFileSync(path, "utf8"); + }; + } + if (typeof d.readTextFile !== "function") { + d.readTextFile = async (path ) => { + if (env("MCPX_ALLOW_READ") !== "1") throw permissionDenied("read", path); + const fsp = builtin("node:fs/promises"); + if (typeof fsp?.readFile === "function") return await fsp.readFile(path, "utf8"); + return d.readTextFileSync(path); + }; + } +} + +function fromFileUrl(url ) { + if (!url.startsWith("file://")) return url; + const withoutScheme = decodeURIComponent(url.slice("file://".length)); + // file:///abs on unix; strip a leading host component if one is present. + return withoutScheme.startsWith("/") ? withoutScheme : "/" + withoutScheme.replace(/^[^/]*\//, ""); +} + +/** + * Where things are, from the point of view of any file in the import graph. + * + * These come from the environment rather than from module scope, so a script + * three imports deep sees the same cwd and entry as the file the user + * actually named. Use here(import.meta) for the current file. + */ +export const paths = { + /** The directory the user ran mcpx from. */ + cwd: pair(env("MCPX_CWD")), + /** The script mcpx was asked to run. Empty for mcpx exec. */ + entry: pair(env("MCPX_ENTRY")), + /** This generated client module. */ + client: pair(env("MCPX_CLIENT")), + /** The config file in effect, if any. */ + config: pair(env("MCPX_CONFIG_PATH")), + /** Directories searched for named scripts, nearest first. */ + scriptDirs: (env("MCPX_SCRIPT_DIRS") || "").split(":").filter(Boolean), +}; + +/** + * The file this is called from. + * + * import { here } from "./mcpx-client.ts"; + * const self = here(import.meta); // { path, real } + * + * A module-level constant cannot do this: it would resolve once, in the + * client, and every importer would see the client's own path. + */ +export function here(meta ) { + return pair(fromFileUrl(meta.url)); +} + +/** The directory containing the file this is called from. */ +export function hereDir(meta ) { + const p = fromFileUrl(meta.url); + const dir = p.slice(0, Math.max(0, p.lastIndexOf("/"))) || "/"; + return pair(dir); +} + + + + + + + + + + + + + + + + + + + +/** + * The value a tool call resolves to. + * + * It behaves as the useful part of the result (parsed structured content, or + * the concatenated text) while still carrying the full envelope on .raw. + */ + + +/** + * What mcpx worked out about a call a server refused: the argument at fault, + * what changed in the tool's schema and when, and the smallest call that works. + */ + + + + + + + + + + +export class ToolError extends Error { + // Written as plain fields rather than constructor parameter properties: + // Node's type-stripping mode erases types without transforming code, and + // parameter properties need a transform. Plain fields run everywhere. + server ; + tool ; + raw ; + diagnostics ; + + constructor(message , server , tool , raw ) { + super(message); + this.name = "ToolError"; + this.server = server; + this.tool = tool; + this.raw = raw; + } +} + +function attachRaw (value , raw ) { + if (value !== null && typeof value === "object") { + try { + Object.defineProperty(value, "raw", { value: raw, enumerable: false, configurable: true }); + } catch { /* frozen object: leave it alone */ } + return value; + } + // Primitives cannot carry properties; box strings so .raw still works. + if (typeof value === "string") { + const boxed = new String(value) ; + Object.defineProperty(boxed, "raw", { value: raw, enumerable: false, configurable: true }); + return boxed; + } + return value; +} + +function unwrap(server , tool , raw ) { + if (raw && raw.isError) { + const text = (raw.content ?? []) + .filter((c) => c.type === "text" && typeof c.text === "string") + .map((c) => c.text) + .join("\n"); + throw new ToolError(text || `${server}.${tool} returned isError`, server, tool, raw); + } + if (raw && raw.structuredContent !== undefined) { + return attachRaw(raw.structuredContent , raw); + } + const blocks = raw?.content ?? []; + const texts = blocks.filter((c) => c.type === "text" && typeof c.text === "string"); + if (texts.length === blocks.length && texts.length > 0) { + const joined = texts.map((c) => c.text ).join("\n"); + // Servers commonly return JSON as text; hand back the parsed value when + // it parses cleanly, since that is almost always what the script wants. + const t = joined.trim(); + if ((t.startsWith("{") && t.endsWith("}")) || (t.startsWith("[") && t.endsWith("]"))) { + try { + return attachRaw(JSON.parse(t) , raw); + } catch { /* not JSON after all */ } + } + return attachRaw(joined , raw); + } + return attachRaw(blocks , raw); +} + +async function __call(server , tool , args ) { + let resp ; + try { + resp = await TRANSPORT.fetch(base() + "/v1/call", { + method: "POST", + headers: { + "content-type": "application/json", + "x-mcpx-session": SESSION, + "x-mcpx-call": SESSION, + "x-mcpx-cwd": env("MCPX_CWD"), + "x-mcpx-pid": env("MCPX_PID"), + "x-mcpx-parent-session": env("MCPX_PARENT_SESSION_ID"), + "x-mcpx-ephemeral": env("MCPX_EPHEMERAL"), + "x-mcpx-run": env("MCPX_RUN"), + "x-mcpx-input": env("MCPX_INPUT"), + }, + body: JSON.stringify({ server, tool, args: args ?? {} }), + }); + } catch (e) { + throw new ToolError( + `cannot reach the mcpx daemon at ${ENDPOINT}: ${(e ).message}`, + server, + tool, + ); + } + const body = await resp.json().catch(() => ({ error: `bad response (http ${resp.status})` })); + if (resp.status === 202 && body.inputRequired) { + // The server stopped to ask something and nothing in this run can + // answer it (MCPX_INPUT=report, set by mcpx exec and mcpx run). Exiting + // 75 rather than throwing: a script that catches ToolError would + // otherwise carry on as if the call had merely failed, and the caller + // would never learn there is a question waiting. + writeStderr("mcpx: " + String(body.inputRequired.text ?? "").trimEnd()); + const g = globalThis ; + if (typeof g.Deno?.exit === "function") g.Deno.exit(75); + if (typeof g.process?.exit === "function") g.process.exit(75); + throw new ToolError(`${server}.${tool} is waiting for input`, server, tool, body); + } + if (!resp.ok || body.error) { + const err = new ToolError(body.error ?? `http ${resp.status}`, server, tool, body); + if (Array.isArray(body.diagnostics)) err.diagnostics = body.diagnostics; + throw err; + } + return unwrap(server, tool, body.result ); +} + + + +/** Structured values attached to a log record. */ + + +const LOG_SENTINEL = "\u001emcpx\u001e"; + +const LEVEL_ORDER = { debug: 0, info: 1, warn: 2, error: 3 }; + +function levelFrom(name , fallback ) { + const n = LEVEL_ORDER[name.trim().toLowerCase() ]; + return n === undefined ? fallback : n; +} + +// The active threshold, so a filtered call costs a comparison instead of a +// JSON encode and a write. The runner passes the same value it will filter on, +// which keeps the two ends from disagreeing. +const MIN_LEVEL = levelFrom(env("MCPX_LOG_LEVEL"), LEVEL_ORDER.info); + +/** + * Levels whose records carry a call site. + * + * Capture costs about 5 microseconds -- building the stack, not reading it -- + * which is roughly fifty times the cost of the record itself. Paying that on + * every info line is waste; paying it on a warning is the moment you most want + * to know where it came from. So the default traces warn and above, and + * MCPX_LOG_SOURCE widens it to everything. + */ +const SOURCE_LEVELS = env("MCPX_LOG_SOURCE") === "1" + ? LEVEL_ORDER.debug + : env("MCPX_LOG_SOURCE") === "0" + ? Number.POSITIVE_INFINITY + : levelFrom(env("MCPX_LOG_SOURCE"), LEVEL_ORDER.warn); + +function writeStderr(line ) { + const d = (globalThis ).Deno; + if (d?.stderr?.writeSync) { + d.stderr.writeSync(new TextEncoder().encode(line + "\n")); + return; + } + const p = (globalThis ).process; + if (p?.stderr?.write) { + p.stderr.write(line + "\n"); + return; + } + console.error(line); +} + +/** A plain data object, as opposed to an Error, an array or a primitive. */ +function isAttrs(v ) { + return typeof v === "object" && v !== null && !Array.isArray(v) && + !(v instanceof Error) && Object.getPrototypeOf(v) === Object.prototype; +} + +function formatFrames(name , message , frames ) { + const head = message ? name + ": " + message : name; + const body = frames.map((f) => { + const at = [f.file, f.line, f.column].filter((x) => x !== undefined).join(":"); + return " at " + (f.function ? f.function + " (" + at + ")" : at); + }); + return [head, ...body].join("\n"); +} + +function describeError(e ) { + // Both forms are wanted: the string is what a human reads, the frames are + // what a query groups by. They cannot both be taken from the Error, because + // V8 memoises whatever prepareStackTrace returned the first time .stack is + // touched -- ask for one and the other is gone. So frames are captured and + // the string is rendered from them. + const frames = errorFrames(e, 16); + const stack = frames.length ? formatFrames(e.name, e.message, frames) : ( + typeof e.stack === "string" ? e.stack : "" + ); + return { + name: e.name, + message: e.message, + ...(stack ? { stack } : {}), + ...(frames.length ? { frames } : {}), + ...((e ).cause !== undefined ? { cause: safeInspect((e ).cause) } : {}), + }; +} + +/** One frame of a captured stack. */ + + + + + + + + + + +/** + * Capture a stack as structured frames. + * + * V8 exposes Error.prepareStackTrace, which hands back CallSite objects + * instead of a formatted string. It is not in any standard, but Deno, Node and + * Bun are all V8 or JSC-with-the-same-shim, and all three were verified to + * support it. Parsing the string form is the fallback, and it is strictly + * worse: it loses async and native flags and breaks on any path containing the + * characters the format uses as delimiters. + */ +export function captureFrames(skip = 0, limit = 32) { + const E = Error ; + const previous = E.prepareStackTrace; + const previousLimit = E.stackTraceLimit; + try { + E.stackTraceLimit = skip + limit + 4; + E.prepareStackTrace = (_e , sites ) => + sites.map((s) => { + const f = {}; + const file = s.getFileName?.(); + if (file) f.file = String(file).replace(/^file:\/\//, ""); + const line = s.getLineNumber?.(); + if (typeof line === "number") f.line = line; + const col = s.getColumnNumber?.(); + if (typeof col === "number") f.column = col; + const fn = s.getFunctionName?.(); + if (fn) f.function = fn; + const tn = s.getTypeName?.(); + if (tn) f.type = tn; + if (s.isAsync?.()) f.async = true; + if (s.isNative?.()) f.native = true; + return f; + }); + const holder = {}; + E.captureStackTrace?.(holder, captureFrames); + const frames = holder.stack ?? (new Error() ).stack ?? []; + return Array.isArray(frames) ? frames.slice(skip, skip + limit) : []; + } catch { + return []; + } finally { + E.prepareStackTrace = previous; + E.stackTraceLimit = previousLimit; + } +} + +/** The frames of an Error, structured, without re-throwing it. */ +export function errorFrames(err , limit = 32) { + const E = Error ; + const previous = E.prepareStackTrace; + try { + E.prepareStackTrace = (_e , sites ) => + sites.map((s) => { + const f = {}; + const file = s.getFileName?.(); + if (file) f.file = String(file).replace(/^file:\/\//, ""); + const line = s.getLineNumber?.(); + if (typeof line === "number") f.line = line; + const fn = s.getFunctionName?.(); + if (fn) f.function = fn; + if (s.isAsync?.()) f.async = true; + return f; + }); + // Reading .stack re-runs prepareStackTrace against the captured sites. + const frames = (err ).stack; + return Array.isArray(frames) ? frames.slice(0, limit) : []; + } catch { + return []; + } finally { + E.prepareStackTrace = previous; + } +} + +/** + * Where the call came from. + * + * Only called when the level warrants it, because capturing the stack is the + * expensive half. + */ +function callSite() { + const frames = captureFrames(0, 8).filter((f) => !(f.file ?? "").includes("mcpx-client")); + const top = frames[0]; + if (!top) return undefined; + return { + ...(top.file ? { "source.file": top.file } : {}), + ...(top.line ? { "source.line": top.line } : {}), + ...(top.column ? { "source.column": top.column } : {}), + ...(top.function ? { "source.function": top.function } : {}), + }; +} + +function send(kind , payload ) { + writeStderr(LOG_SENTINEL + JSON.stringify({ kind, ts: new Date().toISOString(), ...payload })); +} + +function emitRecord( + level , + bound , + msg , + rest , + fileOnly = false, +) { + // Short-circuit before any work. A debug call in a loop should cost a + // comparison when nothing will print. + const n = LEVEL_ORDER[level]; + if (n < MIN_LEVEL) return; + + let attrs = { ...bound }; + const extra = []; + for (const [i, v] of rest.entries()) { + if (i === 0 && isAttrs(v)) { + Object.assign(attrs, v); + continue; + } + extra.push(v instanceof Error ? describeError(v) : v); + } + if (extra.length > 0) attrs.args = extra; + if (n >= SOURCE_LEVELS) Object.assign(attrs, callSite()); + + const hasTemplate = msg.includes("{"); + send("log", { + level, + msg, + ...(hasTemplate ? { template: msg } : {}), + ...(fileOnly ? { fileOnly: true } : {}), + ...(Object.keys(attrs).length > 0 ? { attrs } : {}), + }); +} + +/** + * A logger, optionally carrying attributes bound by with(). + * + * Callable directly: log("message") is log.info("message"), because the + * overwhelmingly common case should not need a method name. + */ + + + + + + + + + + + + + + + + + + + + + +function makeLogger(bound ) { + const fn = ((msg , ...rest ) => emitRecord("info", bound, msg, rest)) ; + return Object.assign(fn, { + debug: (msg , ...rest ) => emitRecord("debug", bound, msg, rest), + info: (msg , ...rest ) => emitRecord("info", bound, msg, rest), + warn: (msg , ...rest ) => emitRecord("warn", bound, msg, rest), + error: (msg , ...rest ) => emitRecord("error", bound, msg, rest), + with: (attrs ) => makeLogger({ ...bound, ...attrs }), + enabled: (level ) => LEVEL_ORDER[level] >= MIN_LEVEL, + }); +} + +/** + * Structured logging for scripts. + * + * A message may carry {placeholders} filled from the attributes, and {{x}} + * writes a literal {x}: + * + * log.info("fetched {count} pages in {ms}ms", { count: 3, ms: 412 }); + * + * The first argument after the message is treated as attributes when it is a + * plain object. Anything else, and anything after it, is collected into an + * "args" array, so console-style calls still carry their values rather than + * being dropped: + * + * log.error("upload failed", err); // err becomes args[0] + * log.debug("state", { id }, "extra", 42); // id is an attribute + * + * Both the rendered message and its template are kept, so output reads as + * prose and still groups by shape. stdout stays clear for results; this is + * stderr. + */ +export const log = makeLogger({}); + +/** + * Stream a result before the script finishes. + * + * A script's return value is one answer delivered at the end. emit() is for + * many answers delivered as they are found: a long crawl, a per-file report, a + * progress feed a caller can act on without waiting. + * + * for (const file of files) emit({ file, findings: await scan(file) }); + * + * Each value is written immediately. In ordinary use it lands on stdout as one + * JSON line per call; under mcpx --json run the values are collected into + * the envelope's results array in order. Either way the consumer sees them + * in sequence rather than as one blob at the end. + */ +export function emitResult(value ) { + send("result", { value }); +} + +export { emitResult as emit }; + +/** + * Route console output through the record stream. + * + * console.log keeps going to stdout, because that is the script's result and + * redirecting it would change what a caller reads. It is *also* mirrored as a + * debug record so it lands in the durable log alongside everything else -- + * otherwise the one thing a script actually printed is the one thing missing + * when you go looking afterwards. + * + * console.error/warn/info/debug become records outright: they are diagnostics, + * and leaving them as bare stderr text means they miss enrichment, formatting + * and the log file. + */ +export function captureConsole() { + const c = globalThis.console ; + if (!c || c.__mcpxWrapped) return; + const original = {}; + for (const k of Object.keys(c)) { + if (typeof c[k] === "function") original[k] = c[k].bind(c); + } + + let depth = 0; + + // Render the message the way the runtime would have. A caller who wrote + // console.info({a:1}) expects to read "{ a: 1 }", not the JSON encoding -- + // the structured copy of the value is already in args, so the message is + // free to be the human form. + const g = globalThis ; + const nodeInspect = builtin("node:util")?.inspect; + const native = + env("MCPX_RUNTIME") === "node" && typeof nodeInspect === "function" + ? (v) => nodeInspect(v) + : typeof g.Deno?.inspect === "function" + ? (v) => g.Deno.inspect(v, { colors: false, depth: 4 }) + : typeof g.Bun?.inspect === "function" + ? (v) => g.Bun.inspect(v) + : typeof nodeInspect === "function" + ? (v) => nodeInspect(v) + : undefined; + const one = (a ) => { + if (typeof a === "string") return a; + if (native) { + try { + return native(a); + } catch { + /* fall through */ + } + } + return safeInspect(a); + }; + // Format specifiers, because a script that writes console.info("%s: %d", + // name, n) expects to read "alice: 42". Dropping the substitution and + // printing the template beside its arguments is the kind of difference that + // makes a captured console feel broken rather than redirected. + // + // Matches the runtimes: substitution happens only when there are arguments + // to substitute, leftover specifiers stay as written, and surplus arguments + // are appended. + const FORMAT = /%[sdifjoOc%]/g; + const applyFormat = (template , rest ) => { + let i = 0; + const text = template.replace(FORMAT, (spec) => { + if (spec === "%%") return "%"; + if (i >= rest.length) return spec; + const v = rest[i++]; + switch (spec) { + case "%s": + return typeof v === "string" ? v : one(v); + case "%d": + case "%i": { + if (typeof v === "bigint") return String(v); + const n = Number(v); + return Number.isNaN(n) ? "NaN" : String(Math.trunc(n)); + } + case "%f": + return String(Number(v)); + case "%j": + return safeInspect(v); + case "%o": + case "%O": + return one(v); + case "%c": + // Styling has no meaning outside a browser. The argument is still + // consumed, which is what keeps the remaining substitutions lined + // up with their specifiers. + return ""; + } + return spec; + }); + return [text, rest.slice(i)]; + }; + + const render = (args ) => { + const pad = " ".repeat(depth); + if (args.length > 1 && typeof args[0] === "string" && FORMAT.test(args[0] )) { + FORMAT.lastIndex = 0; + const [text, rest] = applyFormat(args[0] , args.slice(1)); + return pad + [text, ...rest.map(one)].join(" "); + } + FORMAT.lastIndex = 0; + return pad + args.map(one).join(" "); + }; + + // Keep the original name on every replacement. Something reading + // console.info.name should still see "info"; losing it breaks introspection + // for no gain. + const patch = (name , fn ) => { + Object.defineProperty(fn, "name", { value: name, configurable: true }); + c[name] = fn; + }; + + // The five that carry a level map onto it directly. console.info really is + // log.info; there is no separate concept to reconcile. + const direct = { + info: "info", + warn: "warn", + error: "error", + debug: "debug", + dir: "info", + dirxml: "info", + table: "info", + }; + for (const [name, level] of Object.entries(direct)) { + patch(name, (...args ) => emitRecord(level, { console: name }, render(args), [])); + } + + // stdout is the script's result, so console.log keeps going there. The + // record exists so the durable log has it too, and is file-only so the + // terminal does not show the same line twice. + patch("log", (...args ) => { + original.log?.(...args); + emitRecord("debug", { console: "log" }, render(args), [], true); + }); + + // console.trace is a stack request; honour it rather than dropping the part + // that was asked for. + patch("trace", (...args ) => { + emitRecord("debug", { console: "trace", frames: captureFrames(1, 16) }, render(args), []); + }); + + patch("assert", (cond , ...args ) => { + if (cond) return; + emitRecord("error", { console: "assert" }, render(args.length ? args : ["assertion failed"]), []); + }); + + // Grouping is presentation, and a structured record has no nesting to show. + // Indentation is preserved so output still reads as the author intended. + patch("group", (...args ) => { + if (args.length) emitRecord("info", { console: "group" }, render(args), []); + depth++; + }); + // A record stream has nothing to collapse, so collapsed groups are groups. + patch("groupCollapsed", (...args ) => c.group(...args)); + patch("groupEnd", () => { + depth = Math.max(0, depth - 1); + }); + + // indentLevel is a property rather than a method, and reading it is how some + // libraries decide their own wrapping. Keep it truthful. + Object.defineProperty(c, "indentLevel", { + get: () => depth, + set: (v ) => { + depth = Math.max(0, Math.trunc(Number(v) || 0)); + }, + configurable: true, + }); + + // console.clear wipes a terminal. It must not wipe a durable log, so the + // request is recorded, the indent is reset, and the screen is left alone + // unless nothing is capturing it. + patch("clear", () => { + depth = 0; + emitRecord("debug", { console: "clear" }, "console.clear()", [], true); + }); + + // Devtools profiling markers. There is no profiler here, but dropping the + // call silently loses a deliberate annotation, so they become records. + for (const name of ["profile", "profileEnd", "timeStamp"]) { + patch(name, (...args ) => { + emitRecord("debug", { console: name }, render(args.length ? args : [name + "()"]), [], true); + }); + } + + const counters = new Map (); + patch("count", (label = "default") => { + const n = (counters.get(label) ?? 0) + 1; + counters.set(label, n); + emitRecord("debug", { console: "count", label, count: n }, label + ": " + n, []); + }); + patch("countReset", (label = "default") => { + counters.delete(label); + }); + + const timers = new Map (); + patch("time", (label = "default") => { + timers.set(label, performance.now()); + }); + patch("timeLog", (label = "default", ...args ) => { + const started = timers.get(label); + if (started === undefined) return; + const ms = performance.now() - started; + emitRecord("debug", { console: "timeLog", label, ms }, + label + ": " + ms.toFixed(3) + "ms " + render(args), []); + }); + patch("timeEnd", (label = "default") => { + const started = timers.get(label); + if (started === undefined) return; + timers.delete(label); + const ms = performance.now() - started; + emitRecord("debug", { console: "timeEnd", label, ms }, + label + ": " + ms.toFixed(3) + "ms", []); + }); + + c.__mcpxWrapped = true; + c.__mcpxOriginal = original; +} + +/** Undo captureConsole, for a script that wants the real console back. */ +export function releaseConsole() { + const c = globalThis.console ; + if (!c?.__mcpxWrapped) return; + for (const [k, fn] of Object.entries(c.__mcpxOriginal ?? {})) { + if (fn) c[k] = fn; + } + delete c.__mcpxWrapped; + delete c.__mcpxOriginal; +} + +function safeInspect(v ) { + if (v instanceof Error) return v.stack ?? String(v); + try { + return JSON.stringify(v) ?? String(v); + } catch { + return String(v); + } +} + +/** + * Put the standard surface on globalThis. + * + * A script that imports is easier to read and gives an editor something to + * work with; a script written like a shell one-liner should not have to. Both + * work: the launcher installs these before importing the module, and the + * generated declarations tell an editor they exist. + */ +/** One tool, as search returns it. */ + + + + + + + + + + + +/** + * Find tools by name or description, from inside a script. + * + * Without this, discovering a tool means ending the script, running + * "mcpx search", reading the result, and writing a new script. That round + * trip is the expensive part -- for a model it is a whole turn, and the + * intermediate result passes through its context on the way. + * + * Synchronous, because everything it searches is already in this file. A + * promise here would only be a promise of work already done. + */ +export function search(query , limit = 20) { + const words = String(query).toLowerCase().split(/\s+/).filter(Boolean); + if (words.length === 0) return []; + + const scored = []; + for (const [ns, group] of Object.entries(tools)) { + for (const [name, fn] of Object.entries(group )) { + if (typeof fn !== "function") continue; + const meta = __toolMeta[ns]?.[name] ?? { description: "", params: [], required: [] }; + const hay = (ns + " " + name + " " + meta.description).toLowerCase(); + + let score = 0; + for (const w of words) { + if (!hay.includes(w)) { + score = -1; + break; + } + // A word in the name is worth more than a word in the prose. A tool + // called "grep" beats one whose description merely mentions grepping. + score += (ns + " " + name).toLowerCase().includes(w) ? 10 : 1; + } + if (score < 0) continue; + scored.push({ + score, + match: { + namespace: ns, + tool: name, + call: fn , + description: meta.description, + params: meta.params, + required: meta.required, + }, + }); + } + } + scored.sort((a, b) => b.score - a.score || a.match.tool.localeCompare(b.match.tool)); + return scored.slice(0, limit).map((s) => s.match); +} + +/** + * The signature of one tool, or of a whole namespace. + * + * The companion to search: found something, now what does it take. Returns + * text because that is what it is for -- reading, or printing when a script + * is exploring rather than doing. + */ +export function describe(name ) { + const parts = String(name).split("."); + const ns = parts[0]; + const tool = parts[1]; + const group = __toolMeta[ns]; + if (!group) { + return "no namespace " + JSON.stringify(ns) + + "; there is " + Object.keys(tools).join(", "); + } + const render = (t ) => { + const m = group[t]; + if (!m) return " " + t + "(...)"; + const args = m.params + .map((p) => (m.required.indexOf(p) >= 0 ? p : p + "?")) + .join(", "); + const head = " " + ns + "." + t + "({ " + args + " })"; + return m.description ? head + "\n " + m.description : head; + }; + if (!tool) { + return Object.keys(group).sort().map(render).join("\n"); + } + return render(tool); +} + +export function installGlobals() { + const g = globalThis ; + installDenoCompat(); + g.log ??= log; + g.emit ??= emitResult; + g.tools ??= tools; + g.call ??= call; + g.batch ??= batch; + g.readResource ??= readResource; + g.artifact ??= artifact; + g.ToolError ??= ToolError; + g.paths ??= paths; + g.here ??= here; + g.hereDir ??= hereDir; + g.releaseConsole ??= releaseConsole; + g.captureFrames ??= captureFrames; + g.errorFrames ??= errorFrames; + g.search ??= search; + g.transport ??= transport; + g.describe ??= describe; + for (const [name, ns] of Object.entries(tools)) { + g[name] ??= ns; + if (typeof ns === "object" && ns !== null) { + for (const [fnName, fn] of Object.entries(ns)) g[fnName] ??= fn; + } + } +} + +/** Call any tool by name, including ones added after this client was generated. */ +export async function call(serverOrTool , toolOrArgs , args ) { + if (arguments.length === 1 || (arguments.length === 2 && (typeof toolOrArgs === "object" || toolOrArgs === undefined))) { + return __call("", serverOrTool, toolOrArgs ?? {}); + } + return __call(serverOrTool, String(toolOrArgs), args ?? {}); +} + +/** Execute multiple tool calls in a single turn. */ +export async function batch( + calls , + options +) { + const resp = await TRANSPORT.fetch(base() + "/v1/batch", { + method: "POST", + headers: { + "content-type": "application/json", + "x-mcpx-session": SESSION, + "x-mcpx-call": SESSION, + "x-mcpx-cwd": env("MCPX_CWD"), + "x-mcpx-pid": env("MCPX_PID"), + "x-mcpx-parent-session": env("MCPX_PARENT_SESSION_ID"), + }, + body: JSON.stringify({ + calls: calls.map((c) => ({ + server: c.server ?? c.namespace ?? "", + tool: c.tool, + args: c.args ?? c.arguments ?? {}, + })), + stopOnError: options?.stopOnError ?? true, + parallel: options?.parallel ?? false, + }), + }); + const body = await resp.json(); + if (!resp.ok || body.error) throw new Error(body.error ?? ("http " + resp.status)); + return body.results ?? []; +} + +/** Read an MCP resource URI. */ +export async function readResource(server , uri ) { + const resp = await TRANSPORT.fetch(base() + "/v1/resource", { + method: "POST", + headers: { + "content-type": "application/json", + "x-mcpx-session": SESSION, + "x-mcpx-call": SESSION, + "x-mcpx-cwd": env("MCPX_CWD"), + "x-mcpx-pid": env("MCPX_PID"), + "x-mcpx-parent-session": env("MCPX_PARENT_SESSION_ID"), + }, + body: JSON.stringify({ server, uri }), + }); + const body = await resp.json(); + if (!resp.ok || body.error) throw new ToolError(body.error ?? `http ${resp.status}`, server, uri); + return body.result; +} + +/** What artifact() hands back. Small on purpose: no bytes. */ + + + + + + + + + + + + + + + + + + + +/** + * Hand a file back to whoever asked for this run. + * + * const shot = await chrome_devtools.take_screenshot({ format: "png" }); + * await artifact("checkout.png", shot); + * return { total }; + * + * The data may be a string, bytes, an ArrayBuffer, { path } for a file + * already on disk, or an MCP image/audio/resource content item straight from + * a tool result. + * + * This behaves identically wherever the script runs, and that is the whole + * point of it. Locally the daemon hardlinks the file it was pointed at. + * Remotely the bytes travel once, to the daemon, and the caller fetches them + * only if it wants them. The script does not ask which case it is in, because + * a script that has to ask is a script with two code paths and one of them is + * never tested. + */ +export async function artifact( + name , + data , + opts , +) { + const norm = normaliseArtifact(data); + const query = new URLSearchParams({ name }); + if (opts?.mime ?? norm.mime) query.set("mime", (opts?.mime ?? norm.mime) ); + if (opts?.ttl) query.set("ttl", opts.ttl); + const run = env("MCPX_RUN"); + if (run) query.set("run", run); + if (SESSION) query.set("session", SESSION); + + const headers = { "x-mcpx-session": SESSION }; + // Only when it is actually known. Sending the generic type would beat the + // daemon's guess from the extension, and "shot.png" is a better source of + // truth than "some bytes". + const declared = opts?.mime ?? norm.mime; + if (declared) headers["content-type"] = declared; + let body ; + if (norm.path !== undefined && env("MCPX_ARTIFACTS_LOCAL") === "1") { + // The daemon can see this file. Naming it lets the store hardlink rather + // than read, hash into memory and write again. + headers["x-mcpx-path"] = norm.path; + } else if (norm.path !== undefined) { + body = await readFileBytes(norm.path) ; + } else { + body = norm.bytes ; + } + + const resp = await TRANSPORT.fetch(base() + "/v1/artifacts?" + query.toString(), { + method: "POST", + headers, + body, + }); + const out = await resp.json(); + if (!resp.ok || out.error) { + throw new Error("artifact " + JSON.stringify(name) + ": " + (out.error ?? "http " + resp.status)); + } + // Announced on the same channel as log and emit, so a consumer watching a + // run learns the artifact exists while it is still running rather than at + // the end. + send("artifact", { id: out.id, name: out.name }); + return out ; +} + + + +function b64ToBytes(b64 ) { + const bin = atob(b64); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; +} + +async function readFileBytes(path ) { + const d = (globalThis ).Deno; + if (typeof d?.readFile === "function") return await d.readFile(path); + const fsp = builtin("node:fs/promises"); + if (typeof fsp?.readFile === "function") return new Uint8Array(await fsp.readFile(path)); + throw new Error("cannot read " + path + " in this runtime"); +} + +/** + * Reduce whatever was passed to bytes or a path. + * + * Accepting an MCP content item directly is what makes the common case one + * line: a screenshot arrives as { type: "image", data, mimeType } and that is + * exactly what gets passed in, with no unwrapping at the call site. + */ +function normaliseArtifact(data ) { + if (typeof data === "string") { + return { bytes: new TextEncoder().encode(data), mime: "text/plain; charset=utf-8" }; + } + if (data instanceof Uint8Array) return { bytes: data }; + if (data instanceof ArrayBuffer) return { bytes: new Uint8Array(data) }; + if (ArrayBuffer.isView(data)) { + const v = data ; + return { bytes: new Uint8Array(v.buffer, v.byteOffset, v.byteLength) }; + } + if (data && typeof data === "object") { + const o = data ; + if (typeof o.path === "string") return { path: o.path }; + // A tool result carries its envelope on .raw; reach through to a content + // block with a body rather than making every call site do it. Media and + // embedded resources first: a screenshot result is a caption followed by + // the image, and the caption is not the file anyone meant. + if (o.raw && typeof o.raw === "object") { + const blocks = (o.raw ).content ?? []; + for (const b of blocks) { + const inner = b?.type === "text" ? undefined : normaliseContent(b); + if (inner) return inner; + } + for (const b of blocks) { + const inner = normaliseContent(b); + if (inner) return inner; + } + } + const direct = normaliseContent(o ); + if (direct) return direct; + } + // Anything else is a value, and a value's file form is its JSON. + return { + bytes: new TextEncoder().encode(JSON.stringify(data, null, 2)), + mime: "application/json", + }; +} + +function normaliseContent(b ) { + if (!b || typeof b !== "object") return undefined; + if ((b.type === "image" || b.type === "audio") && typeof b.data === "string") { + return { bytes: b64ToBytes(b.data), mime: b.mimeType }; + } + if (b.type === "resource") { + const r = (b ).resource; + if (r && typeof r.blob === "string") return { bytes: b64ToBytes(r.blob), mime: r.mimeType }; + if (r && typeof r.text === "string") { + return { bytes: new TextEncoder().encode(r.text), mime: r.mimeType ?? "text/plain" }; + } + } + if (b.type === "text" && typeof b.text === "string") { + return { bytes: new TextEncoder().encode(b.text), mime: "text/plain; charset=utf-8" }; + } + return undefined; +} + +export const demo = { + /** + * Always returns a tool error. + */ + boom(args ) { + return __call("demo", "boom", args); + }, + + /** + * Report progress and log messages, then echo the request's _meta. + */ + chatty(args ) { + return __call("demo", "chatty", args); + }, + + /** + * Echo a message back. + * Second line of description. + */ + echo(args + + + ) { + return __call("demo", "echo", args); + }, + + /** + * Tool whose name is not a TypeScript identifier. + */ + fancy_name(args + + + + + + + ) { + return __call("demo", "fancy-name", args); + }, + + /** + * Record a value in this process's state. + */ + open(args + + ) { + return __call("demo", "open", args); + }, + + /** + * Sleep for ms milliseconds, then return. + */ + slow(args + + ) { + return __call("demo", "slow", args); + }, + + /** + * Report this process's pid and everything it has recorded. + */ + state(args ) { + return __call("demo", "state", args); + }, + + /** + * Return structuredContent. + */ + structured(args ) + + { + return __call("demo", "structured", args); + }, + + /** + * Forget everything this process recorded. + */ + wipe(args ) { + return __call("demo", "wipe", args); + }, +}; + +export const tools = { + demo, +}; + +Object.setPrototypeOf(tools, new Proxy({} , { + get(_target, prop, _receiver) { + for (const ns of Object.values(tools)) { + if (typeof ns === "object" && ns !== null && typeof prop === "string" && prop in (ns )) { + return (ns )[prop]; + } + } + if (typeof prop === "string" && prop !== "then" && prop !== "catch") { + return (args ) => __call("", prop, args ?? {}); + } + return undefined; + } +})); + +/** Parameter names and descriptions, for search() and describe(). */ +const __toolMeta = { + "demo": { + "boom": { + "description": "Always returns a tool error.", + "params": [], + "required": [] + }, + "chatty": { + "description": "Report progress and log messages, then echo the request's _meta.", + "params": [], + "required": [] + }, + "echo": { + "description": "Echo a message back.", + "params": [ + "message" + ], + "required": [ + "message" + ] + }, + "fancy-name": { + "description": "Tool whose name is not a TypeScript identifier.", + "params": [ + "count", + "items", + "mode", + "nested" + ], + "required": [] + }, + "open": { + "description": "Record a value in this process's state.", + "params": [ + "value" + ], + "required": [ + "value" + ] + }, + "slow": { + "description": "Sleep for ms milliseconds, then return.", + "params": [ + "ms" + ], + "required": [ + "ms" + ] + }, + "state": { + "description": "Report this process's pid and everything it has recorded.", + "params": [], + "required": [] + }, + "structured": { + "description": "Return structuredContent.", + "params": [], + "required": [] + }, + "wipe": { + "description": "Forget everything this process recorded.", + "params": [], + "required": [] + } + } +}; + +export default tools; diff --git a/pkgs/mcpx/docs/home-example/client.ts b/pkgs/mcpx/docs/home-example/client.ts new file mode 100644 index 0000000000..473027940e --- /dev/null +++ b/pkgs/mcpx/docs/home-example/client.ts @@ -0,0 +1,1420 @@ +// Generated by mcpx. Do not edit; regenerated whenever tool schemas change. +// +// Each function posts one tools/call to the local mcpx daemon, which owns the +// MCP server processes. Results are returned already unwrapped: a text-only +// result becomes a string, a structured result becomes the parsed object. +// Reach for .raw on the returned value when you need the full MCP envelope. + +const DEFAULT_ENDPOINT = "http://127.0.0.1:41591"; +const DEFAULT_SESSION = ""; + +function env(name: string): string { + // Works on Deno, Bun and Node without assuming any of them. + try { + const d = (globalThis as any).Deno; + if (d?.env?.get) return d.env.get(name) ?? ""; + } catch { /* permission denied: fall through */ } + try { + const p = (globalThis as any).process; + if (p?.env) return p.env[name] ?? ""; + } catch { /* not Node-like */ } + return ""; +} + +// The session and endpoint are read at run time rather than baked in, so that +// concurrent runs sharing one generated client file still get their own +// session. That isolation is what gives each run its own browser in +// session-mode pools. +const ENDPOINT = env("MCPX_ENDPOINT") || DEFAULT_ENDPOINT; +const SESSION = env("MCPX_SESSION") || DEFAULT_SESSION; + +/** + * The daemon's unix socket, when one is available. + * + * Measured against the same daemon: a warm socket answers in about 0.17ms, + * loopback TCP in about 0.65ms. Small per call, but a script making a + * thousand calls spends half a second on it, and the socket's filesystem + * permissions are a better access control than an open port. + * + * Each runtime spells a unix-socket fetch differently -- Deno a custom HTTP + * client, Bun an option on fetch, Node an agent on http -- so the choice is + * made once here and every call goes through it. When none works, or no + * socket is named, it falls back to the TCP endpoint every runtime supports. + */ +const SOCKET = env("MCPX_SOCKET"); + +type Fetcher = (url: string, init: RequestInit) => Promise; + +const makeFetcher = (): { fetch: Fetcher; via: string } => { + const g = globalThis as any; + if (!SOCKET) return { fetch: (u, i) => fetch(u, i), via: "tcp" }; + + // Deno: a client whose transport is the socket. + if (g.Deno?.createHttpClient) { + try { + const client = g.Deno.createHttpClient({ proxy: { transport: "unix", path: SOCKET } }); + return { fetch: (u, i) => fetch(u, { ...i, client } as any), via: "unix" }; + } catch { + /* an older Deno; fall through to TCP */ + } + } + // Bun: fetch takes the socket directly. + if (g.Bun) { + return { fetch: (u, i) => fetch(u, { ...i, unix: SOCKET } as any), via: "unix" }; + } + // Node's fetch cannot address a socket without undici, which is not + // guaranteed to be importable here. TCP is correct and nearly as fast. + return { fetch: (u, i) => fetch(u, i), via: "tcp" }; +}; + +const TRANSPORT = makeFetcher(); + +/** Where calls are going, for a script that wants to know. */ +export const transport = (): string => TRANSPORT.via; + +/** The base URL to put in front of a path, given the transport. */ +const base = (): string => (TRANSPORT.via === "unix" ? "http://mcpx" : ENDPOINT); + +/** A filesystem location, as given and as fully resolved. */ +export interface PathPair { + /** The path as mcpx was given it, symlinks and all. */ + readonly path: string; + /** The same location with every symlink resolved. */ + readonly real: string; +} + +function realpath(p: string): string { + if (!p) return p; + try { + const d = (globalThis as any).Deno; + if (d?.realPathSync) return d.realPathSync(p); + } catch { /* not Deno, or denied */ } + try { + // Bun and Node both expose node:fs; require is available in Bun/CJS and + // createRequire covers the rest without a static import. + const req = (globalThis as any).require ?? + (globalThis as any).process?.getBuiltinModule?.bind((globalThis as any).process); + const fs = req ? req("node:fs") : undefined; + if (fs?.realpathSync) return fs.realpathSync(p); + } catch { /* fall through */ } + return p; +} + +function pair(p: string): PathPair { + return { path: p, real: realpath(p) }; +} + +function builtin(name: string): any { + try { + const g = globalThis as any; + const req = g.require ?? g.process?.getBuiltinModule?.bind(g.process); + return req ? req(name) : undefined; + } catch { + return undefined; + } +} + +function permissionDenied(kind: string, path?: string): Error { + const target = path ? " " + String(path) : ""; + const err = new Error("Requires " + kind + " access" + target); + (err as any).name = "PermissionDenied"; + return err; +} + +function installDenoCompat(): void { + const g = globalThis as any; + const d = g.Deno ??= {}; + d.args ??= g.process?.argv?.slice(2) ?? []; + if (typeof d.exit !== "function" && typeof g.process?.exit === "function") { + d.exit = (code?: number) => g.process.exit(code); + } + if (!d.env?.get) { + d.env = { + get(name: string): string | undefined { + return g.process?.env?.[name]; + }, + }; + } + if (typeof d.inspect !== "function") { + if (typeof g.Bun?.inspect === "function") { + d.inspect = (v: unknown, opts?: { colors?: boolean; depth?: number }) => + g.Bun.inspect(v, opts); + } else { + const util = builtin("node:util"); + if (typeof util?.inspect === "function") { + d.inspect = (v: unknown, opts?: { colors?: boolean; depth?: number }) => + util.inspect(v, { colors: false, depth: 4, ...opts }); + } + } + } + if (typeof d.readTextFileSync !== "function") { + d.readTextFileSync = (path: string): string => { + if (env("MCPX_ALLOW_READ") !== "1") throw permissionDenied("read", path); + const fs = builtin("node:fs"); + if (!fs?.readFileSync) throw new Error("readTextFileSync is unavailable in this runtime"); + return fs.readFileSync(path, "utf8"); + }; + } + if (typeof d.readTextFile !== "function") { + d.readTextFile = async (path: string): Promise => { + if (env("MCPX_ALLOW_READ") !== "1") throw permissionDenied("read", path); + const fsp = builtin("node:fs/promises"); + if (typeof fsp?.readFile === "function") return await fsp.readFile(path, "utf8"); + return d.readTextFileSync(path); + }; + } +} + +function fromFileUrl(url: string): string { + if (!url.startsWith("file://")) return url; + const withoutScheme = decodeURIComponent(url.slice("file://".length)); + // file:///abs on unix; strip a leading host component if one is present. + return withoutScheme.startsWith("/") ? withoutScheme : "/" + withoutScheme.replace(/^[^/]*\//, ""); +} + +/** + * Where things are, from the point of view of any file in the import graph. + * + * These come from the environment rather than from module scope, so a script + * three imports deep sees the same cwd and entry as the file the user + * actually named. Use here(import.meta) for the current file. + */ +export const paths = { + /** The directory the user ran mcpx from. */ + cwd: pair(env("MCPX_CWD")), + /** The script mcpx was asked to run. Empty for mcpx exec. */ + entry: pair(env("MCPX_ENTRY")), + /** This generated client module. */ + client: pair(env("MCPX_CLIENT")), + /** The config file in effect, if any. */ + config: pair(env("MCPX_CONFIG_PATH")), + /** Directories searched for named scripts, nearest first. */ + scriptDirs: (env("MCPX_SCRIPT_DIRS") || "").split(":").filter(Boolean), +}; + +/** + * The file this is called from. + * + * import { here } from "./mcpx-client.ts"; + * const self = here(import.meta); // { path, real } + * + * A module-level constant cannot do this: it would resolve once, in the + * client, and every importer would see the client's own path. + */ +export function here(meta: { url: string }): PathPair { + return pair(fromFileUrl(meta.url)); +} + +/** The directory containing the file this is called from. */ +export function hereDir(meta: { url: string }): PathPair { + const p = fromFileUrl(meta.url); + const dir = p.slice(0, Math.max(0, p.lastIndexOf("/"))) || "/"; + return pair(dir); +} + +export interface ContentBlock { + type: string; + text?: string; + data?: string; + mimeType?: string; + uri?: string; + [key: string]: unknown; +} + +export interface RawToolResult { + content?: ContentBlock[]; + structuredContent?: unknown; + isError?: boolean; + [key: string]: unknown; +} + +export type Attached = T & { raw: R }; + +/** + * The value a tool call resolves to. + * + * It behaves as the useful part of the result (parsed structured content, or + * the concatenated text) while still carrying the full envelope on .raw. + */ +export type ToolResult = any; + +/** + * What mcpx worked out about a call a server refused: the argument at fault, + * what changed in the tool's schema and when, and the smallest call that works. + */ +export interface Diagnostic { + kind: string; + tool?: string; + field?: string; + message: string; + changed?: { when: string; kind: string; tool: string; field?: string; what: string }; + fix?: string; + fatal?: boolean; +} + +export class ToolError extends Error { + // Written as plain fields rather than constructor parameter properties: + // Node's type-stripping mode erases types without transforming code, and + // parameter properties need a transform. Plain fields run everywhere. + server: string; + tool: string; + raw?: unknown; + diagnostics?: Diagnostic[]; + + constructor(message: string, server: string, tool: string, raw?: unknown) { + super(message); + this.name = "ToolError"; + this.server = server; + this.tool = tool; + this.raw = raw; + } +} + +function attachRaw(value: T, raw: RawToolResult): T { + if (value !== null && typeof value === "object") { + try { + Object.defineProperty(value, "raw", { value: raw, enumerable: false, configurable: true }); + } catch { /* frozen object: leave it alone */ } + return value; + } + // Primitives cannot carry properties; box strings so .raw still works. + if (typeof value === "string") { + const boxed = new String(value) as unknown as T; + Object.defineProperty(boxed, "raw", { value: raw, enumerable: false, configurable: true }); + return boxed; + } + return value; +} + +function unwrap(server: string, tool: string, raw: RawToolResult): ToolResult { + if (raw && raw.isError) { + const text = (raw.content ?? []) + .filter((c) => c.type === "text" && typeof c.text === "string") + .map((c) => c.text) + .join("\n"); + throw new ToolError(text || `${server}.${tool} returned isError`, server, tool, raw); + } + if (raw && raw.structuredContent !== undefined) { + return attachRaw(raw.structuredContent as ToolResult, raw); + } + const blocks = raw?.content ?? []; + const texts = blocks.filter((c) => c.type === "text" && typeof c.text === "string"); + if (texts.length === blocks.length && texts.length > 0) { + const joined = texts.map((c) => c.text as string).join("\n"); + // Servers commonly return JSON as text; hand back the parsed value when + // it parses cleanly, since that is almost always what the script wants. + const t = joined.trim(); + if ((t.startsWith("{") && t.endsWith("}")) || (t.startsWith("[") && t.endsWith("]"))) { + try { + return attachRaw(JSON.parse(t) as ToolResult, raw); + } catch { /* not JSON after all */ } + } + return attachRaw(joined as ToolResult, raw); + } + return attachRaw(blocks as ToolResult, raw); +} + +async function __call(server: string, tool: string, args: unknown): Promise { + let resp: Response; + try { + resp = await TRANSPORT.fetch(base() + "/v1/call", { + method: "POST", + headers: { + "content-type": "application/json", + "x-mcpx-session": SESSION, + "x-mcpx-call": SESSION, + "x-mcpx-cwd": env("MCPX_CWD"), + "x-mcpx-pid": env("MCPX_PID"), + "x-mcpx-parent-session": env("MCPX_PARENT_SESSION_ID"), + "x-mcpx-ephemeral": env("MCPX_EPHEMERAL"), + "x-mcpx-run": env("MCPX_RUN"), + "x-mcpx-input": env("MCPX_INPUT"), + }, + body: JSON.stringify({ server, tool, args: args ?? {} }), + }); + } catch (e) { + throw new ToolError( + `cannot reach the mcpx daemon at ${ENDPOINT}: ${(e as Error).message}`, + server, + tool, + ); + } + const body = await resp.json().catch(() => ({ error: `bad response (http ${resp.status})` })); + if (resp.status === 202 && body.inputRequired) { + // The server stopped to ask something and nothing in this run can + // answer it (MCPX_INPUT=report, set by mcpx exec and mcpx run). Exiting + // 75 rather than throwing: a script that catches ToolError would + // otherwise carry on as if the call had merely failed, and the caller + // would never learn there is a question waiting. + writeStderr("mcpx: " + String(body.inputRequired.text ?? "").trimEnd()); + const g = globalThis as any; + if (typeof g.Deno?.exit === "function") g.Deno.exit(75); + if (typeof g.process?.exit === "function") g.process.exit(75); + throw new ToolError(`${server}.${tool} is waiting for input`, server, tool, body); + } + if (!resp.ok || body.error) { + const err = new ToolError(body.error ?? `http ${resp.status}`, server, tool, body); + if (Array.isArray(body.diagnostics)) err.diagnostics = body.diagnostics; + throw err; + } + return unwrap(server, tool, body.result as RawToolResult); +} + +export type LogLevel = "debug" | "info" | "warn" | "error"; + +/** Structured values attached to a log record. */ +export type LogAttrs = Record; + +const LOG_SENTINEL = "\u001emcpx\u001e"; + +const LEVEL_ORDER: Record = { debug: 0, info: 1, warn: 2, error: 3 }; + +function levelFrom(name: string, fallback: number): number { + const n = LEVEL_ORDER[name.trim().toLowerCase() as LogLevel]; + return n === undefined ? fallback : n; +} + +// The active threshold, so a filtered call costs a comparison instead of a +// JSON encode and a write. The runner passes the same value it will filter on, +// which keeps the two ends from disagreeing. +const MIN_LEVEL = levelFrom(env("MCPX_LOG_LEVEL"), LEVEL_ORDER.info); + +/** + * Levels whose records carry a call site. + * + * Capture costs about 5 microseconds -- building the stack, not reading it -- + * which is roughly fifty times the cost of the record itself. Paying that on + * every info line is waste; paying it on a warning is the moment you most want + * to know where it came from. So the default traces warn and above, and + * MCPX_LOG_SOURCE widens it to everything. + */ +const SOURCE_LEVELS: number = env("MCPX_LOG_SOURCE") === "1" + ? LEVEL_ORDER.debug + : env("MCPX_LOG_SOURCE") === "0" + ? Number.POSITIVE_INFINITY + : levelFrom(env("MCPX_LOG_SOURCE"), LEVEL_ORDER.warn); + +function writeStderr(line: string): void { + const d = (globalThis as any).Deno; + if (d?.stderr?.writeSync) { + d.stderr.writeSync(new TextEncoder().encode(line + "\n")); + return; + } + const p = (globalThis as any).process; + if (p?.stderr?.write) { + p.stderr.write(line + "\n"); + return; + } + console.error(line); +} + +/** A plain data object, as opposed to an Error, an array or a primitive. */ +function isAttrs(v: unknown): v is LogAttrs { + return typeof v === "object" && v !== null && !Array.isArray(v) && + !(v instanceof Error) && Object.getPrototypeOf(v) === Object.prototype; +} + +function formatFrames(name: string, message: string, frames: Frame[]): string { + const head = message ? name + ": " + message : name; + const body = frames.map((f) => { + const at = [f.file, f.line, f.column].filter((x) => x !== undefined).join(":"); + return " at " + (f.function ? f.function + " (" + at + ")" : at); + }); + return [head, ...body].join("\n"); +} + +function describeError(e: Error): LogAttrs { + // Both forms are wanted: the string is what a human reads, the frames are + // what a query groups by. They cannot both be taken from the Error, because + // V8 memoises whatever prepareStackTrace returned the first time .stack is + // touched -- ask for one and the other is gone. So frames are captured and + // the string is rendered from them. + const frames = errorFrames(e, 16); + const stack = frames.length ? formatFrames(e.name, e.message, frames) : ( + typeof e.stack === "string" ? e.stack : "" + ); + return { + name: e.name, + message: e.message, + ...(stack ? { stack } : {}), + ...(frames.length ? { frames } : {}), + ...((e as any).cause !== undefined ? { cause: safeInspect((e as any).cause) } : {}), + }; +} + +/** One frame of a captured stack. */ +export interface Frame { + file?: string; + line?: number; + column?: number; + function?: string; + type?: string; + async?: boolean; + native?: boolean; +} + +/** + * Capture a stack as structured frames. + * + * V8 exposes Error.prepareStackTrace, which hands back CallSite objects + * instead of a formatted string. It is not in any standard, but Deno, Node and + * Bun are all V8 or JSC-with-the-same-shim, and all three were verified to + * support it. Parsing the string form is the fallback, and it is strictly + * worse: it loses async and native flags and breaks on any path containing the + * characters the format uses as delimiters. + */ +export function captureFrames(skip = 0, limit = 32): Frame[] { + const E = Error as any; + const previous = E.prepareStackTrace; + const previousLimit = E.stackTraceLimit; + try { + E.stackTraceLimit = skip + limit + 4; + E.prepareStackTrace = (_e: Error, sites: any[]) => + sites.map((s) => { + const f: Frame = {}; + const file = s.getFileName?.(); + if (file) f.file = String(file).replace(/^file:\/\//, ""); + const line = s.getLineNumber?.(); + if (typeof line === "number") f.line = line; + const col = s.getColumnNumber?.(); + if (typeof col === "number") f.column = col; + const fn = s.getFunctionName?.(); + if (fn) f.function = fn; + const tn = s.getTypeName?.(); + if (tn) f.type = tn; + if (s.isAsync?.()) f.async = true; + if (s.isNative?.()) f.native = true; + return f; + }); + const holder: any = {}; + E.captureStackTrace?.(holder, captureFrames); + const frames: Frame[] = holder.stack ?? (new Error() as any).stack ?? []; + return Array.isArray(frames) ? frames.slice(skip, skip + limit) : []; + } catch { + return []; + } finally { + E.prepareStackTrace = previous; + E.stackTraceLimit = previousLimit; + } +} + +/** The frames of an Error, structured, without re-throwing it. */ +export function errorFrames(err: Error, limit = 32): Frame[] { + const E = Error as any; + const previous = E.prepareStackTrace; + try { + E.prepareStackTrace = (_e: Error, sites: any[]) => + sites.map((s) => { + const f: Frame = {}; + const file = s.getFileName?.(); + if (file) f.file = String(file).replace(/^file:\/\//, ""); + const line = s.getLineNumber?.(); + if (typeof line === "number") f.line = line; + const fn = s.getFunctionName?.(); + if (fn) f.function = fn; + if (s.isAsync?.()) f.async = true; + return f; + }); + // Reading .stack re-runs prepareStackTrace against the captured sites. + const frames = (err as any).stack; + return Array.isArray(frames) ? frames.slice(0, limit) : []; + } catch { + return []; + } finally { + E.prepareStackTrace = previous; + } +} + +/** + * Where the call came from. + * + * Only called when the level warrants it, because capturing the stack is the + * expensive half. + */ +function callSite(): LogAttrs | undefined { + const frames = captureFrames(0, 8).filter((f) => !(f.file ?? "").includes("mcpx-client")); + const top = frames[0]; + if (!top) return undefined; + return { + ...(top.file ? { "source.file": top.file } : {}), + ...(top.line ? { "source.line": top.line } : {}), + ...(top.column ? { "source.column": top.column } : {}), + ...(top.function ? { "source.function": top.function } : {}), + }; +} + +function send(kind: "log" | "result" | "artifact", payload: Record): void { + writeStderr(LOG_SENTINEL + JSON.stringify({ kind, ts: new Date().toISOString(), ...payload })); +} + +function emitRecord( + level: LogLevel, + bound: LogAttrs, + msg: string, + rest: unknown[], + fileOnly = false, +): void { + // Short-circuit before any work. A debug call in a loop should cost a + // comparison when nothing will print. + const n = LEVEL_ORDER[level]; + if (n < MIN_LEVEL) return; + + let attrs: LogAttrs = { ...bound }; + const extra: unknown[] = []; + for (const [i, v] of rest.entries()) { + if (i === 0 && isAttrs(v)) { + Object.assign(attrs, v); + continue; + } + extra.push(v instanceof Error ? describeError(v) : v); + } + if (extra.length > 0) attrs.args = extra; + if (n >= SOURCE_LEVELS) Object.assign(attrs, callSite()); + + const hasTemplate = msg.includes("{"); + send("log", { + level, + msg, + ...(hasTemplate ? { template: msg } : {}), + ...(fileOnly ? { fileOnly: true } : {}), + ...(Object.keys(attrs).length > 0 ? { attrs } : {}), + }); +} + +/** + * A logger, optionally carrying attributes bound by with(). + * + * Callable directly: log("message") is log.info("message"), because the + * overwhelmingly common case should not need a method name. + */ +export interface Logger { + (msg: string, ...rest: unknown[]): void; + debug(msg: string, ...rest: unknown[]): void; + info(msg: string, ...rest: unknown[]): void; + warn(msg: string, ...rest: unknown[]): void; + error(msg: string, ...rest: unknown[]): void; + /** + * A logger carrying these attributes on every record, mirroring slog's + * Logger.With. + * + * The returned logger must be passed where it is needed; JavaScript has no + * ambient context, so bindings do not follow the call stack on their own. + * + * const scoped = log.with({ run: runId }); + * await scan(scoped, file); + */ + with(attrs: LogAttrs): Logger; + /** True when a record at this level would be emitted. */ + enabled(level: LogLevel): boolean; +} + +function makeLogger(bound: LogAttrs): Logger { + const fn = ((msg: string, ...rest: unknown[]) => emitRecord("info", bound, msg, rest)) as Logger; + return Object.assign(fn, { + debug: (msg: string, ...rest: unknown[]) => emitRecord("debug", bound, msg, rest), + info: (msg: string, ...rest: unknown[]) => emitRecord("info", bound, msg, rest), + warn: (msg: string, ...rest: unknown[]) => emitRecord("warn", bound, msg, rest), + error: (msg: string, ...rest: unknown[]) => emitRecord("error", bound, msg, rest), + with: (attrs: LogAttrs) => makeLogger({ ...bound, ...attrs }), + enabled: (level: LogLevel) => LEVEL_ORDER[level] >= MIN_LEVEL, + }); +} + +/** + * Structured logging for scripts. + * + * A message may carry {placeholders} filled from the attributes, and {{x}} + * writes a literal {x}: + * + * log.info("fetched {count} pages in {ms}ms", { count: 3, ms: 412 }); + * + * The first argument after the message is treated as attributes when it is a + * plain object. Anything else, and anything after it, is collected into an + * "args" array, so console-style calls still carry their values rather than + * being dropped: + * + * log.error("upload failed", err); // err becomes args[0] + * log.debug("state", { id }, "extra", 42); // id is an attribute + * + * Both the rendered message and its template are kept, so output reads as + * prose and still groups by shape. stdout stays clear for results; this is + * stderr. + */ +export const log: Logger = makeLogger({}); + +/** + * Stream a result before the script finishes. + * + * A script's return value is one answer delivered at the end. emit() is for + * many answers delivered as they are found: a long crawl, a per-file report, a + * progress feed a caller can act on without waiting. + * + * for (const file of files) emit({ file, findings: await scan(file) }); + * + * Each value is written immediately. In ordinary use it lands on stdout as one + * JSON line per call; under mcpx --json run the values are collected into + * the envelope's results array in order. Either way the consumer sees them + * in sequence rather than as one blob at the end. + */ +export function emitResult(value: unknown): void { + send("result", { value }); +} + +export { emitResult as emit }; + +/** + * Route console output through the record stream. + * + * console.log keeps going to stdout, because that is the script's result and + * redirecting it would change what a caller reads. It is *also* mirrored as a + * debug record so it lands in the durable log alongside everything else -- + * otherwise the one thing a script actually printed is the one thing missing + * when you go looking afterwards. + * + * console.error/warn/info/debug become records outright: they are diagnostics, + * and leaving them as bare stderr text means they miss enrichment, formatting + * and the log file. + */ +export function captureConsole(): void { + const c = globalThis.console as any; + if (!c || c.__mcpxWrapped) return; + const original: Record void) | undefined> = {}; + for (const k of Object.keys(c)) { + if (typeof c[k] === "function") original[k] = c[k].bind(c); + } + + let depth = 0; + + // Render the message the way the runtime would have. A caller who wrote + // console.info({a:1}) expects to read "{ a: 1 }", not the JSON encoding -- + // the structured copy of the value is already in args, so the message is + // free to be the human form. + const g = globalThis as any; + const nodeInspect = builtin("node:util")?.inspect; + const native: ((v: unknown) => string) | undefined = + env("MCPX_RUNTIME") === "node" && typeof nodeInspect === "function" + ? (v) => nodeInspect(v) + : typeof g.Deno?.inspect === "function" + ? (v) => g.Deno.inspect(v, { colors: false, depth: 4 }) + : typeof g.Bun?.inspect === "function" + ? (v) => g.Bun.inspect(v) + : typeof nodeInspect === "function" + ? (v) => nodeInspect(v) + : undefined; + const one = (a: unknown) => { + if (typeof a === "string") return a; + if (native) { + try { + return native(a); + } catch { + /* fall through */ + } + } + return safeInspect(a); + }; + // Format specifiers, because a script that writes console.info("%s: %d", + // name, n) expects to read "alice: 42". Dropping the substitution and + // printing the template beside its arguments is the kind of difference that + // makes a captured console feel broken rather than redirected. + // + // Matches the runtimes: substitution happens only when there are arguments + // to substitute, leftover specifiers stay as written, and surplus arguments + // are appended. + const FORMAT = /%[sdifjoOc%]/g; + const applyFormat = (template: string, rest: unknown[]): [string, unknown[]] => { + let i = 0; + const text = template.replace(FORMAT, (spec) => { + if (spec === "%%") return "%"; + if (i >= rest.length) return spec; + const v = rest[i++]; + switch (spec) { + case "%s": + return typeof v === "string" ? v : one(v); + case "%d": + case "%i": { + if (typeof v === "bigint") return String(v); + const n = Number(v); + return Number.isNaN(n) ? "NaN" : String(Math.trunc(n)); + } + case "%f": + return String(Number(v)); + case "%j": + return safeInspect(v); + case "%o": + case "%O": + return one(v); + case "%c": + // Styling has no meaning outside a browser. The argument is still + // consumed, which is what keeps the remaining substitutions lined + // up with their specifiers. + return ""; + } + return spec; + }); + return [text, rest.slice(i)]; + }; + + const render = (args: unknown[]) => { + const pad = " ".repeat(depth); + if (args.length > 1 && typeof args[0] === "string" && FORMAT.test(args[0] as string)) { + FORMAT.lastIndex = 0; + const [text, rest] = applyFormat(args[0] as string, args.slice(1)); + return pad + [text, ...rest.map(one)].join(" "); + } + FORMAT.lastIndex = 0; + return pad + args.map(one).join(" "); + }; + + // Keep the original name on every replacement. Something reading + // console.info.name should still see "info"; losing it breaks introspection + // for no gain. + const patch = (name: string, fn: (...a: any[]) => void) => { + Object.defineProperty(fn, "name", { value: name, configurable: true }); + c[name] = fn; + }; + + // The five that carry a level map onto it directly. console.info really is + // log.info; there is no separate concept to reconcile. + const direct: Record = { + info: "info", + warn: "warn", + error: "error", + debug: "debug", + dir: "info", + dirxml: "info", + table: "info", + }; + for (const [name, level] of Object.entries(direct)) { + patch(name, (...args: unknown[]) => emitRecord(level, { console: name }, render(args), [])); + } + + // stdout is the script's result, so console.log keeps going there. The + // record exists so the durable log has it too, and is file-only so the + // terminal does not show the same line twice. + patch("log", (...args: unknown[]) => { + original.log?.(...args); + emitRecord("debug", { console: "log" }, render(args), [], true); + }); + + // console.trace is a stack request; honour it rather than dropping the part + // that was asked for. + patch("trace", (...args: unknown[]) => { + emitRecord("debug", { console: "trace", frames: captureFrames(1, 16) }, render(args), []); + }); + + patch("assert", (cond: unknown, ...args: unknown[]) => { + if (cond) return; + emitRecord("error", { console: "assert" }, render(args.length ? args : ["assertion failed"]), []); + }); + + // Grouping is presentation, and a structured record has no nesting to show. + // Indentation is preserved so output still reads as the author intended. + patch("group", (...args: unknown[]) => { + if (args.length) emitRecord("info", { console: "group" }, render(args), []); + depth++; + }); + // A record stream has nothing to collapse, so collapsed groups are groups. + patch("groupCollapsed", (...args: unknown[]) => c.group(...args)); + patch("groupEnd", () => { + depth = Math.max(0, depth - 1); + }); + + // indentLevel is a property rather than a method, and reading it is how some + // libraries decide their own wrapping. Keep it truthful. + Object.defineProperty(c, "indentLevel", { + get: () => depth, + set: (v: number) => { + depth = Math.max(0, Math.trunc(Number(v) || 0)); + }, + configurable: true, + }); + + // console.clear wipes a terminal. It must not wipe a durable log, so the + // request is recorded, the indent is reset, and the screen is left alone + // unless nothing is capturing it. + patch("clear", () => { + depth = 0; + emitRecord("debug", { console: "clear" }, "console.clear()", [], true); + }); + + // Devtools profiling markers. There is no profiler here, but dropping the + // call silently loses a deliberate annotation, so they become records. + for (const name of ["profile", "profileEnd", "timeStamp"]) { + patch(name, (...args: unknown[]) => { + emitRecord("debug", { console: name }, render(args.length ? args : [name + "()"]), [], true); + }); + } + + const counters = new Map(); + patch("count", (label = "default") => { + const n = (counters.get(label) ?? 0) + 1; + counters.set(label, n); + emitRecord("debug", { console: "count", label, count: n }, label + ": " + n, []); + }); + patch("countReset", (label = "default") => { + counters.delete(label); + }); + + const timers = new Map(); + patch("time", (label = "default") => { + timers.set(label, performance.now()); + }); + patch("timeLog", (label = "default", ...args: unknown[]) => { + const started = timers.get(label); + if (started === undefined) return; + const ms = performance.now() - started; + emitRecord("debug", { console: "timeLog", label, ms }, + label + ": " + ms.toFixed(3) + "ms " + render(args), []); + }); + patch("timeEnd", (label = "default") => { + const started = timers.get(label); + if (started === undefined) return; + timers.delete(label); + const ms = performance.now() - started; + emitRecord("debug", { console: "timeEnd", label, ms }, + label + ": " + ms.toFixed(3) + "ms", []); + }); + + c.__mcpxWrapped = true; + c.__mcpxOriginal = original; +} + +/** Undo captureConsole, for a script that wants the real console back. */ +export function releaseConsole(): void { + const c = globalThis.console as any; + if (!c?.__mcpxWrapped) return; + for (const [k, fn] of Object.entries(c.__mcpxOriginal ?? {})) { + if (fn) c[k] = fn; + } + delete c.__mcpxWrapped; + delete c.__mcpxOriginal; +} + +function safeInspect(v: unknown): string { + if (v instanceof Error) return v.stack ?? String(v); + try { + return JSON.stringify(v) ?? String(v); + } catch { + return String(v); + } +} + +/** + * Put the standard surface on globalThis. + * + * A script that imports is easier to read and gives an editor something to + * work with; a script written like a shell one-liner should not have to. Both + * work: the launcher installs these before importing the module, and the + * generated declarations tell an editor they exist. + */ +/** One tool, as search returns it. */ +export interface ToolMatch { + namespace: string; + tool: string; + /** Call it as tools[namespace][tool](args). */ + call: (args?: Record) => Promise; + description: string; + /** Parameter names, so a caller can check before invoking. */ + params: string[]; + required: string[]; +} + +/** + * Find tools by name or description, from inside a script. + * + * Without this, discovering a tool means ending the script, running + * "mcpx search", reading the result, and writing a new script. That round + * trip is the expensive part -- for a model it is a whole turn, and the + * intermediate result passes through its context on the way. + * + * Synchronous, because everything it searches is already in this file. A + * promise here would only be a promise of work already done. + */ +export function search(query: string, limit = 20): ToolMatch[] { + const words = String(query).toLowerCase().split(/\s+/).filter(Boolean); + if (words.length === 0) return []; + + const scored: Array<{ score: number; match: ToolMatch }> = []; + for (const [ns, group] of Object.entries(tools)) { + for (const [name, fn] of Object.entries(group as Record)) { + if (typeof fn !== "function") continue; + const meta = __toolMeta[ns]?.[name] ?? { description: "", params: [], required: [] }; + const hay = (ns + " " + name + " " + meta.description).toLowerCase(); + + let score = 0; + for (const w of words) { + if (!hay.includes(w)) { + score = -1; + break; + } + // A word in the name is worth more than a word in the prose. A tool + // called "grep" beats one whose description merely mentions grepping. + score += (ns + " " + name).toLowerCase().includes(w) ? 10 : 1; + } + if (score < 0) continue; + scored.push({ + score, + match: { + namespace: ns, + tool: name, + call: fn as ToolMatch["call"], + description: meta.description, + params: meta.params, + required: meta.required, + }, + }); + } + } + scored.sort((a, b) => b.score - a.score || a.match.tool.localeCompare(b.match.tool)); + return scored.slice(0, limit).map((s) => s.match); +} + +/** + * The signature of one tool, or of a whole namespace. + * + * The companion to search: found something, now what does it take. Returns + * text because that is what it is for -- reading, or printing when a script + * is exploring rather than doing. + */ +export function describe(name: string): string { + const parts = String(name).split("."); + const ns = parts[0]; + const tool = parts[1]; + const group = __toolMeta[ns]; + if (!group) { + return "no namespace " + JSON.stringify(ns) + + "; there is " + Object.keys(tools).join(", "); + } + const render = (t: string): string => { + const m = group[t]; + if (!m) return " " + t + "(...)"; + const args = m.params + .map((p) => (m.required.indexOf(p) >= 0 ? p : p + "?")) + .join(", "); + const head = " " + ns + "." + t + "({ " + args + " })"; + return m.description ? head + "\n " + m.description : head; + }; + if (!tool) { + return Object.keys(group).sort().map(render).join("\n"); + } + return render(tool); +} + +export function installGlobals(): void { + const g = globalThis as any; + installDenoCompat(); + g.log ??= log; + g.emit ??= emitResult; + g.tools ??= tools; + g.call ??= call; + g.batch ??= batch; + g.readResource ??= readResource; + g.artifact ??= artifact; + g.ToolError ??= ToolError; + g.paths ??= paths; + g.here ??= here; + g.hereDir ??= hereDir; + g.releaseConsole ??= releaseConsole; + g.captureFrames ??= captureFrames; + g.errorFrames ??= errorFrames; + g.search ??= search; + g.transport ??= transport; + g.describe ??= describe; + for (const [name, ns] of Object.entries(tools)) { + g[name] ??= ns; + if (typeof ns === "object" && ns !== null) { + for (const [fnName, fn] of Object.entries(ns)) g[fnName] ??= fn; + } + } +} + +/** Call any tool by name, including ones added after this client was generated. */ +export async function call(serverOrTool: string, toolOrArgs?: any, args?: unknown): Promise { + if (arguments.length === 1 || (arguments.length === 2 && (typeof toolOrArgs === "object" || toolOrArgs === undefined))) { + return __call("", serverOrTool, toolOrArgs ?? {}); + } + return __call(serverOrTool, String(toolOrArgs), args ?? {}); +} + +/** Execute multiple tool calls in a single turn. */ +export async function batch( + calls: Array<{ server?: string; namespace?: string; tool: string; args?: unknown; arguments?: unknown }>, + options?: { stopOnError?: boolean; parallel?: boolean } +): Promise> { + const resp = await TRANSPORT.fetch(base() + "/v1/batch", { + method: "POST", + headers: { + "content-type": "application/json", + "x-mcpx-session": SESSION, + "x-mcpx-call": SESSION, + "x-mcpx-cwd": env("MCPX_CWD"), + "x-mcpx-pid": env("MCPX_PID"), + "x-mcpx-parent-session": env("MCPX_PARENT_SESSION_ID"), + }, + body: JSON.stringify({ + calls: calls.map((c) => ({ + server: c.server ?? c.namespace ?? "", + tool: c.tool, + args: c.args ?? c.arguments ?? {}, + })), + stopOnError: options?.stopOnError ?? true, + parallel: options?.parallel ?? false, + }), + }); + const body = await resp.json(); + if (!resp.ok || body.error) throw new Error(body.error ?? ("http " + resp.status)); + return body.results ?? []; +} + +/** Read an MCP resource URI. */ +export async function readResource(server: string, uri: string): Promise { + const resp = await TRANSPORT.fetch(base() + "/v1/resource", { + method: "POST", + headers: { + "content-type": "application/json", + "x-mcpx-session": SESSION, + "x-mcpx-call": SESSION, + "x-mcpx-cwd": env("MCPX_CWD"), + "x-mcpx-pid": env("MCPX_PID"), + "x-mcpx-parent-session": env("MCPX_PARENT_SESSION_ID"), + }, + body: JSON.stringify({ server, uri }), + }); + const body = await resp.json(); + if (!resp.ok || body.error) throw new ToolError(body.error ?? `http ${resp.status}`, server, uri); + return body.result; +} + +/** What artifact() hands back. Small on purpose: no bytes. */ +export interface ArtifactRef { + /** The random handle the artifact is fetched by. */ + readonly id: string; + /** The sanitised name. It may differ from what was asked for. */ + readonly name: string; + /** mcpx://artifacts/, readable as an MCP resource. */ + readonly uri: string; + readonly size: number; + readonly mime: string; + readonly sha256: string; +} + +export interface ArtifactOptions { + /** Overrides the type guessed from the name. */ + mime?: string; + /** How long to keep it, as a Go duration string. Default from settings. */ + ttl?: string; +} + +/** + * Hand a file back to whoever asked for this run. + * + * const shot = await chrome_devtools.take_screenshot({ format: "png" }); + * await artifact("checkout.png", shot); + * return { total }; + * + * The data may be a string, bytes, an ArrayBuffer, { path } for a file + * already on disk, or an MCP image/audio/resource content item straight from + * a tool result. + * + * This behaves identically wherever the script runs, and that is the whole + * point of it. Locally the daemon hardlinks the file it was pointed at. + * Remotely the bytes travel once, to the daemon, and the caller fetches them + * only if it wants them. The script does not ask which case it is in, because + * a script that has to ask is a script with two code paths and one of them is + * never tested. + */ +export async function artifact( + name: string, + data: string | Uint8Array | ArrayBuffer | { path: string } | ContentBlock | { raw?: RawToolResult }, + opts?: ArtifactOptions, +): Promise { + const norm = normaliseArtifact(data); + const query = new URLSearchParams({ name }); + if (opts?.mime ?? norm.mime) query.set("mime", (opts?.mime ?? norm.mime) as string); + if (opts?.ttl) query.set("ttl", opts.ttl); + const run = env("MCPX_RUN"); + if (run) query.set("run", run); + if (SESSION) query.set("session", SESSION); + + const headers: Record = { "x-mcpx-session": SESSION }; + // Only when it is actually known. Sending the generic type would beat the + // daemon's guess from the extension, and "shot.png" is a better source of + // truth than "some bytes". + const declared = opts?.mime ?? norm.mime; + if (declared) headers["content-type"] = declared; + let body: BodyInit | undefined; + if (norm.path !== undefined && env("MCPX_ARTIFACTS_LOCAL") === "1") { + // The daemon can see this file. Naming it lets the store hardlink rather + // than read, hash into memory and write again. + headers["x-mcpx-path"] = norm.path; + } else if (norm.path !== undefined) { + body = await readFileBytes(norm.path) as unknown as BodyInit; + } else { + body = norm.bytes as unknown as BodyInit; + } + + const resp = await TRANSPORT.fetch(base() + "/v1/artifacts?" + query.toString(), { + method: "POST", + headers, + body, + }); + const out = await resp.json(); + if (!resp.ok || out.error) { + throw new Error("artifact " + JSON.stringify(name) + ": " + (out.error ?? "http " + resp.status)); + } + // Announced on the same channel as log and emit, so a consumer watching a + // run learns the artifact exists while it is still running rather than at + // the end. + send("artifact", { id: out.id, name: out.name }); + return out as ArtifactRef; +} + +type NormalisedArtifact = { bytes?: Uint8Array; path?: string; mime?: string }; + +function b64ToBytes(b64: string): Uint8Array { + const bin = atob(b64); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; +} + +async function readFileBytes(path: string): Promise { + const d = (globalThis as any).Deno; + if (typeof d?.readFile === "function") return await d.readFile(path); + const fsp = builtin("node:fs/promises"); + if (typeof fsp?.readFile === "function") return new Uint8Array(await fsp.readFile(path)); + throw new Error("cannot read " + path + " in this runtime"); +} + +/** + * Reduce whatever was passed to bytes or a path. + * + * Accepting an MCP content item directly is what makes the common case one + * line: a screenshot arrives as { type: "image", data, mimeType } and that is + * exactly what gets passed in, with no unwrapping at the call site. + */ +function normaliseArtifact(data: unknown): NormalisedArtifact { + if (typeof data === "string") { + return { bytes: new TextEncoder().encode(data), mime: "text/plain; charset=utf-8" }; + } + if (data instanceof Uint8Array) return { bytes: data }; + if (data instanceof ArrayBuffer) return { bytes: new Uint8Array(data) }; + if (ArrayBuffer.isView(data)) { + const v = data as ArrayBufferView; + return { bytes: new Uint8Array(v.buffer, v.byteOffset, v.byteLength) }; + } + if (data && typeof data === "object") { + const o = data as Record; + if (typeof o.path === "string") return { path: o.path }; + // A tool result carries its envelope on .raw; reach through to a content + // block with a body rather than making every call site do it. Media and + // embedded resources first: a screenshot result is a caption followed by + // the image, and the caption is not the file anyone meant. + if (o.raw && typeof o.raw === "object") { + const blocks = (o.raw as RawToolResult).content ?? []; + for (const b of blocks) { + const inner = b?.type === "text" ? undefined : normaliseContent(b); + if (inner) return inner; + } + for (const b of blocks) { + const inner = normaliseContent(b); + if (inner) return inner; + } + } + const direct = normaliseContent(o as ContentBlock); + if (direct) return direct; + } + // Anything else is a value, and a value's file form is its JSON. + return { + bytes: new TextEncoder().encode(JSON.stringify(data, null, 2)), + mime: "application/json", + }; +} + +function normaliseContent(b: ContentBlock | undefined): NormalisedArtifact | undefined { + if (!b || typeof b !== "object") return undefined; + if ((b.type === "image" || b.type === "audio") && typeof b.data === "string") { + return { bytes: b64ToBytes(b.data), mime: b.mimeType }; + } + if (b.type === "resource") { + const r = (b as any).resource; + if (r && typeof r.blob === "string") return { bytes: b64ToBytes(r.blob), mime: r.mimeType }; + if (r && typeof r.text === "string") { + return { bytes: new TextEncoder().encode(r.text), mime: r.mimeType ?? "text/plain" }; + } + } + if (b.type === "text" && typeof b.text === "string") { + return { bytes: new TextEncoder().encode(b.text), mime: "text/plain; charset=utf-8" }; + } + return undefined; +} + +export const demo = { + /** + * Always returns a tool error. + */ + boom(args?: Record): Promise { + return __call("demo", "boom", args); + }, + + /** + * Report progress and log messages, then echo the request's _meta. + */ + chatty(args?: Record): Promise { + return __call("demo", "chatty", args); + }, + + /** + * Echo a message back. + * Second line of description. + */ + echo(args: { + /** text to echo */ + message: string; + }): Promise { + return __call("demo", "echo", args); + }, + + /** + * Tool whose name is not a TypeScript identifier. + */ + fancy_name(args?: { + count?: number | null; + items?: string[]; + mode?: "a" | "b"; + nested?: { + deep: boolean; + }; + }): Promise { + return __call("demo", "fancy-name", args); + }, + + /** + * Record a value in this process's state. + */ + open(args: { + value: string; + }): Promise { + return __call("demo", "open", args); + }, + + /** + * Sleep for ms milliseconds, then return. + */ + slow(args: { + ms: number; + }): Promise { + return __call("demo", "slow", args); + }, + + /** + * Report this process's pid and everything it has recorded. + */ + state(args?: Record): Promise { + return __call("demo", "state", args); + }, + + /** + * Return structuredContent. + */ + structured(args?: Record): Promise> { + return __call("demo", "structured", args); + }, + + /** + * Forget everything this process recorded. + */ + wipe(args?: Record): Promise { + return __call("demo", "wipe", args); + }, +}; + +export const tools = { + demo, +}; + +Object.setPrototypeOf(tools, new Proxy({} as any, { + get(_target, prop, _receiver) { + for (const ns of Object.values(tools)) { + if (typeof ns === "object" && ns !== null && typeof prop === "string" && prop in (ns as any)) { + return (ns as any)[prop]; + } + } + if (typeof prop === "string" && prop !== "then" && prop !== "catch") { + return (args: any) => __call("", prop, args ?? {}); + } + return undefined; + } +})); + +/** Parameter names and descriptions, for search() and describe(). */ +const __toolMeta: Record> = { + "demo": { + "boom": { + "description": "Always returns a tool error.", + "params": [], + "required": [] + }, + "chatty": { + "description": "Report progress and log messages, then echo the request's _meta.", + "params": [], + "required": [] + }, + "echo": { + "description": "Echo a message back.", + "params": [ + "message" + ], + "required": [ + "message" + ] + }, + "fancy-name": { + "description": "Tool whose name is not a TypeScript identifier.", + "params": [ + "count", + "items", + "mode", + "nested" + ], + "required": [] + }, + "open": { + "description": "Record a value in this process's state.", + "params": [ + "value" + ], + "required": [ + "value" + ] + }, + "slow": { + "description": "Sleep for ms milliseconds, then return.", + "params": [ + "ms" + ], + "required": [ + "ms" + ] + }, + "state": { + "description": "Report this process's pid and everything it has recorded.", + "params": [], + "required": [] + }, + "structured": { + "description": "Return structuredContent.", + "params": [], + "required": [] + }, + "wipe": { + "description": "Forget everything this process recorded.", + "params": [], + "required": [] + } + } +}; + +export default tools; diff --git a/pkgs/mcpx/docs/home-example/component.html b/pkgs/mcpx/docs/home-example/component.html new file mode 100644 index 0000000000..34ef6a25be --- /dev/null +++ b/pkgs/mcpx/docs/home-example/component.html @@ -0,0 +1,99 @@ + +
+

+ Simulated — runs in your browser. + This example calls a mock demo server in this page, through + the real generated mcpx client. No daemon, no install, nothing leaves + the tab. To run it for real, copy it as a command below. +

+ + +
const echoed = await tools.demo.echo({ message: "hello from a script" });
+
+console.log("demo.echo:", String(echoed));
+ + + + + + + + + +
diff --git a/pkgs/mcpx/docs/home-example/copy-command.js b/pkgs/mcpx/docs/home-example/copy-command.js new file mode 100644 index 0000000000..2466bb3d13 --- /dev/null +++ b/pkgs/mcpx/docs/home-example/copy-command.js @@ -0,0 +1,66 @@ +// Stage 1 of issue #1876 Approach C: copy-as-command. +// +// Two clipboard payloads for a docs example: +// +// execCommand(source) -> one line that runs the snippet with +// `mcpx exec` against the reader's real +// daemon and real servers. +// scriptCommands(name, source) -> two lines that save the snippet as a +// named script and run it with `mcpx run`. +// +// The one trap (named in the issue): shell quoting. `mcpx exec` takes the +// source as an argument and reads nothing from stdin (stdin is passed +// through to the script), so the source has to arrive inside the command +// itself. Single quotes cannot contain an apostrophe, so the source is +// wrapped in a *quoted* heredoc inside a command substitution: +// +// mcpx exec "$(cat <<'MCPX_EOF' +// +// MCPX_EOF +// )" +// +// Quoting the delimiter ('MCPX_EOF') is what turns expansion off inside the +// body. The delimiter is extended until no line of the source equals it, so +// a source that itself mentions MCPX_EOF still round-trips. Command +// substitution strips trailing newlines; that is fine for source text. +// +// Pure functions, no DOM: the page wires them to buttons, and +// smoke-test.mjs round-trips them through a real shell. + +// wrapSource returns the heredoc body form shared by both commands: +// <<''\n\n, with DELIM chosen clear of the source. +function heredoc(source) { + let delim = "MCPX_EOF"; + const lines = source.split("\n"); + while (lines.includes(delim)) delim += "_X"; + const body = source.endsWith("\n") ? source : source + "\n"; + return { delim, body }; +} + +export function execCommand(source) { + const { delim, body } = heredoc(source); + return `mcpx exec "$(cat <<'${delim}'\n${body}${delim}\n)"`; +} + +const SCRIPT_NAME = /^[a-z0-9][a-z0-9-]*$/; + +export function scriptCommands(name, source) { + if (!SCRIPT_NAME.test(name)) { + throw new Error( + `script name ${JSON.stringify(name)} must be lowercase letters, digits and dashes`, + ); + } + const { delim, body } = heredoc(source); + const path = `.mcpx/scripts/${name}.ts`; + return [ + `mkdir -p .mcpx/scripts && cat > ${path} <<'${delim}'`, + `${body}${delim}`, + `mcpx run ${name}`, + ].join("\n"); +} + +// asScript is the "Copy as script" payload: the source itself, unchanged — +// the reader pastes it into a file (or their editor) as-is. +export function asScript(source) { + return source; +} diff --git a/pkgs/mcpx/docs/home-example/example.ts b/pkgs/mcpx/docs/home-example/example.ts new file mode 100644 index 0000000000..0d4e4ef835 --- /dev/null +++ b/pkgs/mcpx/docs/home-example/example.ts @@ -0,0 +1,18 @@ +// The mcpx home-page example (#1876, Approach C stage 2). +// +// This is the script the home page shows, lets the reader edit, and runs in +// the page against the fake daemon (fake-daemon.js) through the real +// generated client (client.ts / client.browser.js). It is the same shape as +// examples/call-a-tool.ts: nothing is imported, `tools` is on globalThis, +// one call, print the result. +// +// The `demo` namespace is the deterministic fixture server +// (internal/testsupport/fakemcp) — a mock, and the page says so. Keep this +// script in erasable TypeScript only (no enums, namespaces, or parameter +// properties): the in-page strip-only transform (strip-types.js) has to be +// able to run the reader's edits, same as Node's strip-only mode runs the +// generated client. + +const echoed = await tools.demo.echo({ message: "hello from a script" }); + +console.log("demo.echo:", String(echoed)); diff --git a/pkgs/mcpx/docs/home-example/fake-daemon.js b/pkgs/mcpx/docs/home-example/fake-daemon.js new file mode 100644 index 0000000000..6131acc258 --- /dev/null +++ b/pkgs/mcpx/docs/home-example/fake-daemon.js @@ -0,0 +1,79 @@ +// The fake daemon for the home-page simulation (#1876, Approach C stage 2). +// +// The generated mcpx client talks to a daemon over plain HTTP and its hot +// path is one route, POST /v1/call (internal/codegen/emit.go). In a browser +// there is no daemon — so the page patches globalThis.fetch, answers the +// /v1 routes from the in-page mocks (mocks.js), and lets every other +// request through untouched. The client is the real one, emitted by +// `mcpx client` against the fixture servers (see generate-client.sh); only +// the transport's other end is simulated, and the page is labelled that +// way ("simulated — runs in your browser"). +// +// Routes the client can touch: +// POST /v1/call -> answered from mocks +// POST /v1/batch -> not simulated: an honest error, not a fake result +// GET /v1/resource -> not simulated: honest error +// GET /v1/artifacts -> not simulated: honest error +// +// installFakeDaemon() returns a restore function. Installing twice is a +// no-op that returns the existing restore. + +import { callMock } from "./mocks.js"; + +function json(body, status = 200) { + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); +} + +const NOT_SIMULATED = (route) => + json( + { + error: + `${route} is not part of the browser simulation; ` + + `the demo answers /v1/call only`, + }, + 501, + ); + +export function installFakeDaemon() { + if (globalThis.__mcpxFakeDaemon) return globalThis.__mcpxFakeDaemon.restore; + + const original = globalThis.fetch.bind(globalThis); + + const patched = async (input, init) => { + const raw = typeof input === "string" ? input : input.url; + let path; + try { + path = new URL(raw, "http://mcpx.invalid").pathname; + } catch { + return original(input, init); + } + + if (path.endsWith("/v1/call")) { + let req; + try { + req = JSON.parse(init?.body ?? "{}"); + } catch { + return json({ error: "fake daemon: /v1/call body is not JSON" }, 400); + } + const out = callMock(req.server, req.tool, req.args ?? {}); + return json(out); + } + if (path.endsWith("/v1/batch")) return NOT_SIMULATED("/v1/batch"); + if (path.endsWith("/v1/resource")) return NOT_SIMULATED("/v1/resource"); + if (path.endsWith("/v1/artifacts")) return NOT_SIMULATED("/v1/artifacts"); + + return original(input, init); + }; + + const restore = () => { + if (globalThis.fetch === patched) globalThis.fetch = original; + delete globalThis.__mcpxFakeDaemon; + }; + + globalThis.fetch = patched; + globalThis.__mcpxFakeDaemon = { restore }; + return restore; +} diff --git a/pkgs/mcpx/docs/home-example/generate-client.sh b/pkgs/mcpx/docs/home-example/generate-client.sh new file mode 100755 index 0000000000..8407ac3d7c --- /dev/null +++ b/pkgs/mcpx/docs/home-example/generate-client.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Regenerate the home-page example's client from the fixture servers. +# +# Acceptance on #1876: the page runs "the real generated client, emitted at +# docs build time by `mcpx client`/`mcpx types` against fixture servers — +# not a hand-written imitation". Until the site build lands (#1941), this +# script is that build step, run by hand and wired into the site pipeline +# later; client.ts and client.browser.js are checked in so the component +# is complete in the docs source. +# +# It builds mcpx and the deterministic fixture server (fakemcp), points an +# isolated mcpx installation at the fixture as the `demo` namespace (the +# arrangement examples/examples_test.go uses), emits the client, strips it +# for the browser, and stops the daemon it started. +# +# Usage: ./generate-client.sh [path-to-pkgs/mcpx] (default: ../..) +set -euo pipefail + +here="$(cd "$(dirname "$0")" && pwd)" +mcpx_root="${1:-$(cd "$here/../.." && pwd)}" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +export TMPDIR="${TMPDIR:-/tmp}" +(cd "$mcpx_root" && go build -o "$work/mcpx" ./cmd/mcpx) +(cd "$mcpx_root" && go build -o "$work/fakemcp" ./internal/testsupport/fakemcp) + +mkdir -p "$work/home" +printf '{"mcpServers":{"demo":{"command":"%s"}}}' "$work/fakemcp" > "$work/.mcpx.json" + +export HOME="$work/home" +export XDG_CONFIG_HOME="$work/xdg" +# DaemonSearchDirs() also searches $XDG_STATE_HOME/mcpx — isolate it too, +# or the stop below could see (and stop) the caller's own daemons. +export XDG_STATE_HOME="$work/xdg-state" +export MCPX_STATE_DIR="$work/state" +export MCPX_CACHE_DIR="$work/cache" +export MCPX_CONFIG="$work/.mcpx.json" +export MCPX_AUTOSTART_IDLE_EXIT=60s + +"$work/mcpx" client --ns demo -o "$here/client.ts" +# Stop ONLY this config's fixture daemon — never `stop --all`, which shuts +# down every live daemon found in the search dirs, including the caller's +# unrelated sessions. +"$work/mcpx" stop >/dev/null 2>&1 || true + +node "$here/strip-client.mjs" "$here/client.ts" "$here/client.browser.js" +echo "regenerated client.ts and client.browser.js from the demo fixture" diff --git a/pkgs/mcpx/docs/home-example/mocks.js b/pkgs/mcpx/docs/home-example/mocks.js new file mode 100644 index 0000000000..e5ff677ee3 --- /dev/null +++ b/pkgs/mcpx/docs/home-example/mocks.js @@ -0,0 +1,81 @@ +// The in-page mock namespaces for the home-page simulation (#1876 stage 2). +// +// Honest scope: the only namespace is `demo`, the deterministic fixture +// server from internal/testsupport/fakemcp, and only its deterministic +// tools are mirrored here — echo, open, state, wipe, structured, boom, +// fancy-name — with the same results the fixture returns (state is +// per-page-load here; the fixture's pid is reported as 0 because a browser +// tab has no pid worth printing). Tools whose behaviour is timing, +// notifications, or schema-version dependent (slow, chatty, summarise, +// create_issue, outage) are NOT imitated: the fake daemon answers them +// with an error that says they are outside the simulation, rather than a +// made-up result that teaches the reader something false. +// +// Call shape mirrors the daemon's /v1/call result: a returned object is +// `{ result: }`; `{ error: string }` is a transport- +// level failure, which the generated client surfaces as a ToolError. + +const state = []; + +function text(t) { + return { content: [{ type: "text", text: t }] }; +} + +export function callMock(server, tool, args = {}) { + if (server !== "demo") { + return { + error: + `the simulation only has the mock "demo" namespace; ` + + `"${server}" is not available in the browser demo`, + }; + } + switch (tool) { + case "echo": + return { result: text(String(args.message ?? "")) }; + case "open": { + const v = String(args.value ?? ""); + state.push(v); + return { result: text("opened " + v) }; + } + case "state": + return { + result: text(JSON.stringify({ pid: 0, seen: [...state] })), + }; + case "wipe": + state.length = 0; + return { result: text("wiped") }; + case "structured": + // The fixture's every-kind-of-block probe, unchanged. + return { + result: { + content: [ + { type: "text", text: `{"n":42}` }, + { type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" }, + { + type: "resource_link", + uri: "demo://greeting", + name: "greeting", + mimeType: "image/png", + }, + ], + structuredContent: { n: 42 }, + _meta: { "example.com/k": "result" }, + }, + }; + case "boom": + return { + result: { + isError: true, + content: [{ type: "text", text: "boom: deliberate failure" }], + }, + }; + case "fancy-name": + return { result: text(JSON.stringify(args)) }; + default: + return { + error: + `demo.${tool} is not part of the browser simulation; ` + + `run the example with "Copy as mcpx exec" to try it against a real daemon`, + }; + } +} diff --git a/pkgs/mcpx/docs/home-example/run-example.js b/pkgs/mcpx/docs/home-example/run-example.js new file mode 100644 index 0000000000..fe2c6b73d1 --- /dev/null +++ b/pkgs/mcpx/docs/home-example/run-example.js @@ -0,0 +1,202 @@ +// Run the (possibly edited) home-page example in the page (#1876 stage 2). +// +// The pieces, in order: +// 1. the fake daemon is installed (fake-daemon.js) so the generated +// client's POST /v1/call lands in the in-page mocks; +// 2. the real generated client's `tools` object (client.browser.js — +// client.ts after the build-time strip, see generate-client.sh) is +// put on globalThis, along with the client's standard script +// helpers (log, emit, call, ...) — the same surface `mcpx run` +// gives a script through installGlobals(); +// 3. the reader's source goes through the strip-only transform +// (strip-types.js) and is imported as a blob module, so top-level +// await works exactly as it does under mcpx; +// 4. console.log output is captured line by line into the output pane +// for the duration of the run, then everything is restored. +// +// Errors — a ToolError from a mock, a strip-types refusal, a syntax error +// in an edit — are reported through onLine as `error: ...` lines, the way +// a terminal run would print them, not swallowed. + +import { installFakeDaemon } from "./fake-daemon.js"; +import { stripTypes } from "./strip-types.js"; + +/** + * The standard script globals the real runner installs before importing + * a script (internal/runner/runner.go: installGlobals() from the + * generated client). `tools` is handled separately by the caller; these + * are the rest of the named helpers. Namespace objects stay behind + * `tools.*` — the flattening installGlobals also does (a bare `demo` + * global per namespace) is deliberately not reproduced on a docs page. + */ +export const SCRIPT_GLOBALS = [ + "log", + "emit", + "call", + "batch", + "readResource", + "artifact", + "ToolError", + "paths", + "here", + "hereDir", + "releaseConsole", + "captureFrames", + "errorFrames", + "search", + "transport", + "describe", +]; + +/** + * Install the client's script helpers on globalThis for one run, the + * installGlobals way (a name already present is left alone), and return + * a restore function that removes exactly what was installed. + */ +export function installScriptGlobals(client) { + const installed = []; + for (const name of SCRIPT_GLOBALS) { + if (client?.[name] === undefined) continue; + if (name in globalThis) continue; + globalThis[name] = client[name]; + installed.push(name); + } + return () => { + for (const name of installed) delete globalThis[name]; + }; +} + +// The client's log/emit records reach the page as console.error lines +// prefixed with this sentinel (client.ts: LOG_SENTINEL + JSON, through +// writeStderr's browser fallback). The sentinel must match the client's. +const RECORD_SENTINEL = "\u001emcpx\u001e"; + +/** Render one client record line for the output pane, or null if the + * line is not a client record. */ +export function formatRecordLine(line) { + if (typeof line !== "string" || !line.startsWith(RECORD_SENTINEL)) return null; + let record; + try { + record = JSON.parse(line.slice(RECORD_SENTINEL.length)); + } catch { + return null; + } + if (record.kind === "result") return format(record.value); + if (record.kind === "log") { + const attrs = record.attrs ?? {}; + const { args, ...rest } = attrs; + // The client sends the message uninterpolated, plus the template; + // the real runner interpolates {name} from attrs (internal/logging: + // Interpolate — {{ and }} are escapes, a missing key stays as-is) + // and does not repeat the consumed attributes afterwards. + const template = String(record.template ?? record.msg ?? ""); + const used = new Set(); + const rendered = template.replace( + /\{\{|\}\}|\{([a-zA-Z_][a-zA-Z0-9_.-]*)\}/g, + (m, name) => { + if (m === "{{") return "{"; + if (m === "}}") return "}"; + if (!(name in rest)) return m; + used.add(name); + return valueString(rest[name]); + }, + ); + const parts = [rendered]; + for (const a of args ?? []) parts.push(format(a)); + const leftover = Object.keys(rest).filter((k) => !used.has(k)); + if (leftover.length > 0) { + parts.push(leftover.map((k) => `${k}=${format(rest[k])}`).join(" ")); + } + return parts.filter((x) => x !== "").join(" "); + } + return null; +} + +/** A log attribute as the runner renders it in a message + * (internal/logging: valueString). */ +function valueString(v) { + if (v === null || v === undefined) return "null"; + if (typeof v === "string") return v; + if (typeof v === "number" || typeof v === "boolean") return String(v); + try { + return JSON.stringify(v) ?? String(v); + } catch { + return String(v); + } +} + +function format(value) { + if (typeof value === "string") return value; + if (value instanceof Error) return value.message; + try { + return JSON.stringify(value) ?? String(value); + } catch { + return String(value); + } +} + +// Runs are serialized on a module-level chain: a run replaces shared page +// globals (fetch, tools, console.log) and restores them at the end, so two +// overlapping runs would restore each other's swaps mid-flight. Callers +// also disable the Run button, but the invariant lives here so no caller +// can break it. +let runTail = Promise.resolve(); + +export function runExample(source, client, onLine) { + const run = runTail.then(() => runExampleOnce(source, client, onLine)); + runTail = run.catch(() => {}); + return run; +} + +async function runExampleOnce(source, client, onLine) { + const restoreFetch = installFakeDaemon(); + const hadTools = "tools" in globalThis; + const prevTools = globalThis.tools; + const prevLog = console.log; + const prevError = console.error; + globalThis.tools = client?.tools; + const restoreGlobals = installScriptGlobals(client); + console.log = (...args) => onLine(args.map(format).join(" ")); + // The client's log/emit helpers write their records through + // console.error (see formatRecordLine); surface those in the pane + // and let genuine errors through to the page's own console. + console.error = (...args) => { + const rendered = args.length === 1 ? formatRecordLine(args[0]) : null; + if (rendered !== null) onLine(rendered); + else prevError(...args); + }; + try { + const code = stripTypes(source); + const url = URL.createObjectURL( + new Blob([code], { type: "text/javascript" }), + ); + try { + const mod = await import(/* @vite-ignore */ url); + // Mirror the real runner (internal/runner/runner.go): a default + // export is the program's main. Invoke it with the (empty) argv + // array and print a non-undefined return value — an edit shaped + // as `export default () => ...` must behave in the simulation + // exactly as the copied command behaves against a real daemon. + const entry = mod?.default; + if (typeof entry === "function") { + const value = await entry([]); + if (value !== undefined) { + console.log( + typeof value === "string" ? value : JSON.stringify(value, null, 2), + ); + } + } + } finally { + URL.revokeObjectURL(url); + } + } catch (e) { + onLine("error: " + format(e)); + } finally { + console.log = prevLog; + console.error = prevError; + if (hadTools) globalThis.tools = prevTools; + else delete globalThis.tools; + restoreGlobals(); + restoreFetch(); + } +} diff --git a/pkgs/mcpx/docs/home-example/smoke-test.mjs b/pkgs/mcpx/docs/home-example/smoke-test.mjs new file mode 100644 index 0000000000..1b8bf1c32b --- /dev/null +++ b/pkgs/mcpx/docs/home-example/smoke-test.mjs @@ -0,0 +1,359 @@ +// Smoke test for the home-page example component (#1876 stages 1-2). +// +// Run with Node (>= 22, for node:module type stripping of client.ts if the +// browser build has not been generated yet): +// +// node smoke-test.mjs +// +// Three checks, no browser needed: +// 1. Stage 1 round-trip: execCommand(source) pasted into a real shell +// delivers the source to `mcpx exec` verbatim — apostrophes, dollar +// signs, backticks and a line that reads MCPX_EOF included. A stub +// `mcpx` captures its argument, standing in for the reader's daemon +// run (the acceptance check "pasted into a terminal, runs against a +// real local daemon" is this same command with the real binary). +// 2. Stage 2 end-to-end: the fake daemon + the REAL generated client + +// example.ts produce the example's expected output. +// 3. The strip-only transform runs a typed edit of the example. +// +// #1941 (site build) should wire this into the docs CI pipeline. + +import { execCommand, scriptCommands } from "./copy-command.js"; +import { installFakeDaemon } from "./fake-daemon.js"; +import { formatRecordLine, installScriptGlobals } from "./run-example.js"; +import { stripTypes } from "./strip-types.js"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync, readFileSync, writeFileSync, existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, dirname } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const here = dirname(fileURLToPath(import.meta.url)); +let failures = 0; +const check = (name, ok, detail = "") => { + console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? " — " + detail : ""}`); + if (!ok) failures++; +}; + +// --- 1. copy-as-command round-trips through a shell ----------------------- +{ + const dir = mkdtempSync(join(tmpdir(), "mcpx-home-example-")); + const out = join(dir, "captured.txt"); + writeFileSync( + join(dir, "mcpx"), + `#!/bin/sh\nprintf '%s' "$2" > ${JSON.stringify(out)}\n`, + { mode: 0o755 }, + ); + const source = + `const s = await tools.demo.echo({ message: "it's $HOME \`whoami\`" });\n` + + `// MCPX_EOF on its own line must not end the heredoc early\n` + + `MCPX_EOF\nconsole.log(s);`; + const cmd = execCommand(source); + execFileSync("bash", ["-c", cmd], { + env: { ...process.env, PATH: `${dir}:${process.env.PATH}` }, + }); + const captured = readFileSync(out, "utf8"); + // Command substitution strips trailing newlines; the source has none. + check("stage1: mcpx exec receives the source verbatim", captured === source); + + const script = scriptCommands("home-example", source); + check( + "stage1: script form saves then runs the named script", + script.includes("cat > .mcpx/scripts/home-example.ts") && + script.trimEnd().endsWith("mcpx run home-example"), + ); +} + +// --- 1b. strip-types is syntax-aware: literals and comments are data ----- +{ + check( + "strip: `as` inside a string literal is preserved", + stripTypes(`console.log("copy as script");`) === + `console.log("copy as script");`, + ); + check( + "strip: template text and comments preserved, real casts still stripped", + stripTypes( + "const s = `hi ${name as string}`; // keep as is\nconsole.log(s as string);", + ) === "const s = `hi ${name}`; // keep as is\nconsole.log(s);", + ); + check( + "strip: annotation-shaped text inside a string is preserved", + stripTypes(`const label: string = "value: string = x";`) === + `const label = "value: string = x";`, + ); +} + +// --- 1c. strip-types: object properties are not parameter annotations ---- +{ + const objLine = + "const expected = 1, actual = 2;\n" + + "console.log({ first: 0, actual: expected, last: 0 }.actual);"; + check( + "strip: object property after a comma keeps its value", + stripTypes(objLine) === objLine, + stripTypes(objLine), + ); + check( + "strip: declarations, arrows and methods still strip", + stripTypes( + "function f(a: number, b?: string): void {}\n" + + "const g = (x: number): number => x;\n" + + "class C { run(v: string): string { return v; } }", + ) === + "function f(a, b) {}\nconst g = (x) => x;\nclass C { run(v) { return v; } }", + stripTypes( + "function f(a: number, b?: string): void {}\n" + + "const g = (x: number): number => x;\n" + + "class C { run(v: string): string { return v; } }", + ), + ); + check( + "strip: default-value object literals keep their properties", + stripTypes("function h(o = { a: 1, b: 2 }, n: number): void {}") === + "function h(o = { a: 1, b: 2 }, n) {}", + stripTypes("function h(o = { a: 1, b: 2 }, n: number): void {}"), + ); +} + +// --- 1d. strip-types: regex literals are protected, division is not ------- +{ + check( + "strip: a regex containing annotation-shaped text is preserved", + stripTypes("console.log(/ as string /.source);") === + "console.log(/ as string /.source);", + ); + check( + "strip: division still reads as code", + stripTypes("const x: number = a / b / c;") === "const x = a / b / c;", + ); + check( + "strip: a regex after a keyword is preserved, flags included", + stripTypes("function t(s: string): boolean { return /a: string/i.test(s); }") === + "function t(s) { return /a: string/i.test(s); }", + stripTypes("function t(s: string): boolean { return /a: string/i.test(s); }"), + ); +} + +// --- 1d2. strip-types: literals inside a construct do not split it ---------- +{ + const greet = + 'function greet(name: string = "world"): string { return name; }\n' + + "console.log(greet());"; + check( + "strip: a string default does not split the parameter list", + stripTypes(greet) === + 'function greet(name = "world") { return name; }\nconsole.log(greet());', + stripTypes(greet), + ); + check( + "strip: a comment inside a parameter list does not split it either", + stripTypes("function f(a: number, /* units */ b: string): void {}") === + "function f(a, /* units */ b) {}", + stripTypes("function f(a: number, /* units */ b: string): void {}"), + ); +} + +// --- 1d3. strip-types: an assertion never eats its literal operand ---------- +{ + check( + "strip: a cast on a string literal keeps the literal", + stripTypes('console.log("hello" as string);') === + 'console.log("hello");', + stripTypes('console.log("hello" as string);'), + ); + check( + "strip: a cast in a declaration keeps the value", + stripTypes('const message = "hello" as string;') === + 'const message = "hello";', + stripTypes('const message = "hello" as string;'), + ); +} + +// --- 1d4. strip-types: declarations are removed whole, literals included --- +{ + check( + "strip: a string-literal union type alias leaves nothing behind", + stripTypes('type Mode = "fast" | "slow";\nconsole.log("fast");') === + '\nconsole.log("fast");', + stripTypes('type Mode = "fast" | "slow";\nconsole.log("fast");'), + ); + check( + "strip: an interface with a literal union member is removed whole", + stripTypes('interface Cfg { mode: "fast" | "slow" }\nconst x = 1;') === + "\nconst x = 1;", + stripTypes('interface Cfg { mode: "fast" | "slow" }\nconst x = 1;'), + ); +} + +// --- 1e. run-example: script globals + client record lines ------------------ +{ + const fakeClient = { log: () => {}, emit: () => {}, describe: () => "" }; + const restore = installScriptGlobals(fakeClient); + check( + "run: script globals are installed for the run", + globalThis.log === fakeClient.log && globalThis.emit === fakeClient.emit, + ); + restore(); + check( + "run: script globals are removed afterwards", + !("log" in globalThis) && !("emit" in globalThis), + ); + globalThis.log = "page's own"; + const restore2 = installScriptGlobals(fakeClient); + check( + "run: a pre-existing global is left alone (installGlobals semantics)", + globalThis.log === "page's own", + ); + restore2(); + delete globalThis.log; + + const sentinel = "\u001emcpx\u001e"; + check( + "run: an emit record renders its value", + formatRecordLine(sentinel + JSON.stringify({ kind: "result", value: "hi" })) === + "hi", + ); + check( + "run: a log record renders message and args", + formatRecordLine( + sentinel + + JSON.stringify({ kind: "log", msg: "starting", attrs: { args: [42] } }), + ) === "starting 42", + ); + check( + "run: a non-record console.error line is not a record", + formatRecordLine("some plain error") === null, + ); + check( + "run: a log template is interpolated and its attrs consumed", + formatRecordLine( + sentinel + + JSON.stringify({ + kind: "log", + msg: "fetched {count} pages", + template: "fetched {count} pages", + attrs: { count: 3 }, + }), + ) === "fetched 3 pages", + ); + check( + "run: escaped braces render literally, missing keys stay, leftovers append", + formatRecordLine( + sentinel + + JSON.stringify({ + kind: "log", + msg: "use {{x}} for {missing}", + template: "use {{x}} for {missing}", + attrs: { other: 1 }, + }), + ) === "use {x} for {missing} other=1", + ); +} + +// --- 2+3. fake daemon + real generated client ----------------------------- +const clientPath = existsSync(join(here, "client.browser.js")) + ? join(here, "client.browser.js") + : join(here, "client.ts"); // Node strips its types on import. + +async function runSource(source) { + const lines = []; + const prevLog = console.log; + // Braces, deliberately: console.log returns undefined, and a default + // export that ends in a log call must "return" undefined too — an + // expression-bodied capture would hand back push()'s count and the + // runner mirror below would print it as the script's result. + console.log = (...args) => { + lines.push(args.map((a) => (typeof a === "string" ? a : String(a))).join(" ")); + }; + try { + const dir = mkdtempSync(join(tmpdir(), "mcpx-home-run-")); + const mod = join(dir, "example.mjs"); + writeFileSync(mod, stripTypes(source)); + // Mirror runExampleOnce (run-example.js), which mirrors the real + // runner: import, then invoke a function default export with an + // empty argv array and print a non-undefined return value. + const imported = await import(pathToFileURL(mod).href + `?t=${Date.now()}`); + if (typeof imported?.default === "function") { + const value = await imported.default([]); + if (value !== undefined) { + console.log( + typeof value === "string" ? value : JSON.stringify(value, null, 2), + ); + } + } + } finally { + console.log = prevLog; + } + return lines; +} + +{ + const restore = installFakeDaemon(); + try { + const { tools } = await import(pathToFileURL(clientPath).href); + globalThis.tools = tools; + + const example = readFileSync(join(here, "example.ts"), "utf8"); + const lines = await runSource(example); + check( + "stage2: in-browser example runs end-to-end against the fake daemon", + lines.join("\n") === "demo.echo: hello from a script", + lines.join("\n"), + ); + + const typed = + `interface Opts { message: string }\n` + + `type Alias = string;\n` + + `const opts: Opts = { message: "typed edit" };\n` + + `const echoed: string = await tools.demo.echo(opts);\n` + + `console.log("demo.echo:", echoed as string);`; + const typedLines = await runSource(typed); + check( + "stage2: strip-only transform runs a typed edit", + typedLines.join("\n") === "demo.echo: typed edit", + typedLines.join("\n"), + ); + + const objLines = await runSource( + "const expected = 1, actual = 2;\n" + + "console.log({ first: 0, actual: expected, last: 0 }.actual);", + ); + check( + "stage2: object-property example prints the same as the copied command", + objLines.join("\n") === "1", + objLines.join("\n"), + ); + + const defLines = await runSource( + `export default () => console.log("ran via default export");`, + ); + check( + "stage2: a default-export edit is invoked like the real runner", + defLines.join("\n") === "ran via default export", + defLines.join("\n"), + ); + + const greetLines = await runSource( + 'function greet(name: string = "world"): string { return name; }\n' + + "console.log(greet());", + ); + check( + "stage2: an edit with a string default parameter runs", + greetLines.join("\n") === "world", + greetLines.join("\n"), + ); + + const defRetLines = await runSource(`export default () => "returned";`); + check( + "stage2: a default export's return value is printed", + defRetLines.join("\n") === "returned", + defRetLines.join("\n"), + ); + } finally { + delete globalThis.tools; + restore(); + } +} + +process.exit(failures === 0 ? 0 : 1); diff --git a/pkgs/mcpx/docs/home-example/strip-client.mjs b/pkgs/mcpx/docs/home-example/strip-client.mjs new file mode 100644 index 0000000000..69bf4dd05b --- /dev/null +++ b/pkgs/mcpx/docs/home-example/strip-client.mjs @@ -0,0 +1,26 @@ +// Build-time half of generate-client.sh: strip the types from the real +// generated client (client.ts) into client.browser.js, which a browser can +// import directly. Uses Node's own strip-only transform — the same +// erasable-syntax contract the client is written to (docs/story.md, +// "Runtime portability") — so the browser artifact is the generated client +// verbatim minus annotations, never a hand-maintained copy. +// +// Usage: node strip-client.mjs client.ts client.browser.js + +import { stripTypeScriptTypes } from "node:module"; +import { readFileSync, writeFileSync } from "node:fs"; + +const [input, output] = process.argv.slice(2); +if (!input || !output) { + console.error("usage: node strip-client.mjs "); + process.exit(2); +} +const src = readFileSync(input, "utf8"); +const stripped = stripTypeScriptTypes(src); +writeFileSync( + output, + "// Generated from client.ts by strip-client.mjs (strip-only). Do not edit;\n" + + "// regenerate with generate-client.sh.\n" + + stripped, +); +console.log(`stripped ${input} -> ${output}`); diff --git a/pkgs/mcpx/docs/home-example/strip-types.js b/pkgs/mcpx/docs/home-example/strip-types.js new file mode 100644 index 0000000000..32ebd8d400 --- /dev/null +++ b/pkgs/mcpx/docs/home-example/strip-types.js @@ -0,0 +1,500 @@ +// A strip-only TypeScript transform for the home-page example (#1876). +// +// Why strip-only: the generated mcpx client is written to run under Node's +// strip-only TypeScript mode (docs/story.md, "Runtime portability"), and +// the docs examples are written the same way. The page needs the same +// favour for the reader's *edits* to example.ts — change a line, press Run +// — without shipping a compiler. (Candidates weighed in the issue: sucrase +// is the small real stripper, esbuild-wasm and tsc are megabytes. When the +// site build lands in #1941 it may swap this module for sucrase behind the +// same signature; the component does not care.) +// +// What this handles — the erasable subset docs examples use: +// - `interface X { ... }` and `type X = ...;` declarations (removed) +// - annotations on variable declarations: `const x: T = ...` +// - parameter and return annotations: `function f(a: T): R { ... }`, +// `(a: T) => ...` +// - `as T` casts (removed) +// - optional parameters `a?: T` +// +// What it refuses, loudly, rather than mistranslating: enums, namespaces, +// parameter properties (`constructor(private x)`), and decorators. An +// unsupported edit produces a clear error in the output pane — never a +// silently different program. Anything outside the subset above may also +// fail to strip; the failure mode is a syntax error on import, shown in +// the pane, not wrong behaviour. + +const TYPE = String.raw`[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*(?:\s*<[^<>;{}()]*>)?(?:\s*\[\])*(?:\s*\|\s*[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*(?:\s*<[^<>;{}()]*>)?(?:\s*\[\])*)*\??`; + +function removeBalanced(src, start) { + // start is at the opening '{' — return the index just past its match. + let depth = 0; + for (let i = start; i < src.length; i++) { + if (src[i] === "{") depth++; + else if (src[i] === "}") { + depth--; + if (depth === 0) return i + 1; + } + } + throw new Error("strip-types: unbalanced braces in type declaration"); +} + +function interfaceSpans(src) { + const re = /(?:^|\n)[ \t]*(?:export\s+)?interface\s+[A-Za-z_$][\w$]*[^{]*\{/g; + const spans = []; + let m; + while ((m = re.exec(src)) !== null) { + const brace = m.index + m[0].length - 1; + const end = removeBalanced(src, brace); + spans.push([m.index, end]); + re.lastIndex = end; + } + return spans; +} + +function typeAliasSpans(src) { + const re = /(?:^|\n)[ \t]*(?:export\s+)?type\s+[A-Za-z_$][\w$]*(?:\s*<[^>]*>)?\s*=\s*/g; + const spans = []; + let m; + while ((m = re.exec(src)) !== null) { + // Scan to the terminating ';' at depth 0 (object types contain braces). + let depth = 0; + let i = re.lastIndex; + for (; i < src.length; i++) { + const c = src[i]; + if (c === "{" || c === "(" || c === "[") depth++; + else if (c === "}" || c === ")" || c === "]") depth--; + else if (c === ";" && depth === 0) break; + } + spans.push([m.index, i + 1]); + re.lastIndex = i + 1; + } + return spans; +} + +/** + * Deletion spans for a regex pass whose replacement keeps a prefix of + * each match: kept(m) is how many leading characters survive (the + * parenthesised group for annotation passes, 1 for the return pass's + * ')', 0 for `as` casts, whose whole match is deleted). + */ +function passSpans(src, re, kept) { + const spans = []; + let m; + while ((m = re.exec(src)) !== null) { + const k = typeof kept === "function" ? kept(m) : kept; + if (m[0].length > k) spans.push([m.index + k, m.index + m[0].length]); + if (m[0].length === 0) re.lastIndex++; + } + return spans; +} + +// --- Syntax-aware segmentation ------------------------------------------- +// The regex passes below must never rewrite text inside string literals, +// template-literal text, or comments: a reader's edit such as +// console.log("copy as script") is data, not an `as` cast. segmentize() +// splits the source into code and protected segments; the structural +// passes then run on the whole source with protected segments masked +// to spaces (lengths preserved), so a construct split by a literal — +// a parameter list with a string default — is still seen whole. +// Template ${...} interpolations are code and are segmented +// recursively. Regex literals are protected too (see regexAllowedHere). + +function skipQuoted(src, i, quote) { + // i is at the opening quote; return the index just past the closer. + i++; + while (i < src.length) { + if (src[i] === "\\") i += 2; + else if (src[i] === quote) return i + 1; + else i++; + } + return src.length; +} + +function scanExprEnd(src, i) { + // i is just past a template '${'; return the index of its matching '}', + // skipping nested strings, templates, and comments. + let depth = 1; + while (i < src.length) { + const c = src[i]; + if (c === '"' || c === "'") i = skipQuoted(src, i, c); + else if (c === "`") i = skipTemplate(src, i); + else if (c === "/" && src[i + 1] === "/") { + const j = src.indexOf("\n", i); + i = j < 0 ? src.length : j; + } else if (c === "/" && src[i + 1] === "*") { + const j = src.indexOf("*/", i + 2); + i = j < 0 ? src.length : j + 2; + } else if (c === "{") { + depth++; + i++; + } else if (c === "}") { + depth--; + if (depth === 0) return i; + i++; + } else i++; + } + return src.length; +} + +function skipTemplate(src, i) { + // i is at the opening backtick; return the index just past the closer. + i++; + while (i < src.length) { + if (src[i] === "\\") i += 2; + else if (src[i] === "`") return i + 1; + else if (src[i] === "$" && src[i + 1] === "{") i = scanExprEnd(src, i + 2) + 1; + else i++; + } + return src.length; +} + +// A '/' opens a regex literal only where a value cannot stand: at the +// start, after an operator or opener, or after a keyword like return. +// After an operand (identifier, number, ')', ']', a string) it is +// division. segmentize() tracks just enough history for that call — +// regex literals are protected segments, like strings, because a +// pattern can contain text the stripping passes would otherwise eat +// (/ as string / lost its pattern to the `as` pass). +const REGEX_KEYWORDS = new Set([ + "return", "typeof", "instanceof", "in", "of", "new", "delete", + "void", "case", "do", "else", "yield", "await", "throw", +]); + +function regexAllowedHere(history) { + const tail = history.replace(/\s+$/, ""); + if (tail === "") return true; + const last = tail[tail.length - 1]; + if (/[\w$]/.test(last)) { + const word = /([A-Za-z_$][\w$]*)$/.exec(tail)?.[1] ?? ""; + return REGEX_KEYWORDS.has(word); + } + // Operand enders: a value just ended, so '/' divides. + if (last === ")" || last === "]" || last === "}" || last === '"') return false; + return true; +} + +function scanRegexEnd(src, i) { + // i is at the opening '/'; return the index just past the flags, or + // -1 if this is not a well-formed literal on one line. + let inClass = false; + let j = i + 1; + while (j < src.length) { + const c = src[j]; + if (c === "\\") j += 2; + else if (c === "\n") return -1; + else if (c === "[") { inClass = true; j++; } + else if (c === "]") { inClass = false; j++; } + else if (c === "/" && !inClass) { + j++; + while (j < src.length && /[a-z]/.test(src[j])) j++; + return j; + } else j++; + } + return -1; +} + +function segmentize(src) { + const segs = []; + let code = ""; + // The recent code history, for the regex/division decision: code + // characters as scanned, '"' as the marker for a just-ended operand + // segment (string, template, regex), ' ' for a comment. + let history = ""; + const flushCode = () => { + if (code) { + segs.push({ code: true, text: code }); + code = ""; + } + }; + const prot = (text, marker = '"') => { + flushCode(); + if (text) segs.push({ code: false, text }); + history += marker; + }; + let i = 0; + while (i < src.length) { + const c = src[i]; + const n = src[i + 1]; + if (c === "/" && n === "/") { + let j = src.indexOf("\n", i); + if (j < 0) j = src.length; + prot(src.slice(i, j), " "); + i = j; + } else if (c === "/" && n === "*") { + let j = src.indexOf("*/", i + 2); + j = j < 0 ? src.length : j + 2; + prot(src.slice(i, j), " "); + i = j; + } else if (c === "/" && regexAllowedHere(history)) { + const j = scanRegexEnd(src, i); + if (j > 0) { + prot(src.slice(i, j)); + i = j; + } else { + code += c; + history += c; + i++; + } + } else if (c === '"' || c === "'") { + const j = skipQuoted(src, i, c); + prot(src.slice(i, j)); + i = j; + } else if (c === "`") { + // Literal chunks are protected; ${...} expressions are code. + let j = i + 1; + let chunkStart = i; + while (j < src.length) { + if (src[j] === "\\") { + j += 2; + continue; + } + if (src[j] === "`") { + j++; + break; + } + if (src[j] === "$" && src[j + 1] === "{") { + prot(src.slice(chunkStart, j + 2)); // chunk incl. the '${' + const end = scanExprEnd(src, j + 2); + for (const s of segmentize(src.slice(j + 2, end))) segs.push(s); + chunkStart = end; // the closing '}' starts the next chunk + j = end + 1; + continue; + } + j++; + } + prot(src.slice(chunkStart, j)); + i = j; + } else { + code += c; + history += c; + i++; + } + } + flushCode(); + return segs; +} + +// --- Parameter annotations ------------------------------------------------ +// The naive pass — "an identifier after '(' or ',' followed by ': Type' +// and then ',', ')' or '='" — cannot tell a parameter list from an object +// literal inside a call: `{ first: 0, actual: expected }` matches it, and +// stripping there silently rewrites a property into shorthand, changing +// what the program computes. So annotations are stripped only inside +// paren groups that are actually parameter lists, and only at the +// group's own depth (an object literal in a default value is nested, +// and its properties are data, not annotations). + +const CONTROL_KEYWORDS = new Set(["if", "for", "while", "switch", "catch", "with"]); + +function findMatchingParen(src, open) { + let depth = 0; + for (let i = open; i < src.length; i++) { + if (src[i] === "(") depth++; + else if (src[i] === ")") { + depth--; + if (depth === 0) return i; + } + } + return -1; +} + +function isParamList(src, open, close) { + // What follows the group decides: an optional return annotation, then + // a body ('{') or an arrow ('=>'). A call is followed by neither. + let rest = src.slice(close + 1).replace(/^\s+/, ""); + if (rest.startsWith(":")) { + const t = new RegExp(String.raw`^:\s*` + TYPE).exec(rest); + if (!t) return false; + rest = rest.slice(t[0].length).replace(/^\s+/, ""); + } + if (!rest.startsWith("{") && !rest.startsWith("=>")) return false; + // Control-flow parens are followed by a body too, but hold no params. + const before = /(?:^|[^\w$.])([A-Za-z_$][\w$]*)\s*(?:<[^<>]*>)?\s*$/.exec( + src.slice(0, open), + ); + return !(before && CONTROL_KEYWORDS.has(before[1])); +} + +function maskNested(text) { + // Length-preserving: characters inside nested (), {} or [] become + // spaces (delimiters stay), so a match found in the masked text maps + // to the same span in the original. + let out = ""; + let depth = 0; + for (const c of text) { + if (c === "(" || c === "{" || c === "[") { + out += c; + depth++; + } else if (c === ")" || c === "}" || c === "]") { + depth--; + out += c; + } else out += depth > 0 ? " " : c; + } + return out; +} + +const PARAM_PASSES = [ + new RegExp(String.raw`([(,]\s*[A-Za-z_$][\w$]*)\?\s*:\s*` + TYPE + String.raw`(?=\s*[,)=])`, "g"), + new RegExp(String.raw`([(,]\s*[A-Za-z_$][\w$]*)\s*:\s*` + TYPE + String.raw`(?=\s*[,)=])`, "g"), +]; + +function groupParamSpans(inner, base, spans) { + // The passes anchor on the '(' or ',' before a parameter and look + // ahead to the ',', ')' or '=' after its type; the group's own parens + // are not part of `inner`, so matches are found in a copy lent a + // synthetic comma before and a synthetic ')' after. maskNested keeps + // nested spans (object literals in defaults) from matching, at the + // same offsets. Span coordinates are converted back by dropping the + // one synthetic leading character. + const masked = maskNested("," + inner + ")"); + for (const re of PARAM_PASSES) { + re.lastIndex = 0; + let m; + while ((m = re.exec(masked)) !== null) { + spans.push([base + m.index + m[1].length - 1, base + m.index + m[0].length - 1]); + } + } +} + +function collectParamSpans(src, base, spans) { + let i = 0; + while (i < src.length) { + const open = src.indexOf("(", i); + if (open < 0) return; + const close = findMatchingParen(src, open); + if (close < 0) return; + // Nested groups first: an arrow in a default value or an argument + // has its own parameter list, judged on its own merits. + collectParamSpans(src.slice(open + 1, close), base + open + 1, spans); + if (isParamList(src, open, close)) { + groupParamSpans(src.slice(open + 1, close), base + open + 1, spans); + } + i = close + 1; + } +} + +// The structural passes run on the WHOLE source with protected +// segments masked to spaces (newlines kept, lengths preserved), never +// on isolated segments: a parameter list split by a string default — +// function greet(name: string = "world") — is one list, and only the +// whole-source view can see it. Masking is length-preserving, so a +// deletion span found in the masked text is a span of the original; +// every pass below only ever deletes (annotations, casts, type +// declarations), so the transform is: collect spans, merge, cut. +function maskProtected(source) { + return segmentize(source) + .map((s) => (s.code ? s.text : s.text.replace(/[^\n]/g, " "))) + .join(""); +} + +/** + * The [start, end) ranges of the original that are protected literals + * or comments. A deletion span must never cut into one: a pass can + * legitimately reach into a masked literal — the `as` pass's leading + * \\s+ happily eats the spaces a masked string became — and cutting + * there would delete the literal itself from the output. + */ +function protectedRanges(source) { + const ranges = []; + let offset = 0; + for (const s of segmentize(source)) { + if (!s.code) ranges.push([offset, offset + s.text.length]); + offset += s.text.length; + } + return ranges; +} + +function subtractRanges(spans, ranges, source) { + const out = []; + for (const [a, b] of spans) { + let pieces = [[a, b]]; + for (const [pa, pb] of ranges) { + const next = []; + for (const [x, y] of pieces) { + if (pb <= x || pa >= y) { + next.push([x, y]); + continue; + } + if (pa > x) next.push([x, pa]); + if (pb < y) next.push([pb, y]); + } + pieces = next; + } + // A piece that is only whitespace is dropped too: splitting a span + // at a literal can leave the space before the literal as its own + // piece (`= "x" as string`), and cutting it would weld the literal + // to whatever precedes it. No real deletion is whitespace-only — + // every pass deletes at least a colon, a keyword, or a brace. + out.push( + ...pieces.filter( + ([x, y]) => y > x && !/^\s*$/.test(source.slice(x, y)), + ), + ); + } + return out; +} + +export function stripTypes(source) { + const masked = maskProtected(source); + if ( + /^\s*(?:export\s+)?(?:enum|namespace)\s/m.test(masked) || + /constructor\s*\([^)]*\b(?:private|public|protected|readonly)\b/.test(masked) + ) { + throw new Error( + "strip-types: enums, namespaces and parameter properties are not " + + "erasable and are not supported in the browser demo — remove them and run again", + ); + } + // Type and interface declarations are removed whole — including any + // literals inside them (`type Mode = "fast" | "slow";` must not leave + // `"fast""slow"` behind). Operand protection below applies only to + // the annotation/cast passes, never to a declaration span. + const declSpans = [ + ...interfaceSpans(masked), + ...typeAliasSpans(masked), + ]; + const spans = [ + // `as T` casts. + ...passSpans(masked, new RegExp(String.raw`\s+as\s+` + TYPE, "g"), 0), + // Variable annotations: const/let/var name: T (=|;) + ...passSpans( + masked, + new RegExp( + String.raw`(\b(?:const|let|var)\s+[A-Za-z_$][\w$]*)\s*:\s*` + + TYPE + + String.raw`(?=\s*[=;])`, + "g", + ), + (m) => m[1].length, + ), + // Return annotations: ): T { and ): T => + ...passSpans( + masked, + new RegExp(String.raw`\)\s*:\s*` + TYPE + String.raw`(?=\s*(?:\{|=>))`, "g"), + 1, + ), + ]; + collectParamSpans(masked, 0, spans); + + // No annotation/cast deletion may cut into a protected literal or + // comment; declaration spans are exempt (see declSpans above). + const cut = [ + ...declSpans, + ...subtractRanges(spans, protectedRanges(source), source), + ]; + cut.sort((a, b) => a[0] - b[0]); + spans.length = 0; + spans.push(...cut); + let out = ""; + let last = 0; + for (const [a, b] of spans) { + if (a >= last) { + out += source.slice(last, a); + last = b; + } else if (b > last) { + last = b; + } + } + return out + source.slice(last); +}