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
32 changes: 18 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,21 +213,25 @@ const tools = await registerAgentTools({
// After a sign-in or a role change: await tools.refresh();
```

**Effects.** `read` changes nothing (finding, reading, computing, producing a
**Effects** (Lazurio Module Standard, "Effects and publication"; decision D1
of LZD-0037). `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,
never in a runtime that states `LAZURIO_RUNTIME_DEPLOYMENT=production`, else
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.
changes no shared data and prepares a step a person completes in the
interface. `write` is a draft: a reversible change that publishes nothing, which
an agent makes on its own. `publish` is a publication: an irreversible step or
one others see (an approval, a signature, a sending, a deletion, a movement of
money, the publication of a draft or of data to everyone). An agent calls it
only after the person's explicit "Publikuj". A publication is a tool of its own,
never a mode of a draft tool, and the registry gives it `destructiveHint: true`
itself. A draft and a publication are offered only while `dataWriter` allows
writing (`LAZURIO_RUNTIME_DATA_WRITER=true`; unset, never in a runtime that
states `LAZURIO_RUNTIME_DEPLOYMENT=production`, else only to a local or
Environment entry). **Until the Owner decides how the App knows that the person
said "Publikuj", a production application offers no publication**, on `/mcp`
or on the page, and a development version does
(`AGENT_PUBLICATION_IN_PRODUCTION`, the one place that decision changes). A
0.4 declaration of a publication (`effect: "write"` with `publishesData:
true`, or `publicationConsent`) is refused at registration.

**Answers and refusals.** A tool returns `{ ok: true, data, files? }` or
`{ ok: false, reason, message, current_revision?, details? }` and never throws
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@lazurio/module-kit",
"version": "0.4.1",
"version": "0.5.0",
"description": "Lazurio Module Standard runtime helpers: listener, health, shutdown, app access, tools for agents",
"license": "MIT",
"type": "module",
Expand Down
89 changes: 57 additions & 32 deletions src/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,26 @@ export const REFUSAL_CODES = [
] as const;
export type RefusalCode = (typeof REFUSAL_CODES)[number];

/** What a tool does to the App's data:
/** What a tool does (Lazurio Module Standard, "Effects and publication",
* decision D1 of LZD-0037):
* - `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";
* - `prepare`: changes no shared data and prepares a step a person completes
* in the interface;
* - `write`: a draft, a reversible change that publishes nothing. An agent
* makes it on its own;
* - `publish`: a publication, an irreversible step or one others see (an
* approval, a signature, a sending, a deletion, a movement of money, the
* publication of a draft or of data to everyone). An agent calls it only
* after the person's explicit "Publikuj". It always carries
* `destructiveHint`, and until the Owner decides how the App knows that the
* person said "Publikuj", a production application does not offer it. */
export type ToolEffect = "read" | "prepare" | "write" | "publish";

/** Whether an agent may publish in a production application. False until the
* Owner decides how the App knows the person's "Publikuj" (LZD-0037, D1);
* the one place that decision changes. */
export const AGENT_PUBLICATION_IN_PRODUCTION = false;

/** The application role a tool needs at least. */
export type ToolRole = "user" | "admin";
Expand Down Expand Up @@ -154,24 +165,16 @@ interface ToolDefinitionBase<Input> {
) => Promise<ToolResult<object>> | ToolResult<object>;
}

/** One tool of the App. */
export type ToolDefinition<Input = unknown> = ToolDefinitionBase<Input> &
(
| {
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;
}
);
/** One tool of the App. A publication is a tool of its own, never a mode of
* a draft tool. */
export type ToolDefinition<Input = unknown> = ToolDefinitionBase<Input> & {
readonly effect: ToolEffect;
/** Until 0.4: a write that published data. A draft is `write` (this may
* still say `false`); a publication is `effect: "publish"`. */
readonly publishesData?: false;
/** Gone in 0.5: a publication is `effect: "publish"` (LZD-0037, D1). */
readonly publicationConsent?: never;
};

/** Types a tool from its input schema. */
export function defineTool<Input>(
Expand Down Expand Up @@ -257,7 +260,8 @@ export interface ToolRegistry {
* 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). */
* request, an unknown tool or an unreadable body (treat it as a write).
* `write` and `publish` both change data. */
effectOf(request: Request): Promise<ToolEffect | null>;
}

Expand Down Expand Up @@ -336,7 +340,7 @@ function appContextTool(app: AppInfo): ToolDefinition<Record<string, never>> {
}

function descriptor(tool: ToolDefinition<unknown>): ToolDescriptor {
const readOnly = tool.effect !== "write";
const readOnly = tool.effect === "read" || tool.effect === "prepare";
return {
name: tool.name,
...(tool.title === undefined ? {} : { title: tool.title }),
Expand All @@ -349,7 +353,7 @@ function descriptor(tool: ToolDefinition<unknown>): ToolDescriptor {
annotations: {
...(tool.title === undefined ? {} : { title: tool.title }),
readOnlyHint: readOnly,
destructiveHint: tool.effect === "write" && tool.publishesData === true,
destructiveHint: tool.effect === "publish",
idempotentHint: tool.idempotent ?? readOnly,
openWorldHint: false,
untrustedContentHint: tool.untrustedContent === true,
Expand Down Expand Up @@ -471,6 +475,26 @@ export function createToolRegistry(options: ToolRegistryOptions): ToolRegistry {
throw new TypeError(`Tool name is not snake_case: ${tool.name}`);
if (tools.has(tool.name))
throw new TypeError(`Tool defined twice: ${tool.name}`);
// What a JavaScript caller or an older declaration may still hand in.
const declared = tool as unknown as {
readonly effect: unknown;
readonly publishesData?: unknown;
readonly publicationConsent?: unknown;
};
if (
!(["read", "prepare", "write", "publish"] as unknown[]).includes(
declared.effect,
)
)
throw new TypeError(`Tool effect unknown: ${tool.name}`);
if (declared.publishesData === true)
throw new TypeError(
`${tool.name} publishes data: declare it as its own tool with effect "publish"`,
);
if (declared.publicationConsent !== undefined)
throw new TypeError(
`${tool.name}: publicationConsent is gone; a publication is effect "publish" (LZD-0037, D1)`,
);
tools.set(tool.name, tool as ToolDefinition<unknown>);
}
const own = listener(listenerId, env);
Expand Down Expand Up @@ -507,20 +531,21 @@ export function createToolRegistry(options: ToolRegistryOptions): ToolRegistry {
"forbidden",
`${tool.name} needs the Application Admin role.`,
);
if (tool.effect !== "write") return null;
if (tool.effect === "read" || tool.effect === "prepare") return null;
// A draft and a publication go through the same writer gate.
if (!canWrite)
return refusal(
"data_read_only",
"This App does not change data now (read-only mode).",
);
if (
tool.publishesData === true &&
tool.effect === "publish" &&
where === "production" &&
(tool.publicationConsent ?? "").trim() === ""
!AGENT_PUBLICATION_IN_PRODUCTION
)
return refusal(
"forbidden",
`${tool.name} would publish data; in a production application a person publishes in the interface.`,
`${tool.name} publishes; a production application offers agents no publication until the Owner decides how it knows the person's "Publikuj" (LZD-0037, D1). A person publishes in the interface.`,
);
return null;
};
Expand Down
109 changes: 51 additions & 58 deletions test/tools.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, test } from "bun:test";
import {
AGENT_PUBLICATION_IN_PRODUCTION,
createToolRegistry,
dataWriter,
defineTool,
Expand Down Expand Up @@ -97,25 +98,12 @@ const saveDraft = defineTool({
});

const publishRecord = defineTool({
name: "save_record",
description: "Uloží a publikuje změnu záznamu.",
name: "publish_record",
description: "Publikuje koncept záznamu všem.",
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",
effect: "publish",
run: ({ id }) => ({ ok: true, data: { id } }),
});

Expand Down Expand Up @@ -165,7 +153,6 @@ const TOOLS = [
findRecords,
saveDraft,
publishRecord,
publishTicket,
prepareApproval,
exportPdf,
failing,
Expand Down Expand Up @@ -344,7 +331,6 @@ describe("/mcp transport", () => {
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",
Expand Down Expand Up @@ -380,12 +366,15 @@ describe("/mcp transport", () => {
expect(call.structured.reason).toBe("data_read_only");
});

test("a tool that publishes data is not offered in production", async () => {
test("a publication is not offered in production until D1, and is in a development version", async () => {
expect(await mcpToolNames(writer, { role: "admin" })).not.toContain(
"save_record",
"publish_record",
);
const call = await mcpTool(writer, "save_record", { id: "r1" });
const call = await mcpTool(writer, "publish_record", { id: "r1" });
expect(call.structured.reason).toBe("forbidden");
expect(String(call.structured.message)).toContain("LZD-0037, D1");
const viaPage = await pageTool(writer, "publish_record", { id: "r1" });
expect([viaPage.status, viaPage.body.reason]).toEqual([403, "forbidden"]);
const local = registry(localEnvironment());
const response = await local.handleMcp(
new Request("http://127.0.0.1:43100/mcp", {
Expand All @@ -399,46 +388,47 @@ describe("/mcp transport", () => {
);
const listed = (
(await response.json()) as {
result: { tools: Array<{ name: string }> };
result: {
tools: Array<{ name: string; annotations: Record<string, unknown> }>;
};
}
).result.tools.map((tool) => tool.name);
expect(listed).toContain("save_record");
).result.tools;
const published = listed.find((tool) => tool.name === "publish_record");
expect(published?.annotations).toEqual({
readOnlyHint: false,
destructiveHint: true,
idempotentHint: false,
openWorldHint: false,
});
// The same writer gate as a draft: not in a read-only copy.
expect(await mcpToolNames(reader, { role: "admin" })).not.toContain(
"publish_record",
);
expect(AGENT_PUBLICATION_IN_PRODUCTION).toBe(false);
});

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<unknown>,
test("a publication declared the 0.4 way is refused at registration", () => {
const base = {
name: "old_publish",
description: "x",
input: strings("id"),
inputSchema: schema("id"),
minRole: "user" as const,
run: () => ({ ok: true as const, data: {} }),
};
for (const [declared, message] of [
[{ ...base, effect: "write", publishesData: true }, 'effect "publish"'],
[
{ ...base, effect: "write", publicationConsent: "plan DEV-0000" },
"publicationConsent is gone",
],
});
expect(await mcpToolNames(blank, { role: "user" })).not.toContain(
"create_ticket",
);
[{ ...base, effect: "delete" }, "Tool effect unknown"],
] as const)
expect(() =>
registry(hostedEnvironment({ writer: true }), [], {
tools: [declared as unknown as ToolDefinition<unknown>],
}),
).toThrow(message);
});

test("annotations say what a tool does", async () => {
Expand Down Expand Up @@ -829,8 +819,11 @@ describe("effectOf", () => {
),
).toBe("prepare");
expect(
await writer.effectOf(post("/api/agent-tools/save_record", {})),
await writer.effectOf(post("/api/agent-tools/save_record_draft", {})),
).toBe("write");
expect(
await writer.effectOf(post("/api/agent-tools/publish_record", {})),
).toBe("publish");
});
test("other MCP methods and the manifest read; unknown is null", async () => {
expect(
Expand Down
Loading