diff --git a/README.md b/README.md index f18eb58..4b93ae5 100644 --- a/README.md +++ b/README.md @@ -2,12 +2,13 @@ Runtime helpers for Apps that follow the **Lazurio Module Standard**: read the listener a Lazurio Platform assigned, answer health, shut down cleanly on -`SIGTERM`, and learn who came to the App and with which application role. +`SIGTERM`, learn who came to the App and with which application role, and +offer the App's tools to agents through `/mcp` and WebMCP. This is the **only shared runtime library of a Module**. It stays small on purpose: reading the runtime environment, health, shutdown and dev server -options. It is not a framework, it has no runtime dependencies, and anything -beyond that belongs in the Module itself. +options, and the one tool contract for agents. It is not a framework, it has +no runtime dependencies, and anything beyond that belongs in the Module itself. ## Install @@ -15,6 +16,9 @@ beyond that belongs in the Module itself. bun add github:Lazurio/module-kit#v0.3.0 ``` +The tools for agents (`/tools`, `/tools/testing`, `/webmcp`) come with the next +release; until it is tagged, `v0.3.0` has no tools. + The package ships TypeScript sources (`exports` and `types` point at `src/index.ts`). Bun runs them natively and there is no build step. The source uses only erasable syntax and compiles under `strict`, @@ -142,6 +146,114 @@ Python: `app_access(headers, "app")` takes the request headers as a mapping the same values, `"admin"` for the Application Admin and `"user"` for the Application User. +## Tools for agents + +An App defines its tools once, on its server, and offers them through two +transports over the same handler (Module Standard, "Agents in the App"): + +- `/mcp`: a stateless MCP server (Streamable HTTP, JSON answers, POST only, no + batches, body bounded to 64 KiB) behind the Application host's gateway, which + admits a Lazurio Auth Bearer token with the application's role; +- the page: `GET /api/agent-tools` lists the tools for the person who has the + page open and `POST /api/agent-tools/` calls one with the page's own + session (only from the App's own origin). `@lazurio/module-kit/webmcp` + registers them as WebMCP tools, so an agent with the App open in the + Environment browser calls them directly. + +Both read who came only through `appAccess`, list only the tools the role and +the writer mode allow, and refuse with the same codes. Every registry also +answers `get_app_context`: module, version, data generation, `production` or +`environment`, entry, role and whether the caller may change data now. + +```ts +import { z } from "zod"; +import { createToolRegistry, defineTool } from "@lazurio/module-kit/tools"; + +const FindInput = z.strictObject({ query: z.string().max(200) }); + +const registry = createToolRegistry({ + app: { module: "revisions", version: "1.4.0", dataGeneration: "v3" }, + tools: [ + defineTool({ + name: "find_revisions", + description: "Najde revize podle čísla, zákazníka nebo adresy.", + input: FindInput, + inputSchema: z.toJSONSchema(FindInput, { io: "input" }), + minRole: "user", + effect: "read", + untrustedContent: true, + // The same domain service the interface calls, never the data files. + run: async ({ query }, { access }) => ({ + ok: true, + data: { items: await revisions.find(query, access) }, + }), + }), + ], +}); + +Bun.serve({ + hostname: host, + port, + fetch: withHealth(async (request) => { + const path = new URL(request.url).pathname; + if (path === "/mcp") return registry.handleMcp(request); + return (await registry.handlePage(request)) ?? app(request); + }), +}); +``` + +On the page: + +```ts +import { registerAgentTools } from "@lazurio/module-kit/webmcp"; + +const tools = await registerAgentTools({ + // View tools of the page never change data. + viewTools: [{ name: "open_revision", description: "Otevře revizi.", + inputSchema: { type: "object", properties: { id: { type: "string" } } }, + execute: ({ id }) => router.open(id) }], +}); +// After a sign-in or a role change: await tools.refresh(); +``` + +**Effects.** `read` changes nothing (finding, reading, computing, producing a +file such as a PDF) and is offered in the read-only mode as well. `prepare` +changes no shared data and prepares a step a person completes in the interface +(an approval, a signature, a sending). `write` changes data and says with +`publishesData` whether the change is a publication of data (a commit and push +in repository-db, `DOLT_COMMIT` in a database) or a draft. A write is offered +only while `dataWriter` allows it (`LAZURIO_RUNTIME_DATA_WRITER=true`; unset +only to a local or Environment entry), and a write that publishes data is not +offered in a production application: there a person publishes in the +interface. The one exception is a kind of record for which the Owner allowed +agents to publish in advance, with the decision recorded: such a tool names it +in `publicationConsent` (a plan or decision reference), which is the person's +prior consent to that Publication. No tool completes an approval, a signature, a sending, a deletion +or a person's confirmation. + +**Answers and refusals.** A tool returns `{ ok: true, data, files? }` or +`{ ok: false, reason, message, current_revision?, details? }` and never throws +for an expected outcome. The common reasons are `identity_unavailable`, +`forbidden`, `unknown_tool`, `invalid_input`, `not_found`, `record_changed` +(with `current_revision`), `data_read_only`, `unavailable` and +`internal_error`; a Module adds domain reasons of its own. On `/mcp` a refusal +is a tool result with `isError` and `structuredContent`; a file is an embedded +resource. Every call writes one audit line (channel, tool, entry, subject, +role, outcome, duration), never the input or the answer. + +**A data layer that decides by the method.** Every tool call is a `POST`. +An App whose data layer chooses a read or a write path by the HTTP method asks +`registry.effectOf(request)` instead: the named tool's effect for `tools/call` +and page calls, `read` for other MCP methods and the manifest, and `null` +(treat as a write) for any other path or anything it cannot tell. It reads a copy, so the request stays +readable. + +**Tests.** `@lazurio/module-kit/tools/testing` builds requests as the gateway +states them (`gatewayRequest`, `hostedEnvironment`, `localEnvironment`) and +calls the registry (`mcpCall`, `mcpToolNames`, `mcpTool`, `pageTool`), so a +Module tests the list per role, the refusal without a role, writes in the +read-only mode and `record_changed` on both transports. + ## Bun.serve ```ts diff --git a/package.json b/package.json index c88b332..f28b0d2 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@lazurio/module-kit", - "version": "0.3.0", - "description": "Lazurio Module Standard runtime helpers: listener, health, shutdown, app access", + "version": "0.4.0", + "description": "Lazurio Module Standard runtime helpers: listener, health, shutdown, app access, tools for agents", "license": "MIT", "type": "module", "packageManager": "bun@1.4.2", @@ -13,6 +13,18 @@ ".": { "types": "./src/index.ts", "default": "./src/index.ts" + }, + "./tools": { + "types": "./src/tools.ts", + "default": "./src/tools.ts" + }, + "./tools/testing": { + "types": "./src/tools-testing.ts", + "default": "./src/tools-testing.ts" + }, + "./webmcp": { + "types": "./src/webmcp.ts", + "default": "./src/webmcp.ts" } }, "types": "./src/index.ts", diff --git a/src/tools-testing.ts b/src/tools-testing.ts new file mode 100644 index 0000000..79f2fc0 --- /dev/null +++ b/src/tools-testing.ts @@ -0,0 +1,184 @@ +/** + * Test helpers for a Module's tools: requests as the Application host's + * gateway states them, MCP calls and page calls. For tests only; the gateway + * removes every client copy of these headers in production. + */ +import { GATEWAY_HEADERS } from "./index.ts"; +import type { ToolRegistry } from "./tools.ts"; + +/** The external origin the helpers use unless told otherwise. */ +export const TEST_ORIGIN = "https://app.example-org.lazurio.app"; + +/** A runtime environment of an App on an Application host. */ +export function hostedEnvironment( + options: { + readonly origin?: string; + readonly writer?: boolean; + readonly listener?: string; + readonly extra?: Readonly>; + } = {}, +): Record { + const key = (options.listener ?? "app") + .toUpperCase() + .replace(/[^A-Z0-9]/g, "_"); + return { + [`LAZURIO_RUNTIME_LISTENER_${key}_HOST`]: "127.0.0.1", + [`LAZURIO_RUNTIME_LISTENER_${key}_PORT`]: "43100", + [`LAZURIO_RUNTIME_LISTENER_${key}_EXTERNAL_ORIGIN`]: + options.origin ?? TEST_ORIGIN, + LAZURIO_RUNTIME_DATA_WRITER: options.writer === true ? "true" : "false", + ...options.extra, + }; +} + +/** A runtime environment of a Module version in an Environment: no gateway, + * no writer flag. */ +export function localEnvironment(listener = "app"): Record { + const key = listener.toUpperCase().replace(/[^A-Z0-9]/g, "_"); + return { + [`LAZURIO_RUNTIME_LISTENER_${key}_HOST`]: "127.0.0.1", + [`LAZURIO_RUNTIME_LISTENER_${key}_PORT`]: "43100", + }; +} + +/** Who the gateway states: an Application User or Admin, a person with the + * whole Environment, or nobody (`none`, as an older gateway would). */ +export type GatewayCaller = + | { readonly role: "user" | "admin"; readonly subject?: string } + | { readonly role: "environment"; readonly subject?: string } + | { readonly role: "none" }; + +export const TEST_SUBJECT = "2659b76d-0000-4000-8000-000000000001"; + +/** A request through the gateway to the App's external origin. */ +export function gatewayRequest( + path: string, + options: { + readonly caller?: GatewayCaller; + readonly method?: string; + readonly body?: unknown; + readonly origin?: string | null; + readonly appOrigin?: string; + readonly headers?: Readonly>; + } = {}, +): Request { + const appOrigin = options.appOrigin ?? TEST_ORIGIN; + const caller = options.caller ?? { role: "user" }; + const headers: Record = { + host: new URL(appOrigin).host, + ...options.headers, + }; + if (options.body !== undefined) + headers["content-type"] ??= "application/json"; + if (options.origin !== undefined && options.origin !== null) + headers.origin = options.origin; + if (caller.role !== "none") { + headers[GATEWAY_HEADERS.subject] = caller.subject ?? TEST_SUBJECT; + headers[GATEWAY_HEADERS.username] = "test-person"; + if (caller.role === "environment") + headers[GATEWAY_HEADERS.entry] = "environment"; + else { + headers[GATEWAY_HEADERS.entry] = "app"; + headers[GATEWAY_HEADERS.appRole] = caller.role; + } + } + return new Request(new URL(path, appOrigin), { + method: options.method ?? (options.body === undefined ? "GET" : "POST"), + headers, + ...(options.body === undefined + ? {} + : { + body: + typeof options.body === "string" + ? options.body + : JSON.stringify(options.body), + }), + }); +} + +let nextId = 1; + +/** Sends one JSON-RPC request to `/mcp` and returns the HTTP status and the + * parsed answer. */ +export async function mcpCall( + registry: ToolRegistry, + method: string, + params: Record = {}, + options: { + readonly caller?: GatewayCaller; + readonly appOrigin?: string; + } = {}, +): Promise<{ status: number; body: Record }> { + const response = await registry.handleMcp( + gatewayRequest("/mcp", { + ...options, + body: { jsonrpc: "2.0", id: nextId++, method, params }, + }), + ); + const text = await response.text(); + return { + status: response.status, + body: text === "" ? {} : (JSON.parse(text) as Record), + }; +} + +/** The names `tools/list` returns for a caller. */ +export async function mcpToolNames( + registry: ToolRegistry, + caller: GatewayCaller, + appOrigin?: string, +): Promise { + const { body } = await mcpCall( + registry, + "tools/list", + {}, + { caller, ...(appOrigin === undefined ? {} : { appOrigin }) }, + ); + const result = body.result as { tools?: Array<{ name: string }> } | undefined; + return (result?.tools ?? []).map((tool) => tool.name).sort(); +} + +/** Calls a tool through `/mcp` and returns its structured answer. */ +export async function mcpTool( + registry: ToolRegistry, + name: string, + input: unknown, + caller: GatewayCaller = { role: "user" }, + appOrigin?: string, +): Promise<{ isError: boolean; structured: Record }> { + const { body } = await mcpCall( + registry, + "tools/call", + { name, arguments: input }, + { caller, ...(appOrigin === undefined ? {} : { appOrigin }) }, + ); + const result = body.result as + | { isError: boolean; structuredContent: Record } + | undefined; + if (result === undefined) + throw new Error(`No tool result: ${JSON.stringify(body)}`); + return { isError: result.isError, structured: result.structuredContent }; +} + +/** Calls a tool as the page does and returns the status and answer. */ +export async function pageTool( + registry: ToolRegistry, + name: string, + input: unknown, + caller: GatewayCaller = { role: "user" }, + appOrigin: string = TEST_ORIGIN, +): Promise<{ status: number; body: Record }> { + const response = await registry.handlePage( + gatewayRequest(`/api/agent-tools/${name}`, { + caller, + appOrigin, + origin: appOrigin, + body: input, + }), + ); + if (response === null) throw new Error("The page endpoint did not answer."); + return { + status: response.status, + body: (await response.json()) as Record, + }; +} diff --git a/src/tools.ts b/src/tools.ts new file mode 100644 index 0000000..2c0339e --- /dev/null +++ b/src/tools.ts @@ -0,0 +1,853 @@ +/** + * One tool contract for agents (Lazurio Module Standard, "Agents in the App"). + * + * A Module defines its tools once, on its server, and offers them through two + * transports over the same handler: + * + * - `/mcp`: a stateless MCP server (Streamable HTTP, JSON responses, POST + * only) behind the Application host's gateway, which admits a Lazurio Auth + * Bearer token with the application's role; + * - the page: a manifest and a call endpoint that the App's own page uses to + * register the same tools as WebMCP tools (`@lazurio/module-kit/webmcp`), + * called with the page's own session. + * + * Both read who came only through `appAccess`, list only the tools the role + * and the writer mode allow, and refuse with the same codes. A tool calls the + * Module's domain service, never the data files or SQL directly, so the data + * layer (repository-db in `app/v3`, Dolt in `app/v4`) changes under the tools + * without changing them. + */ +import { type AppAccess, appAccess, listener } from "./index.ts"; + +type Environment = Readonly>; + +/** The MCP protocol revisions this server speaks, newest first. */ +export const MCP_PROTOCOL_VERSIONS = [ + "2025-11-25", + "2025-06-18", + "2025-03-26", +] as const; + +/** The refusal codes every App answers with, on `/mcp`, on the page and in + * its own HTTP API. A Module may add domain refusals of its own + * (`snake_case`, for example `document_number_taken`). */ +export const REFUSAL_CODES = [ + "identity_unavailable", + "forbidden", + "unknown_tool", + "invalid_input", + "not_found", + "record_changed", + "data_read_only", + "unavailable", + "internal_error", +] as const; +export type RefusalCode = (typeof REFUSAL_CODES)[number]; + +/** What a tool does to the App's data: + * - `read`: changes nothing (finding, reading, computing, producing a file + * such as a PDF); offered in the read-only mode as well; + * - `prepare`: changes no shared data and prepares a step the person + * completes in the interface (an approval, a signature, a sending); + * - `write`: changes data. `publishesData` says whether the change is a + * publication of data (a commit and push in repository-db, `DOLT_COMMIT` in + * a database) or only a draft. */ +export type ToolEffect = "read" | "prepare" | "write"; + +/** The application role a tool needs at least. */ +export type ToolRole = "user" | "admin"; + +/** Where the call came from, recorded with the change and in the audit. */ +export type ToolChannel = "mcp" | "webmcp"; + +/** Where the App runs: an Organization's production application on an + * Application host, or a Module version in an Environment. */ +export type Deployment = "production" | "environment"; + +/** A JSON Schema object, as MCP and WebMCP carry it. */ +export type JsonSchema = Readonly>; + +/** The Standard Schema interface (https://standardschema.dev), which zod, + * valibot and others implement; module-kit depends on none of them. */ +export interface StandardSchemaV1 { + readonly "~standard": { + readonly version: 1; + readonly vendor: string; + readonly validate: ( + value: unknown, + ) => StandardResult | Promise>; + readonly types?: + | { readonly input: Input; readonly output: Output } + | undefined; + }; +} +type StandardIssue = { + readonly message: string; + readonly path?: + | ReadonlyArray + | undefined; +}; +type StandardResult = + | { readonly value: Output; readonly issues?: undefined } + | { readonly issues: ReadonlyArray }; + +/** An application role that came: never `unknown`. */ +export type KnownAccess = Exclude; + +/** What a tool's handler gets besides its input. */ +export interface ToolContext { + readonly access: KnownAccess; + readonly channel: ToolChannel; + readonly deployment: Deployment; + /** Whether this App may change data now (`dataWriter`). */ + readonly canWrite: boolean; + readonly request: Request; +} + +/** A file a tool produced, such as a PDF. */ +export interface ToolFile { + readonly name: string; + readonly mimeType: string; + readonly data: Uint8Array; +} + +/** A refusal: the reason code, a sentence for the agent and, for + * `record_changed`, the record's current revision. */ +export interface ToolRefusal { + readonly ok: false; + readonly reason: RefusalCode | (string & {}); + readonly message: string; + readonly current_revision?: string; + readonly details?: Readonly>; +} + +/** What a tool returns: JSON data (an object) and optional files, or a + * refusal. A tool never throws for an expected outcome. */ +export type ToolResult> = + | { + readonly ok: true; + readonly data: Data; + readonly files?: readonly ToolFile[]; + } + | ToolRefusal; + +interface ToolDefinitionBase { + /** `snake_case`, verb first, in English: `find_revisions`. */ + readonly name: string; + readonly title?: string; + /** In the Organization's language: what the tool does and returns. */ + readonly description: string; + /** Validates and types the input (zod, valibot…). */ + readonly input: StandardSchemaV1; + /** The same input as JSON Schema, as agents see it. */ + readonly inputSchema: JsonSchema; + readonly outputSchema?: JsonSchema; + readonly minRole: ToolRole; + /** Calling it twice with the same input changes nothing more. */ + readonly idempotent?: boolean; + /** Its answer carries text people or other systems wrote; the agent + * treats it as data, never as instructions. */ + readonly untrustedContent?: boolean; + readonly run: ( + input: Input, + context: ToolContext, + ) => Promise> | ToolResult; +} + +/** One tool of the App. */ +export type ToolDefinition = ToolDefinitionBase & + ( + | { + readonly effect: "read" | "prepare"; + readonly publishesData?: never; + readonly publicationConsent?: never; + } + | { + readonly effect: "write"; + readonly publishesData: boolean; + /** For a write that publishes data in a production application: where + * the Owner decided in advance that agents publish this kind of record + * (a plan or decision reference). That is the person's prior consent + * to the Publication; without it the tool is not offered there. */ + readonly publicationConsent?: string; + } + ); + +/** Types a tool from its input schema. */ +export function defineTool( + tool: ToolDefinition, +): ToolDefinition { + return tool; +} + +/** What an agent sees of a tool, on `/mcp` and on the page. */ +export interface ToolDescriptor { + readonly name: string; + readonly title?: string; + readonly description: string; + readonly inputSchema: JsonSchema; + readonly outputSchema?: JsonSchema; + readonly effect: ToolEffect; + readonly annotations: { + readonly title?: string; + readonly readOnlyHint: boolean; + readonly destructiveHint: boolean; + readonly idempotentHint: boolean; + readonly openWorldHint: boolean; + readonly untrustedContentHint: boolean; + }; +} + +/** The App this registry serves, as `get_app_context` reports it. */ +export interface AppInfo { + /** The Module's slug. */ + readonly module: string; + /** The App's released version (its `package.json` version). */ + readonly version: string; + /** The App generation, which names its data layer. */ + readonly dataGeneration: "v1" | "v2" | "v3" | "v4"; + readonly title?: string; + /** Rules of the domain the agent should know, in the Organization's + * language (MCP `instructions`). */ + readonly instructions?: string; +} + +/** One line of the audit: who called which tool and how it ended, never + * the input or the answer. */ +export interface ToolAuditEvent { + readonly event: "agent-tool"; + readonly channel: ToolChannel; + readonly tool: string; + readonly entry: AppAccess["entry"]; + readonly subject: string | null; + readonly appRole: AppAccess["appRole"]; + readonly outcome: "ok" | RefusalCode | (string & {}); + readonly durationMs: number; +} + +export interface ToolRegistryOptions { + readonly app: AppInfo; + // biome-ignore lint/suspicious/noExplicitAny: each tool types its own input + readonly tools: readonly ToolDefinition[]; + /** The listener `appAccess` reads (default `app`). */ + readonly listener?: string; + readonly env?: Environment; + /** The page endpoints' path (default `/api/agent-tools`). */ + readonly pagePath?: string; + /** The MCP endpoint's path (default `/mcp`), which `effectOf` classifies + * as MCP. */ + readonly mcpPath?: string; + /** Upper bound of a request body (default 64 KiB). */ + readonly maxBodyBytes?: number; + /** Upper bound of the files of one answer (default 10 MiB). */ + readonly maxFileBytes?: number; + /** Receives every call; the default writes one JSON line to stdout. */ + readonly audit?: (event: ToolAuditEvent) => void; +} + +export interface ToolRegistry { + /** Answers `/mcp`. */ + handleMcp(request: Request): Promise; + /** Answers the page endpoints, or `null` for any other path. */ + handlePage(request: Request): Promise; + /** The tools this access may see now. */ + list(access: AppAccess): readonly ToolDescriptor[]; + /** What a request to `/mcp` or to the page endpoints does to the data, + * read from a copy of the request, so a data layer that decides by the + * HTTP method (every tool call is a `POST`) can decide by the tool: + * `tools/call` and a page call give the named tool's effect, every other + * MCP method and the manifest are `read`, and `null` means not a tool + * request, an unknown tool or an unreadable body (treat it as a write). */ + effectOf(request: Request): Promise; +} + +const TOOL_NAME = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/; + +/** Whether this App may change data now. `LAZURIO_RUNTIME_DATA_WRITER=true` + * writes and any other value does not; on an Application host the variable is + * always set. Without it (a Module version in an Environment) only a local or + * Environment entry writes, to the Environment's own data. */ +export function dataWriter( + access: AppAccess, + env: Environment = process.env, +): boolean { + const value = env.LAZURIO_RUNTIME_DATA_WRITER; + if (value !== undefined) return value === "true"; + return access.entry === "local" || access.entry === "environment"; +} + +/** Where the App runs. Until the runtime states it explicitly + * (Lazurio/LazurioPlatform#1041), an App on an Application host is the one + * whose runtime sets `LAZURIO_RUNTIME_DATA_WRITER`. */ +export function deployment(env: Environment = process.env): Deployment { + const stated = env.LAZURIO_RUNTIME_DEPLOYMENT; + if (stated === "production" || stated === "environment") return stated; + return env.LAZURIO_RUNTIME_DATA_WRITER === undefined + ? "environment" + : "production"; +} + +const EMPTY_INPUT: StandardSchemaV1> = { + "~standard": { + version: 1, + vendor: "lazurio", + validate: (value) => + value !== null && + typeof value === "object" && + !Array.isArray(value) && + Object.keys(value).length === 0 + ? { value: {} } + : { issues: [{ message: "The tool takes no input." }] }, + }, +}; + +function appContextTool(app: AppInfo): ToolDefinition> { + return { + name: "get_app_context", + title: "App context", + description: + "Which App this is and how you work with it now: module, version, data generation, production application or a Module version in an Environment, your entry and application role, whether you may change data.", + input: EMPTY_INPUT, + inputSchema: { + type: "object", + properties: {}, + additionalProperties: false, + }, + minRole: "user", + effect: "read", + idempotent: true, + run: (_input, context) => ({ + ok: true, + data: { + module: app.module, + app_version: app.version, + data_generation: app.dataGeneration, + deployment: context.deployment, + entry: context.access.entry, + app_role: context.access.appRole, + person: context.access.person, + can_write: context.canWrite, + channel: context.channel, + }, + }), + }; +} + +function descriptor(tool: ToolDefinition): ToolDescriptor { + const readOnly = tool.effect !== "write"; + return { + name: tool.name, + ...(tool.title === undefined ? {} : { title: tool.title }), + description: tool.description, + inputSchema: tool.inputSchema, + ...(tool.outputSchema === undefined + ? {} + : { outputSchema: tool.outputSchema }), + effect: tool.effect, + annotations: { + ...(tool.title === undefined ? {} : { title: tool.title }), + readOnlyHint: readOnly, + destructiveHint: tool.effect === "write" && tool.publishesData === true, + idempotentHint: tool.idempotent ?? readOnly, + openWorldHint: false, + untrustedContentHint: tool.untrustedContent === true, + }, + }; +} + +function refusal( + reason: ToolRefusal["reason"], + message: string, + extra: Partial> = {}, +): ToolRefusal { + return { ok: false, reason, message, ...extra }; +} + +const HTTP_STATUS: Readonly> = { + identity_unavailable: 403, + forbidden: 403, + data_read_only: 403, + unknown_tool: 404, + not_found: 404, + invalid_input: 422, + record_changed: 409, + unavailable: 503, + internal_error: 500, +}; + +function json( + body: unknown, + status = 200, + headers: Readonly> = {}, +) { + return new Response(JSON.stringify(body), { + status, + headers: { + "content-type": "application/json; charset=utf-8", + "cache-control": "no-store", + ...headers, + }, + }); +} + +function base64(data: Uint8Array): string { + let binary = ""; + for (let i = 0; i < data.length; i += 0x8000) + binary += String.fromCharCode(...data.subarray(i, i + 0x8000)); + return btoa(binary); +} + +/** A tool name from a page path segment, or null when it is not one (a + * malformed percent escape, a slash). */ +function toolNameOf(segment: string): string | null { + try { + const name = decodeURIComponent(segment); + return TOOL_NAME.test(name) ? name : null; + } catch { + return null; + } +} + +/** Whether the body is declared as JSON (`application/json`, any + * parameters). */ +function isJson(request: Request): boolean { + const type = request.headers.get("content-type") ?? ""; + return type.split(";")[0]?.trim().toLowerCase() === "application/json"; +} + +class BodyTooLarge extends Error {} + +async function readBody(request: Request, max: number): Promise { + const declared = Number(request.headers.get("content-length") ?? "0"); + if (declared > max) throw new BodyTooLarge(); + const reader = request.body?.getReader(); + if (reader === undefined) return ""; + const chunks: Uint8Array[] = []; + let size = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > max) { + await reader.cancel(); + throw new BodyTooLarge(); + } + chunks.push(value); + } + const all = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { + all.set(chunk, offset); + offset += chunk.byteLength; + } + return new TextDecoder().decode(all); +} + +function issuesOf(issues: ReadonlyArray) { + return issues.map((issue) => ({ + message: issue.message, + path: (issue.path ?? []).map((part) => + typeof part === "object" ? String(part.key) : String(part), + ), + })); +} + +/** Builds the App's tool registry: its tools plus `get_app_context`. */ +export function createToolRegistry(options: ToolRegistryOptions): ToolRegistry { + const env = options.env ?? process.env; + const listenerId = options.listener ?? "app"; + const pagePath = (options.pagePath ?? "/api/agent-tools").replace(/\/$/, ""); + const mcpPath = (options.mcpPath ?? "/mcp").replace(/\/$/, ""); + const maxBody = options.maxBodyBytes ?? 64 * 1024; + const maxFiles = options.maxFileBytes ?? 10 * 1024 * 1024; + const audit = + options.audit ?? + ((event: ToolAuditEvent) => console.log(JSON.stringify(event))); + const tools = new Map>(); + for (const tool of [appContextTool(options.app), ...options.tools]) { + if (!TOOL_NAME.test(tool.name)) + throw new TypeError(`Tool name is not snake_case: ${tool.name}`); + if (tools.has(tool.name)) + throw new TypeError(`Tool defined twice: ${tool.name}`); + tools.set(tool.name, tool as ToolDefinition); + } + const own = listener(listenerId, env); + /** The origins this App itself is served from: its external origin behind + * a gateway, else its own loopback listener (scheme, host and port). */ + const ownOrigins: ReadonlySet = new Set( + own.externalOrigin !== null + ? [new URL(own.externalOrigin).origin] + : ["127.0.0.1", "localhost", "[::1]"].map( + (host) => `http://${host}:${own.port}`, + ), + ); + + /** Whether an `Origin` is exactly one of this App's own origins; anything + * else, including another port on the same computer, is refused. */ + const originAllowed = (origin: string): boolean => { + try { + const parsed = new URL(origin); + return parsed.origin === origin && ownOrigins.has(origin); + } catch { + return false; + } + }; + + /** Why this access may not call this tool now, or null. */ + const barrier = ( + tool: ToolDefinition, + access: KnownAccess, + canWrite: boolean, + where: Deployment, + ): ToolRefusal | null => { + if (tool.minRole === "admin" && access.appRole !== "admin") + return refusal( + "forbidden", + `${tool.name} needs the Application Admin role.`, + ); + if (tool.effect !== "write") return null; + if (!canWrite) + return refusal( + "data_read_only", + "This App does not change data now (read-only mode).", + ); + if ( + tool.publishesData === true && + where === "production" && + (tool.publicationConsent ?? "").trim() === "" + ) + return refusal( + "forbidden", + `${tool.name} would publish data; in a production application a person publishes in the interface.`, + ); + return null; + }; + + const known = (access: AppAccess): access is KnownAccess => + access.entry !== "unknown"; + + const list = (access: AppAccess): readonly ToolDescriptor[] => { + if (!known(access)) return []; + const canWrite = dataWriter(access, env); + const where = deployment(env); + return [...tools.values()] + .filter((tool) => barrier(tool, access, canWrite, where) === null) + .map(descriptor); + }; + + const call = async ( + name: string, + raw: unknown, + access: KnownAccess, + channel: ToolChannel, + request: Request, + ): Promise> => { + const started = performance.now(); + const finish = (result: ToolResult) => { + audit({ + event: "agent-tool", + channel, + tool: tools.has(name) ? name : "(unknown)", + entry: access.entry, + subject: access.person?.subject ?? null, + appRole: access.appRole, + outcome: result.ok ? "ok" : result.reason, + durationMs: Math.round(performance.now() - started), + }); + return result; + }; + const tool = tools.get(name); + if (tool === undefined) + return finish(refusal("unknown_tool", "This App has no such tool.")); + const canWrite = dataWriter(access, env); + const where = deployment(env); + const blocked = barrier(tool, access, canWrite, where); + if (blocked !== null) return finish(blocked); + let parsed: Awaited< + ReturnType<(typeof tool.input)["~standard"]["validate"]> + >; + try { + parsed = await tool.input["~standard"].validate(raw ?? {}); + } catch (error) { + console.error( + JSON.stringify({ + event: "agent-tool-error", + tool: name, + stage: "input", + error: error instanceof Error ? error.name : "unknown", + }), + ); + return finish(refusal("internal_error", "The tool failed.")); + } + if (parsed.issues !== undefined) + return finish( + refusal("invalid_input", "The input does not match the tool.", { + details: { issues: issuesOf(parsed.issues) }, + }), + ); + try { + const result = await tool.run(parsed.value, { + access, + channel, + deployment: where, + canWrite, + request, + }); + if (result.ok) { + const size = (result.files ?? []).reduce( + (sum, file) => sum + file.data.byteLength, + 0, + ); + if (size > maxFiles) + return finish( + refusal("unavailable", "The produced files are too large."), + ); + } + return finish(result); + } catch (error) { + console.error( + JSON.stringify({ + event: "agent-tool-error", + tool: name, + error: error instanceof Error ? error.name : "unknown", + }), + ); + return finish(refusal("internal_error", "The tool failed.")); + } + }; + + const mcpResult = (result: ToolResult) => { + if (!result.ok) + return { + content: [{ type: "text", text: JSON.stringify(result) }], + structuredContent: result, + isError: true, + }; + const files = (result.files ?? []).map((file) => ({ + type: "resource", + resource: { + uri: `urn:lazurio:${options.app.module}:file:${encodeURIComponent(file.name)}`, + mimeType: file.mimeType, + blob: base64(file.data), + }, + })); + return { + content: [{ type: "text", text: JSON.stringify(result.data) }, ...files], + structuredContent: result.data, + isError: false, + }; + }; + + const rpcError = (id: unknown, code: number, message: string, status = 200) => + json({ jsonrpc: "2.0", id: id ?? null, error: { code, message } }, status); + + const handleMcp = async (request: Request): Promise => { + if (request.method !== "POST") + return json({ error: "method_not_allowed" }, 405, { allow: "POST" }); + const origin = request.headers.get("origin"); + if (origin !== null && !originAllowed(origin)) + return json({ error: "origin_not_allowed" }, 403); + const access = appAccess(request, listenerId, env); + if (!known(access)) return json({ error: "identity_unavailable" }, 403); + const version = request.headers.get("mcp-protocol-version"); + if ( + version !== null && + !(MCP_PROTOCOL_VERSIONS as readonly string[]).includes(version) + ) + return rpcError(null, -32600, "Unsupported MCP protocol version.", 400); + if (!isJson(request)) return json({ error: "unsupported_media_type" }, 415); + let text: string; + try { + text = await readBody(request, maxBody); + } catch (error) { + if (error instanceof BodyTooLarge) + return json({ error: "body_too_large" }, 413); + throw error; + } + let message: unknown; + try { + message = JSON.parse(text); + } catch { + return rpcError(null, -32700, "Parse error.", 400); + } + if (Array.isArray(message)) + return rpcError(null, -32600, "Batches are not supported.", 400); + if ( + message === null || + typeof message !== "object" || + (message as { jsonrpc?: unknown }).jsonrpc !== "2.0" || + typeof (message as { method?: unknown }).method !== "string" + ) { + // A response or a malformed message: nothing to answer. + if (message !== null && typeof message === "object" && "id" in message) + return new Response(null, { status: 202 }); + return rpcError(null, -32600, "Invalid request.", 400); + } + const { id, method, params } = message as { + id?: unknown; + method: string; + params?: Record; + }; + if (id === undefined) return new Response(null, { status: 202 }); + switch (method) { + case "initialize": { + const asked = params?.protocolVersion; + const protocolVersion = ( + MCP_PROTOCOL_VERSIONS as readonly unknown[] + ).includes(asked) + ? (asked as string) + : MCP_PROTOCOL_VERSIONS[0]; + return json({ + jsonrpc: "2.0", + id, + result: { + protocolVersion, + capabilities: { tools: { listChanged: false } }, + serverInfo: { + name: options.app.module, + ...(options.app.title === undefined + ? {} + : { title: options.app.title }), + version: options.app.version, + }, + ...(options.app.instructions === undefined + ? {} + : { instructions: options.app.instructions }), + }, + }); + } + case "ping": + return json({ jsonrpc: "2.0", id, result: {} }); + case "tools/list": + return json({ + jsonrpc: "2.0", + id, + result: { + tools: list(access).map( + ({ + effect: _effect, + annotations: { untrustedContentHint: _hint, ...annotations }, + ...tool + }) => ({ ...tool, annotations }), + ), + }, + }); + case "tools/call": { + const name = params?.name; + if (typeof name !== "string") + return rpcError(id, -32602, "tools/call needs a tool name."); + const result = await call( + name, + params?.arguments, + access, + "mcp", + request, + ); + return json({ jsonrpc: "2.0", id, result: mcpResult(result) }); + } + default: + return rpcError(id, -32601, "Method not found."); + } + }; + + const handlePage = async (request: Request): Promise => { + const path = new URL(request.url).pathname.replace(/\/$/, ""); + const isManifest = path === pagePath; + const isCall = path.startsWith(`${pagePath}/`); + if (!isManifest && !isCall) return null; + const access = appAccess(request, listenerId, env); + if (isManifest) { + if (request.method !== "GET") + return json({ error: "method_not_allowed" }, 405, { allow: "GET" }); + if (!known(access)) + return json( + refusal("identity_unavailable", "Lazurio did not say who came."), + 403, + ); + return json({ + app: { + module: options.app.module, + version: options.app.version, + data_generation: options.app.dataGeneration, + }, + tools: list(access), + }); + } + if (request.method !== "POST") + return json({ error: "method_not_allowed" }, 405, { allow: "POST" }); + // The page calls with its own session: only its own origin may. + const origin = request.headers.get("origin"); + if (origin === null || !originAllowed(origin)) + return json({ error: "origin_not_allowed" }, 403); + // A cross-site page could send a simple `text/plain` POST without a + // preflight; the page sends JSON. + if (!isJson(request)) return json({ error: "unsupported_media_type" }, 415); + if (!known(access)) + return json( + refusal("identity_unavailable", "Lazurio did not say who came."), + 403, + ); + const name = toolNameOf(path.slice(pagePath.length + 1)); + if (name === null) + return json(refusal("unknown_tool", "This App has no such tool."), 404); + let raw: unknown; + try { + const text = await readBody(request, maxBody); + raw = text === "" ? {} : JSON.parse(text); + } catch (error) { + if (error instanceof BodyTooLarge) + return json({ error: "body_too_large" }, 413); + return json(refusal("invalid_input", "The input is not JSON."), 422); + } + const result = await call(name, raw, access, "webmcp", request); + if (!result.ok) return json(result, HTTP_STATUS[result.reason] ?? 409); + return json({ + ok: true, + data: result.data, + ...(result.files === undefined + ? {} + : { + files: result.files.map((file) => ({ + name: file.name, + mimeType: file.mimeType, + base64: base64(file.data), + })), + }), + }); + }; + + const effectOf = async (request: Request): Promise => { + const path = new URL(request.url).pathname.replace(/\/$/, ""); + if (path === pagePath) return "read"; + if (path.startsWith(`${pagePath}/`)) { + if (request.method !== "POST") return "read"; + const name = toolNameOf(path.slice(pagePath.length + 1)); + return name === null ? null : (tools.get(name)?.effect ?? null); + } + // Only the MCP endpoint is MCP; any other path is not a tool request. + if (path !== mcpPath) return null; + if (request.method !== "POST") return "read"; + let message: unknown; + try { + message = JSON.parse(await readBody(request.clone(), maxBody)); + } catch { + return null; + } + if ( + message === null || + typeof message !== "object" || + Array.isArray(message) + ) + return null; + const { method, params } = message as { + method?: unknown; + params?: { name?: unknown }; + }; + if (method !== "tools/call") return "read"; + return typeof params?.name === "string" + ? (tools.get(params.name)?.effect ?? null) + : null; + }; + + return { handleMcp, handlePage, list, effectOf }; +} diff --git a/src/webmcp.ts b/src/webmcp.ts new file mode 100644 index 0000000..f31b73b --- /dev/null +++ b/src/webmcp.ts @@ -0,0 +1,190 @@ +/** + * The page side of the one tool contract (Lazurio Module Standard, "Agents + * in the App"): registers the App's server tools as WebMCP tools, so an agent + * that has the App open in the Environment browser (the right panel) calls + * them directly, with the page's own session. + * + * The page asks its server which tools the person may use now (already + * filtered by role and writer mode) and registers exactly those; each call + * goes to the same server handler as `/mcp`. A page may add view tools of its + * own (opening a record, showing a view) that never change data. Without the + * WebMCP API (`document.modelContext`, `navigator.modelContext`) nothing is + * registered and the page works the same. + */ +import type { ToolDescriptor } from "./tools.ts"; + +/** A WebMCP tool as the page registers it. */ +export interface WebMcpTool { + readonly name: string; + readonly title?: string; + readonly description: string; + readonly inputSchema: Readonly>; + readonly annotations?: { + readonly readOnlyHint?: boolean; + readonly untrustedContentHint?: boolean; + }; + readonly execute: (input: unknown) => Promise; +} + +/** The part of the WebMCP API this helper uses. */ +export interface ModelContextLike { + registerTool( + tool: WebMcpTool, + options?: { readonly signal?: AbortSignal }, + ): unknown; +} + +/** A view tool of the page: it opens or shows something and never changes + * data. Its answer is JSON for the agent; a refusal is `{ ok: false, reason, + * message }`, never a thrown error. */ +export interface PageViewTool { + readonly name: string; + readonly title?: string; + readonly description: string; + readonly inputSchema: Readonly>; + readonly execute: (input: unknown) => Promise | unknown; +} + +export interface RegisterAgentToolsOptions { + /** The page endpoints of the server registry (default `/api/agent-tools`). */ + readonly endpoint?: string; + readonly viewTools?: readonly PageViewTool[]; + readonly modelContext?: ModelContextLike | null; + readonly fetch?: typeof fetch; +} + +export interface AgentTools { + /** The names registered now. */ + readonly registered: readonly string[]; + /** Asks the server again (after a sign-in, a role or writer change). */ + refresh(): Promise; + /** Removes every tool this helper registered. */ + unregister(): void; +} + +function findModelContext(): ModelContextLike | null { + const scope = globalThis as { + document?: { modelContext?: ModelContextLike }; + navigator?: { modelContext?: ModelContextLike }; + }; + return scope.document?.modelContext ?? scope.navigator?.modelContext ?? null; +} + +async function answer(response: Response): Promise { + try { + return await response.json(); + } catch { + return { + ok: false, + reason: "unavailable", + message: `The App answered HTTP ${response.status}.`, + }; + } +} + +/** Registers the App's tools for agents on this page. */ +export async function registerAgentTools( + options: RegisterAgentToolsOptions = {}, +): Promise { + const context = + options.modelContext === undefined + ? findModelContext() + : options.modelContext; + const endpoint = (options.endpoint ?? "/api/agent-tools").replace(/\/$/, ""); + const doFetch = options.fetch ?? fetch; + let controllers: Array<{ abort(): void }> = []; + let registered: string[] = []; + + const unregister = () => { + for (const controller of controllers) controller.abort(); + controllers = []; + registered = []; + }; + + const register = (tool: WebMcpTool) => { + if (context === null) return; + const controller = new AbortController(); + const handle = context.registerTool(tool, { signal: controller.signal }); + const legacy = handle as { unregister?: () => void } | undefined; + controllers.push({ + abort: () => { + controller.abort(); + legacy?.unregister?.(); + }, + }); + registered.push(tool.name); + }; + + const refresh = async (): Promise => { + unregister(); + if (context === null) return registered; + let tools: readonly ToolDescriptor[] = []; + try { + const response = await doFetch(endpoint, { + credentials: "same-origin", + headers: { accept: "application/json" }, + }); + if (response.ok) + tools = + ((await response.json()) as { tools?: ToolDescriptor[] }).tools ?? []; + } catch { + tools = []; + } + const serverNames = new Set(tools.map((tool) => tool.name)); + for (const tool of tools) + register({ + name: tool.name, + ...(tool.title === undefined ? {} : { title: tool.title }), + description: tool.description, + inputSchema: tool.inputSchema, + annotations: { + readOnlyHint: tool.annotations.readOnlyHint, + untrustedContentHint: tool.annotations.untrustedContentHint, + }, + execute: async (input) => + answer( + await doFetch(`${endpoint}/${encodeURIComponent(tool.name)}`, { + method: "POST", + credentials: "same-origin", + headers: { + "content-type": "application/json", + accept: "application/json", + }, + body: JSON.stringify(input ?? {}), + }), + ), + }); + for (const view of options.viewTools ?? []) { + // A view tool never shadows a server tool. + if (serverNames.has(view.name)) continue; + register({ + name: view.name, + ...(view.title === undefined ? {} : { title: view.title }), + description: view.description, + inputSchema: view.inputSchema, + annotations: { readOnlyHint: true }, + execute: async (input) => { + try { + return await view.execute(input); + } catch { + return { + ok: false, + reason: "internal_error", + message: "The view tool failed.", + }; + } + }, + }); + } + return registered; + }; + + await refresh(); + return { + get registered() { + return [...registered]; + }, + refresh, + unregister, + }; +} diff --git a/test/tools.test.ts b/test/tools.test.ts new file mode 100644 index 0000000..a282657 --- /dev/null +++ b/test/tools.test.ts @@ -0,0 +1,897 @@ +import { describe, expect, test } from "bun:test"; +import { + createToolRegistry, + dataWriter, + defineTool, + deployment, + type StandardSchemaV1, + type ToolAuditEvent, + type ToolDefinition, +} from "../src/tools.ts"; +import { + gatewayRequest, + hostedEnvironment, + localEnvironment, + mcpCall, + mcpTool, + mcpToolNames, + pageTool, + TEST_ORIGIN, + TEST_SUBJECT, +} from "../src/tools-testing.ts"; + +/** A tiny Standard Schema: an object with the given required string fields. */ +function strings( + ...keys: K[] +): StandardSchemaV1> { + return { + "~standard": { + version: 1, + vendor: "test", + validate: (value) => { + if (value === null || typeof value !== "object" || Array.isArray(value)) + return { issues: [{ message: "Expected an object." }] }; + const record = value as Record; + const extra = Object.keys(record).filter( + (key) => !keys.includes(key as K), + ); + if (extra.length > 0) + return { issues: [{ message: "Unknown field.", path: extra }] }; + for (const key of keys) + if (typeof record[key] !== "string") + return { issues: [{ message: "Expected a string.", path: [key] }] }; + return { value: record as Record }; + }, + }, + }; +} + +const schema = (...keys: string[]) => ({ + type: "object", + properties: Object.fromEntries(keys.map((key) => [key, { type: "string" }])), + required: keys, + additionalProperties: false, +}); + +const records = new Map([["r1", { title: "Revize 1", revision: "a" }]]); + +const findRecords = defineTool({ + name: "find_records", + description: "Najde záznamy.", + input: strings("query"), + inputSchema: schema("query"), + minRole: "user", + effect: "read", + untrustedContent: true, + run: ({ query }) => ({ + ok: true, + data: { + items: [...records.entries()] + .filter(([, record]) => record.title.includes(query)) + .map(([id, record]) => ({ id, ...record })), + }, + }), +}); + +const saveDraft = defineTool({ + name: "save_record_draft", + description: "Uloží koncept záznamu.", + input: strings("id", "title", "base_revision"), + inputSchema: schema("id", "title", "base_revision"), + minRole: "user", + effect: "write", + publishesData: false, + run: ({ id, base_revision }, context) => { + const record = records.get(id); + if (record === undefined) + return { ok: false, reason: "not_found", message: "Záznam neexistuje." }; + if (record.revision !== base_revision) + return { + ok: false, + reason: "record_changed", + message: "Záznam se mezitím změnil.", + current_revision: record.revision, + }; + return { ok: true, data: { id, channel: context.channel } }; + }, +}); + +const publishRecord = defineTool({ + name: "save_record", + description: "Uloží a publikuje změnu záznamu.", + input: strings("id"), + inputSchema: schema("id"), + minRole: "user", + effect: "write", + publishesData: true, + run: ({ id }) => ({ ok: true, data: { id } }), +}); + +const publishTicket = defineTool({ + name: "create_ticket", + description: "Založí a publikuje ticket.", + input: strings("id"), + inputSchema: schema("id"), + minRole: "user", + effect: "write", + publishesData: true, + publicationConsent: "plan DEV-0000, Owner 2026-11-14: agents publish tickets", + run: ({ id }) => ({ ok: true, data: { id } }), +}); + +const prepareApproval = defineTool({ + name: "prepare_record_approval", + description: "Připraví Schválení; schvaluje člověk.", + input: strings("id"), + inputSchema: schema("id"), + minRole: "admin", + effect: "prepare", + run: ({ id }) => ({ ok: true, data: { id, ready: true } }), +}); + +const exportPdf = defineTool({ + name: "export_record_pdf", + description: "Vyrobí PDF.", + input: strings("id"), + inputSchema: schema("id"), + minRole: "user", + effect: "read", + run: ({ id }) => ({ + ok: true, + data: { id }, + files: [ + { + name: `${id}.pdf`, + mimeType: "application/pdf", + data: new TextEncoder().encode("%PDF-1.7"), + }, + ], + }), +}); + +const failing = defineTool({ + name: "break_things", + description: "Selže.", + input: strings(), + inputSchema: schema(), + minRole: "user", + effect: "read", + run: () => { + throw new Error("secret detail /db/records.json"); + }, +}); + +const TOOLS = [ + findRecords, + saveDraft, + publishRecord, + publishTicket, + prepareApproval, + exportPdf, + failing, +] as ToolDefinition[]; + +function registry( + env: Record, + audit: ToolAuditEvent[] = [], + extra: Partial[0]> = {}, +) { + return createToolRegistry({ + app: { + module: "records", + version: "1.2.3", + dataGeneration: "v3", + instructions: "Pravidla domény.", + }, + tools: TOOLS, + env, + audit: (event) => audit.push(event), + ...extra, + }); +} + +const writer = registry(hostedEnvironment({ writer: true })); +const reader = registry(hostedEnvironment({ writer: false })); + +describe("registry definition", () => { + test("a tool name must be snake_case and unique", () => { + const bad = { ...findRecords, name: "findRecords" }; + expect(() => registry(hostedEnvironment(), [], { tools: [bad] })).toThrow( + "snake_case", + ); + expect(() => + registry(hostedEnvironment(), [], { tools: [findRecords, findRecords] }), + ).toThrow("twice"); + const shadow = { ...findRecords, name: "get_app_context" }; + expect(() => + registry(hostedEnvironment(), [], { tools: [shadow] }), + ).toThrow("twice"); + }); +}); + +describe("writer and deployment", () => { + const app = { entry: "app", appRole: "user" } as const; + const local = { entry: "local", appRole: "admin" } as const; + test("true writes, any other value does not, unset only locally", () => { + expect( + dataWriter(app as never, { LAZURIO_RUNTIME_DATA_WRITER: "true" }), + ).toBe(true); + for (const value of ["false", "TRUE", "1", ""]) + expect( + dataWriter(app as never, { LAZURIO_RUNTIME_DATA_WRITER: value }), + ).toBe(false); + expect(dataWriter(app as never, {})).toBe(false); + expect(dataWriter(local as never, {})).toBe(true); + }); + test("a host that sets the writer flag is production", () => { + expect(deployment({ LAZURIO_RUNTIME_DATA_WRITER: "false" })).toBe( + "production", + ); + expect(deployment({})).toBe("environment"); + expect( + deployment({ + LAZURIO_RUNTIME_DATA_WRITER: "true", + LAZURIO_RUNTIME_DEPLOYMENT: "environment", + }), + ).toBe("environment"); + }); +}); + +describe("/mcp transport", () => { + test("initialize negotiates the protocol and names the App's version", async () => { + const { status, body } = await mcpCall(writer, "initialize", { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "test", version: "0" }, + }); + expect(status).toBe(200); + expect(body.result).toEqual({ + protocolVersion: "2025-06-18", + capabilities: { tools: { listChanged: false } }, + serverInfo: { name: "records", version: "1.2.3" }, + instructions: "Pravidla domény.", + }); + const newer = await mcpCall(writer, "initialize", { + protocolVersion: "2099-01-01", + }); + expect( + (newer.body.result as { protocolVersion: string }).protocolVersion, + ).toBe("2025-11-25"); + }); + + test("only POST, no batches, bounded body, JSON only", async () => { + const get = await writer.handleMcp(gatewayRequest("/mcp")); + expect(get.status).toBe(405); + expect(get.headers.get("allow")).toBe("POST"); + const batch = await writer.handleMcp( + gatewayRequest("/mcp", { + body: [{ jsonrpc: "2.0", id: 1, method: "ping" }], + }), + ); + expect(batch.status).toBe(400); + const large = await writer.handleMcp( + gatewayRequest("/mcp", { + body: { + jsonrpc: "2.0", + id: 1, + method: "ping", + pad: "x".repeat(70_000), + }, + }), + ); + expect(large.status).toBe(413); + const text = await writer.handleMcp( + gatewayRequest("/mcp", { + body: "ping", + headers: { "content-type": "text/plain" }, + }), + ); + expect(text.status).toBe(415); + const parse = await writer.handleMcp( + gatewayRequest("/mcp", { body: "{not json" }), + ); + expect(parse.status).toBe(400); + }); + + test("a notification is accepted without an answer", async () => { + const response = await writer.handleMcp( + gatewayRequest("/mcp", { + body: { jsonrpc: "2.0", method: "notifications/initialized" }, + }), + ); + expect(response.status).toBe(202); + expect(await response.text()).toBe(""); + }); + + test("an unsupported protocol version header is refused", async () => { + const response = await writer.handleMcp( + gatewayRequest("/mcp", { + body: { jsonrpc: "2.0", id: 1, method: "ping" }, + headers: { "mcp-protocol-version": "1999-01-01" }, + }), + ); + expect(response.status).toBe(400); + }); + + test("a foreign Origin is refused, a missing one is not", async () => { + const foreign = await writer.handleMcp( + gatewayRequest("/mcp", { + origin: "https://evil.example", + body: { jsonrpc: "2.0", id: 1, method: "ping" }, + }), + ); + expect(foreign.status).toBe(403); + const own = await writer.handleMcp( + gatewayRequest("/mcp", { + origin: TEST_ORIGIN, + body: { jsonrpc: "2.0", id: 1, method: "ping" }, + }), + ); + expect(own.status).toBe(200); + }); + + test("without a stated person nothing is answered", async () => { + const { status, body } = await mcpCall( + writer, + "tools/list", + {}, + { caller: { role: "none" } }, + ); + expect(status).toBe(403); + expect(body).toEqual({ error: "identity_unavailable" }); + }); + + test("the list follows the role", async () => { + expect(await mcpToolNames(writer, { role: "user" })).toEqual([ + "break_things", + "create_ticket", + "export_record_pdf", + "find_records", + "get_app_context", + "save_record_draft", + ]); + expect(await mcpToolNames(writer, { role: "admin" })).toContain( + "prepare_record_approval", + ); + expect(await mcpToolNames(writer, { role: "environment" })).toContain( + "prepare_record_approval", + ); + }); + + test("a tool the role does not have is refused, an unknown one too", async () => { + const hidden = await mcpTool(writer, "prepare_record_approval", { + id: "r1", + }); + expect(hidden.isError).toBe(true); + expect(hidden.structured.reason).toBe("forbidden"); + const unknown = await mcpTool(writer, "drop_everything", {}); + expect(unknown.structured.reason).toBe("unknown_tool"); + }); + + test("read-only mode hides writes and refuses a direct call", async () => { + const names = await mcpToolNames(reader, { role: "admin" }); + expect(names).not.toContain("save_record_draft"); + expect(names).toContain("export_record_pdf"); + const call = await mcpTool(reader, "save_record_draft", { + id: "r1", + title: "x", + base_revision: "a", + }); + expect(call.structured.reason).toBe("data_read_only"); + }); + + test("a tool that publishes data is not offered in production", async () => { + expect(await mcpToolNames(writer, { role: "admin" })).not.toContain( + "save_record", + ); + const call = await mcpTool(writer, "save_record", { id: "r1" }); + expect(call.structured.reason).toBe("forbidden"); + const local = registry(localEnvironment()); + const response = await local.handleMcp( + new Request("http://127.0.0.1:43100/mcp", { + method: "POST", + headers: { + host: "127.0.0.1:43100", + "content-type": "application/json", + }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), + }), + ); + const listed = ( + (await response.json()) as { + result: { tools: Array<{ name: string }> }; + } + ).result.tools.map((tool) => tool.name); + expect(listed).toContain("save_record"); + }); + + test("with the Owner's recorded consent a publishing write is offered in production", async () => { + const names = await mcpToolNames(writer, { role: "user" }); + expect(names).toContain("create_ticket"); + expect(names).not.toContain("save_record"); + const call = await mcpTool(writer, "create_ticket", { id: "t1" }); + expect(call.structured).toEqual({ id: "t1" }); + expect(await mcpToolNames(reader, { role: "user" })).not.toContain( + "create_ticket", + ); + const viaPage = await pageTool(writer, "create_ticket", { id: "t2" }); + expect([viaPage.status, viaPage.body]).toEqual([ + 200, + { ok: true, data: { id: "t2" } }, + ]); + const otherViaPage = await pageTool(writer, "save_record", { id: "r1" }); + expect([otherViaPage.status, otherViaPage.body.reason]).toEqual([ + 403, + "forbidden", + ]); + const readOnlyViaPage = await pageTool(reader, "create_ticket", { + id: "t3", + }); + expect(readOnlyViaPage.body.reason).toBe("data_read_only"); + const blank = registry(hostedEnvironment({ writer: true }), [], { + tools: [ + { + ...publishTicket, + publicationConsent: " ", + } as ToolDefinition, + ], + }); + expect(await mcpToolNames(blank, { role: "user" })).not.toContain( + "create_ticket", + ); + }); + + test("annotations say what a tool does", async () => { + const { body } = await mcpCall( + writer, + "tools/list", + {}, + { caller: { role: "admin" } }, + ); + const tools = (body.result as { tools: Array> }) + .tools; + const byName = Object.fromEntries(tools.map((tool) => [tool.name, tool])); + expect(byName.find_records?.annotations).toEqual({ + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }); + expect(byName.save_record_draft?.annotations).toEqual({ + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false, + }); + expect(byName.find_records?.effect).toBeUndefined(); + }); + + test("get_app_context reports the App and the caller", async () => { + const { isError, structured } = await mcpTool( + writer, + "get_app_context", + {}, + ); + expect(isError).toBe(false); + expect(structured).toEqual({ + module: "records", + app_version: "1.2.3", + data_generation: "v3", + deployment: "production", + entry: "app", + app_role: "user", + person: { subject: TEST_SUBJECT, username: "test-person" }, + can_write: true, + channel: "mcp", + }); + }); + + test("invalid input is a tool refusal with the issues", async () => { + const { isError, structured } = await mcpTool(writer, "find_records", { + query: 3, + }); + expect(isError).toBe(true); + expect(structured.reason).toBe("invalid_input"); + expect(structured.details).toEqual({ + issues: [{ message: "Expected a string.", path: ["query"] }], + }); + }); + + test("record_changed carries the current revision", async () => { + const { structured } = await mcpTool(writer, "save_record_draft", { + id: "r1", + title: "x", + base_revision: "old", + }); + expect(structured).toEqual({ + ok: false, + reason: "record_changed", + message: "Záznam se mezitím změnil.", + current_revision: "a", + }); + }); + + test("a file comes back as an embedded resource", async () => { + const { body } = await mcpCall(writer, "tools/call", { + name: "export_record_pdf", + arguments: { id: "r1" }, + }); + const content = (body.result as { content: Array> }) + .content; + expect(content[1]).toEqual({ + type: "resource", + resource: { + uri: "urn:lazurio:records:file:r1.pdf", + mimeType: "application/pdf", + blob: btoa("%PDF-1.7"), + }, + }); + }); + + test("a failing tool says internal_error and leaks nothing", async () => { + const errors: string[] = []; + const original = console.error; + console.error = (line: string) => errors.push(line); + try { + const { structured } = await mcpTool(writer, "break_things", {}); + expect(structured).toEqual({ + ok: false, + reason: "internal_error", + message: "The tool failed.", + }); + } finally { + console.error = original; + } + expect(errors.join("\n")).not.toContain("secret detail"); + }); + + test("every call is audited without input or answer", async () => { + const audit: ToolAuditEvent[] = []; + const audited = registry(hostedEnvironment({ writer: true }), audit); + await mcpTool(audited, "find_records", { query: "secret-query" }); + await mcpTool(audited, "prepare_record_approval", { id: "r1" }); + expect(audit.map(({ durationMs: _d, ...event }) => event)).toEqual([ + { + event: "agent-tool", + channel: "mcp", + tool: "find_records", + entry: "app", + subject: TEST_SUBJECT, + appRole: "user", + outcome: "ok", + }, + { + event: "agent-tool", + channel: "mcp", + tool: "prepare_record_approval", + entry: "app", + subject: TEST_SUBJECT, + appRole: "user", + outcome: "forbidden", + }, + ]); + expect(JSON.stringify(audit)).not.toContain("secret-query"); + }); +}); + +describe("page transport", () => { + test("the manifest lists the same tools as /mcp", async () => { + for (const caller of [{ role: "user" }, { role: "admin" }] as const) { + const response = await reader.handlePage( + gatewayRequest("/api/agent-tools", { caller }), + ); + const manifest = (await response?.json()) as { + tools: Array<{ name: string; effect: string }>; + }; + expect(manifest.tools.map((tool) => tool.name).sort()).toEqual( + await mcpToolNames(reader, caller), + ); + } + }); + + test("a call goes through the same handler, with the webmcp channel", async () => { + const { status, body } = await pageTool(writer, "save_record_draft", { + id: "r1", + title: "x", + base_revision: "a", + }); + expect(status).toBe(200); + expect(body).toEqual({ ok: true, data: { id: "r1", channel: "webmcp" } }); + const stale = await pageTool(writer, "save_record_draft", { + id: "r1", + title: "x", + base_revision: "old", + }); + expect(stale.status).toBe(409); + expect(stale.body.reason).toBe("record_changed"); + const readOnly = await pageTool(reader, "save_record_draft", { + id: "r1", + title: "x", + base_revision: "a", + }); + expect(readOnly.status).toBe(403); + expect(readOnly.body.reason).toBe("data_read_only"); + }); + + test("a call needs the page's own origin", async () => { + for (const origin of [null, "https://evil.example"]) { + const response = await writer.handlePage( + gatewayRequest("/api/agent-tools/find_records", { + origin, + body: { query: "R" }, + }), + ); + expect(response?.status).toBe(403); + } + }); + + test("without a stated person the page gets no tools", async () => { + const response = await writer.handlePage( + gatewayRequest("/api/agent-tools", { caller: { role: "none" } }), + ); + if (response === null) throw new Error("no answer"); + expect(response.status).toBe(403); + expect(((await response.json()) as { reason: string }).reason).toBe( + "identity_unavailable", + ); + }); + + test("other paths are not the registry's", async () => { + expect(await writer.handlePage(gatewayRequest("/api/records"))).toBeNull(); + }); + + test("a file comes back as base64", async () => { + const { body } = await pageTool(writer, "export_record_pdf", { id: "r1" }); + expect(body.files).toEqual([ + { name: "r1.pdf", mimeType: "application/pdf", base64: btoa("%PDF-1.7") }, + ]); + }); +}); + +describe("review of #6: origin boundary and failing validators", () => { + const local = registry(localEnvironment()); + const localRequest = ( + path: string, + origin: string | null, + contentType: string, + body: string, + ) => + new Request(`http://127.0.0.1:43100${path}`, { + method: "POST", + headers: { + host: "127.0.0.1:43100", + "content-type": contentType, + ...(origin === null ? {} : { origin }), + }, + body, + }); + const draft = JSON.stringify({ id: "r1", title: "x", base_revision: "a" }); + + test("a page on another loopback port cannot call a local App", async () => { + for (const contentType of ["text/plain", "application/json"]) + for (const origin of [ + "http://localhost:9999", + "http://127.0.0.1:9999", + "https://127.0.0.1:43100", + "http://127.0.0.2:43100", + ]) { + const response = await local.handlePage( + localRequest( + "/api/agent-tools/save_record_draft", + origin, + contentType, + draft, + ), + ); + expect([origin, contentType, response?.status]).toEqual([ + origin, + contentType, + 403, + ]); + } + }); + + test("the local App's own origin may call it, as JSON only", async () => { + for (const origin of [ + "http://127.0.0.1:43100", + "http://localhost:43100", + "http://[::1]:43100", + ]) { + const ok = await local.handlePage( + localRequest( + "/api/agent-tools/save_record_draft", + origin, + "application/json; charset=utf-8", + draft, + ), + ); + expect([origin, ok?.status]).toEqual([origin, 200]); + } + const plain = await local.handlePage( + localRequest( + "/api/agent-tools/save_record_draft", + "http://127.0.0.1:43100", + "text/plain", + draft, + ), + ); + expect(plain?.status).toBe(415); + }); + + test("a hosted page call as text/plain is refused", async () => { + const response = await writer.handlePage( + gatewayRequest("/api/agent-tools/find_records", { + origin: TEST_ORIGIN, + body: JSON.stringify({ query: "R" }), + headers: { "content-type": "text/plain" }, + }), + ); + expect(response?.status).toBe(415); + }); + + test("/mcp keeps the same origin boundary locally", async () => { + const ping = JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }); + const foreign = await local.handleMcp( + localRequest("/mcp", "http://localhost:9999", "application/json", ping), + ); + expect(foreign.status).toBe(403); + const own = await local.handleMcp( + localRequest("/mcp", "http://localhost:43100", "application/json", ping), + ); + expect(own.status).toBe(200); + const none = await local.handleMcp( + localRequest("/mcp", null, "application/json", ping), + ); + expect(none.status).toBe(200); + const plain = await local.handleMcp( + localRequest("/mcp", null, "text/plain; x=json", ping), + ); + expect(plain.status).toBe(415); + }); + + for (const [label, validate] of [ + [ + "throws", + () => { + throw new Error("validator detail"); + }, + ], + ["rejects", () => Promise.reject(new Error("validator detail"))], + ] as const) { + test(`a validator that ${label} is internal_error, audited, on both transports`, async () => { + const audit: ToolAuditEvent[] = []; + const broken = defineTool({ + name: "broken_input", + description: "Rozbitý validátor.", + input: { + "~standard": { version: 1, vendor: "test", validate }, + } as StandardSchemaV1>, + inputSchema: schema(), + minRole: "user", + effect: "read", + run: () => ({ ok: true, data: {} }), + }); + const audited = registry(hostedEnvironment({ writer: true }), audit, { + tools: [broken as ToolDefinition], + }); + const errors: string[] = []; + const original = console.error; + console.error = (line: string) => errors.push(line); + try { + const viaMcp = await mcpTool(audited, "broken_input", {}); + expect(viaMcp.structured).toEqual({ + ok: false, + reason: "internal_error", + message: "The tool failed.", + }); + const viaPage = await pageTool(audited, "broken_input", {}); + expect(viaPage.status).toBe(500); + expect(viaPage.body.reason).toBe("internal_error"); + } finally { + console.error = original; + } + expect(audit.map((event) => [event.channel, event.outcome])).toEqual([ + ["mcp", "internal_error"], + ["webmcp", "internal_error"], + ]); + expect(errors.join("\n")).not.toContain("validator detail"); + }); + } +}); + +describe("effectOf", () => { + const post = (path: string, body: unknown) => + gatewayRequest(path, { body, origin: TEST_ORIGIN }); + test("a tool call has its tool's effect, and the request stays readable", async () => { + const request = post("/mcp", { + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { name: "save_record_draft", arguments: {} }, + }); + expect(await writer.effectOf(request)).toBe("write"); + expect(((await request.json()) as { method: string }).method).toBe( + "tools/call", + ); + expect( + await writer.effectOf( + post("/mcp", { + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { name: "export_record_pdf" }, + }), + ), + ).toBe("read"); + expect( + await writer.effectOf( + post("/api/agent-tools/prepare_record_approval", {}), + ), + ).toBe("prepare"); + expect( + await writer.effectOf(post("/api/agent-tools/save_record", {})), + ).toBe("write"); + }); + test("other MCP methods and the manifest read; unknown is null", async () => { + expect( + await writer.effectOf( + post("/mcp", { jsonrpc: "2.0", id: 1, method: "tools/list" }), + ), + ).toBe("read"); + expect(await writer.effectOf(gatewayRequest("/api/agent-tools"))).toBe( + "read", + ); + expect( + await writer.effectOf( + post("/mcp", { + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { name: "nope" }, + }), + ), + ).toBeNull(); + expect(await writer.effectOf(post("/mcp", "{not json"))).toBeNull(); + expect(await writer.effectOf(post("/api/agent-tools/nope", {}))).toBeNull(); + }); +}); + +describe("review of #6 round 3: effectOf only for tool requests", () => { + const post = (path: string, body: unknown) => + gatewayRequest(path, { body, origin: TEST_ORIGIN }); + test("an ordinary App request is not a tool request", async () => { + expect( + await writer.effectOf(post("/api/records", { title: "changed" })), + ).toBeNull(); + expect( + await writer.effectOf( + post("/api/records", { jsonrpc: "2.0", id: 1, method: "tools/list" }), + ), + ).toBeNull(); + expect(await writer.effectOf(gatewayRequest("/api/records"))).toBeNull(); + expect( + await writer.effectOf(post("/mcp/extra", { method: "ping" })), + ).toBeNull(); + }); + test("a malformed page tool path is null, and the page answers unknown_tool", async () => { + expect(await writer.effectOf(post("/api/agent-tools/%ZZ", {}))).toBeNull(); + expect( + await writer.effectOf(post("/api/agent-tools/a%2Fb", {})), + ).toBeNull(); + const response = await writer.handlePage(post("/api/agent-tools/%ZZ", {})); + expect(response?.status).toBe(404); + }); + test("a custom MCP path is the one classified", async () => { + const custom = registry(hostedEnvironment({ writer: true }), [], { + mcpPath: "/agents/mcp", + }); + const call = { + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { name: "save_record_draft" }, + }; + expect(await custom.effectOf(post("/agents/mcp", call))).toBe("write"); + expect(await custom.effectOf(post("/mcp", call))).toBeNull(); + }); +}); diff --git a/test/webmcp.test.ts b/test/webmcp.test.ts new file mode 100644 index 0000000..83e1e63 --- /dev/null +++ b/test/webmcp.test.ts @@ -0,0 +1,227 @@ +import { describe, expect, test } from "bun:test"; +import { createToolRegistry, defineTool } from "../src/tools.ts"; +import { + type GatewayCaller, + gatewayRequest, + hostedEnvironment, + TEST_ORIGIN, +} from "../src/tools-testing.ts"; +import { + type ModelContextLike, + registerAgentTools, + type WebMcpTool, +} from "../src/webmcp.ts"; + +const anyObject = { + "~standard": { + version: 1 as const, + vendor: "test", + validate: (value: unknown) => ({ value: value as Record }), + }, +}; + +function makeRegistry(writer: boolean) { + return createToolRegistry({ + app: { module: "records", version: "1.0.0", dataGeneration: "v3" }, + env: hostedEnvironment({ writer }), + audit: () => {}, + tools: [ + defineTool({ + name: "find_records", + description: "Najde záznamy.", + input: anyObject, + inputSchema: { type: "object" }, + minRole: "user", + effect: "read", + untrustedContent: true, + run: (input, context) => ({ + ok: true, + data: { input, channel: context.channel }, + }), + }), + defineTool({ + name: "save_record_draft", + description: "Uloží koncept.", + input: anyObject, + inputSchema: { type: "object" }, + minRole: "user", + effect: "write", + publishesData: false, + run: () => ({ ok: true, data: { saved: true } }), + }), + ], + }); +} + +/** A fetch that sends the page's requests through the gateway to a registry. */ +function pageFetch( + registry: ReturnType, + caller: GatewayCaller, +): typeof fetch { + return (async (input: string | URL | Request, init?: RequestInit) => { + const path = typeof input === "string" ? input : input.toString(); + const body = init?.body === undefined ? undefined : String(init.body); + const request = gatewayRequest(path, { + caller, + method: init?.method ?? "GET", + origin: init?.method === "POST" ? TEST_ORIGIN : null, + ...(body === undefined ? {} : { body }), + }); + return ( + (await registry.handlePage(request)) ?? + new Response("not found", { status: 404 }) + ); + }) as typeof fetch; +} + +function fakeContext() { + const tools = new Map(); + const context: ModelContextLike = { + registerTool(tool, options) { + tools.set(tool.name, tool); + options?.signal?.addEventListener("abort", () => tools.delete(tool.name)); + }, + }; + return { tools, context }; +} + +describe("registerAgentTools", () => { + test("registers the server's tools for this person and calls the server", async () => { + const { tools, context } = fakeContext(); + const agentTools = await registerAgentTools({ + modelContext: context, + fetch: pageFetch(makeRegistry(true), { role: "user" }), + }); + expect([...agentTools.registered].sort()).toEqual([ + "find_records", + "get_app_context", + "save_record_draft", + ]); + expect(tools.get("find_records")?.annotations).toEqual({ + readOnlyHint: true, + untrustedContentHint: true, + }); + const answer = await tools.get("find_records")?.execute({ query: "R" }); + expect(answer).toEqual({ + ok: true, + data: { input: { query: "R" }, channel: "webmcp" }, + }); + }); + + test("in read-only mode the page offers no write tool", async () => { + const { tools, context } = fakeContext(); + await registerAgentTools({ + modelContext: context, + fetch: pageFetch(makeRegistry(false), { role: "admin" }), + }); + expect(tools.has("save_record_draft")).toBe(false); + expect(tools.has("find_records")).toBe(true); + }); + + test("without a stated person the page registers no server tool", async () => { + const { tools, context } = fakeContext(); + await registerAgentTools({ + modelContext: context, + fetch: pageFetch(makeRegistry(true), { role: "none" }), + viewTools: [ + { + name: "open_record", + description: "Otevře záznam.", + inputSchema: { type: "object" }, + execute: () => ({ ok: true }), + }, + ], + }); + expect([...tools.keys()]).toEqual(["open_record"]); + }); + + test("a view tool never shadows a server tool and its failure is an answer", async () => { + const { tools, context } = fakeContext(); + await registerAgentTools({ + modelContext: context, + fetch: pageFetch(makeRegistry(true), { role: "user" }), + viewTools: [ + { + name: "find_records", + description: "Stínová verze.", + inputSchema: { type: "object" }, + execute: () => ({ shadow: true }), + }, + { + name: "open_record", + description: "Otevře záznam.", + inputSchema: { type: "object" }, + execute: () => { + throw new Error("boom"); + }, + }, + ], + }); + expect(tools.get("find_records")?.description).toBe("Najde záznamy."); + expect(await tools.get("open_record")?.execute({})).toEqual({ + ok: false, + reason: "internal_error", + message: "The view tool failed.", + }); + }); + + test("refresh follows a change of role, unregister removes everything", async () => { + const { tools, context } = fakeContext(); + let caller: GatewayCaller = { role: "none" }; + const registry = makeRegistry(true); + const agentTools = await registerAgentTools({ + modelContext: context, + fetch: ((input: string | URL | Request, init?: RequestInit) => + pageFetch(registry, caller)(input, init)) as typeof fetch, + }); + expect(tools.size).toBe(0); + caller = { role: "user" }; + await agentTools.refresh(); + expect(tools.has("find_records")).toBe(true); + agentTools.unregister(); + expect(tools.size).toBe(0); + expect(agentTools.registered).toEqual([]); + }); + + test("without the WebMCP API nothing happens and nothing throws", async () => { + const agentTools = await registerAgentTools({ + modelContext: null, + fetch: (() => { + throw new Error("must not be called"); + }) as unknown as typeof fetch, + }); + expect(agentTools.registered).toEqual([]); + }); + + test("a non-JSON answer becomes an unavailable refusal", async () => { + const { tools, context } = fakeContext(); + await registerAgentTools({ + modelContext: context, + fetch: (async (_input: string | URL | Request, init?: RequestInit) => + init?.method === "POST" + ? new Response("", { status: 502 }) + : Response.json({ + tools: [ + { + name: "find_records", + description: "x", + inputSchema: {}, + effect: "read", + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + untrustedContentHint: false, + }, + }, + ], + })) as typeof fetch, + }); + expect(await tools.get("find_records")?.execute({})).toEqual({ + ok: false, + reason: "unavailable", + message: "The App answered HTTP 502.", + }); + }); +});