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
79 changes: 79 additions & 0 deletions examples/pdf-server/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1862,3 +1862,82 @@ describe.skipIf(!viewIsBuilt)("splitAppTools view config injection", () => {
expect(idx).toBeLessThan(html.indexOf("<script type"));
});
});

describe("interact annotation schema validation", () => {
async function callInteract(args: Record<string, unknown>) {
const server = createServer({ enableInteract: true });
const client = new Client({ name: "t", version: "1" });
const [ct, st] = InMemoryTransport.createLinkedPair();
await Promise.all([server.connect(st), client.connect(ct)]);
try {
return await client.callTool({
name: "interact",
arguments: {
viewUUID: "11111111-2222-3333-4444-555555555555",
...args,
},
});
} finally {
await client.close();
await server.close();
}
}

it("rejects a stamp without label, naming the field", async () => {
const result = await callInteract({
action: "add_annotations",
annotations: [
// The classic mix-up: `content` (note/freetext's field) instead of
// `label` — previously this rendered as the literal text "undefined".
{
id: "s1",
type: "stamp",
page: 1,
x: 100,
y: 100,
content: "APPROVED",
},
],
});
expect(result.isError).toBe(true);
const text = (result.content as Array<{ text?: string }>)[0]?.text ?? "";
expect(text).toContain("annotations[0] (stamp)");
expect(text).toContain("label");
});

it("accepts a valid stamp and queues it", async () => {
const result = await callInteract({
action: "add_annotations",
annotations: [
{ id: "s1", type: "stamp", page: 1, x: 100, y: 100, label: "APPROVED" },
],
});
expect(result.isError).toBeFalsy();
const text = (result.content as Array<{ text?: string }>)[0]?.text ?? "";
expect(text).toContain("Queued");
});

it("rejects an unknown annotation type", async () => {
const result = await callInteract({
action: "add_annotations",
annotations: [{ id: "x1", type: "sparkles", page: 1 }],
});
expect(result.isError).toBe(true);
});

it("update_annotations accepts a partial def but still requires id", async () => {
const ok = await callInteract({
action: "update_annotations",
annotations: [{ id: "s1", type: "stamp", label: "REJECTED" }],
});
expect(ok.isError).toBeFalsy();

const bad = await callInteract({
action: "update_annotations",
annotations: [{ type: "stamp", label: "REJECTED" }],
});
expect(bad.isError).toBe(true);
const text = (bad.content as Array<{ text?: string }>)[0]?.text ?? "";
expect(text).toContain("id");
});
});
50 changes: 44 additions & 6 deletions examples/pdf-server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,11 @@ const PageInterval = z.object({
// poll queue. Defined once in src/commands.ts; both sides import it.
// (`import type` → no pdf-lib bundled into the server.)
import type { PdfCommand } from "./src/commands.js";
import {
AnnotationDefSchema,
AnnotationUpdateSchema,
formatAnnotationIssues,
} from "./src/annotation-schemas.js";
export type { PdfCommand };

// =============================================================================
Expand Down Expand Up @@ -2043,6 +2048,24 @@ URL: ${normalized}`,
],
isError: true,
};
// Enforce the per-type contract (e.g. a stamp REQUIRES `label`;
// without this a stamp sent with `content` instead rendered as
// the literal text "undefined").
for (let i = 0; i < annotations.length; i++) {
const parsed = AnnotationDefSchema.safeParse(annotations[i]);
if (!parsed.success) {
return {
content: [
{
type: "text",
text: `add_annotations: ${formatAnnotationIssues(i, (annotations[i] as { type?: unknown }).type, parsed.error)}`,
},
],
isError: true,
};
}
annotations[i] = parsed.data;
}
// Resolve image annotations: fetch imageUrl → imageData, auto-detect dimensions.
// Rejection (path not allowed, not https, fetch failed) surfaces as
// a tool error so the model sees it — don't silently skip.
Expand All @@ -2065,9 +2088,9 @@ URL: ${normalized}`,
}
enqueueCommand(uuid, {
type: "add_annotations",
// resolveImageAnnotation populates optional x/y/width/height;
// input is validated as Record<string,any>[] so this cast is
// the wire-protocol promise, not a compiler guarantee.
// Schema-validated above; the residual gap this cast bridges
// is the image variant's optional x/y/width/height, which
// resolveImageAnnotation has just filled in.
annotations: annotations as Extract<
PdfCommand,
{ type: "add_annotations" }
Expand All @@ -2086,6 +2109,21 @@ URL: ${normalized}`,
],
isError: true,
};
for (let i = 0; i < annotations.length; i++) {
const parsed = AnnotationUpdateSchema.safeParse(annotations[i]);
if (!parsed.success) {
return {
content: [
{
type: "text",
text: `update_annotations: ${formatAnnotationIssues(i, (annotations[i] as { type?: unknown }).type, parsed.error)}`,
},
],
isError: true,
};
}
annotations[i] = parsed.data;
}
enqueueCommand(uuid, {
type: "update_annotations",
annotations: annotations as Extract<
Expand Down Expand Up @@ -2409,11 +2447,11 @@ IMPORTANT: viewUUID must be the exact UUID returned by display_pdf (e.g. "a1b2c3
- For highlights/underlines, each rect's y is the TOP of the highlighted region.

Annotation types:
• highlight: rects:[{x,y,width,height}], color?, content? • underline: rects:[{x,y,w,h}], color?
• strikethrough: rects:[{x,y,w,h}], color? • note: x, y, content, color?
• highlight: rects:[{x,y,width,height}], color?, content? • underline: rects:[{x,y,width,height}], color?
• strikethrough: rects:[{x,y,width,height}], color? • note: x, y, content, color?
• rectangle: x, y, width, height, color?, fillColor?, rotation? • circle: x, y, width, height, color?, fillColor?
• line: x1, y1, x2, y2, color? • freetext: x, y, content, fontSize?, color?
• stamp: x, y, label (any text, e.g. APPROVED, DRAFT, CONFIDENTIAL), color?, rotation?
• stamp: x, y, label (REQUIRED — the stamp's text, e.g. APPROVED, DRAFT, CONFIDENTIAL), color?, rotation?
• image: imageUrl (required), x?, y?, width?, height?, mimeType?, rotation?, aspect? — places an image (signature, logo, etc.) on the page. Pass a local file path or HTTPS URL (NO data: URIs, NO base64). Width/height auto-detected if omitted. Users can also drag & drop images directly onto the viewer.

TIP: For text annotations, prefer highlight_text (auto-finds text) over manual rects.
Expand Down
Loading
Loading