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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 115 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,23 @@

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

```sh
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`,
Expand Down Expand Up @@ -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/<name>` 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
Expand Down
16 changes: 14 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -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",
Expand Down
184 changes: 184 additions & 0 deletions src/tools-testing.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>>;
} = {},
): Record<string, string> {
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<string, string> {
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<Record<string, string>>;
} = {},
): Request {
const appOrigin = options.appOrigin ?? TEST_ORIGIN;
const caller = options.caller ?? { role: "user" };
const headers: Record<string, string> = {
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<string, unknown> = {},
options: {
readonly caller?: GatewayCaller;
readonly appOrigin?: string;
} = {},
): Promise<{ status: number; body: Record<string, unknown> }> {
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<string, unknown>),
};
}

/** The names `tools/list` returns for a caller. */
export async function mcpToolNames(
registry: ToolRegistry,
caller: GatewayCaller,
appOrigin?: string,
): Promise<string[]> {
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<string, unknown> }> {
const { body } = await mcpCall(
registry,
"tools/call",
{ name, arguments: input },
{ caller, ...(appOrigin === undefined ? {} : { appOrigin }) },
);
const result = body.result as
| { isError: boolean; structuredContent: Record<string, unknown> }
| 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<string, unknown> }> {
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<string, unknown>,
};
}
Loading
Loading