Skip to content
Open
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
3 changes: 3 additions & 0 deletions src/credits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ export function creditClass(tool: string, kind: string): CreditClass {
if (method === "get_analytics") return action === "export_contacts" ? "export" : "read";
if (method === "call_recordings") return action === "list" || action === "search" ? "read" : "export";
if (method === "send_message" || method === "create_attachment_upload") return "send";
// kaption-links.MCP.5 — create_tracked_links is a send (2 credits); list_tracked_links and get_link_clicks fall
// through to read (1).
if (method === "create_tracked_links") return "send";
if (method.startsWith("manage_")) {
if (READ_ACTIONS.has(action)) return "read";
if (SEND_ACTIONS[method]?.has(action)) return "send";
Expand Down
32 changes: 28 additions & 4 deletions src/ledger-credits.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,10 @@ function restApi(answer: (() => Response) | Record<string, unknown> = planAnswer
return { fetcher, asked };
}

function fakeRoom(phone: string, fail = false) {
function fakeRoom(phone: string, fail = false, features: Record<string, boolean> = {}) {
const room = {
calls: [] as string[],
async watchManage() { return { manage_kaption: true, plans: true }; },
async watchManage() { return { manage_kaption: true, plans: true, ...features }; },
async meteringPhone() { return phone; },
async handleMcpRequestSettled(method: string) {
room.calls.push(method);
Expand All @@ -100,8 +100,8 @@ function fakeRoom(phone: string, fail = false) {
return room;
}

async function world(vars: Record<string, string> = {}, opts: { fail?: boolean } = {}) {
const room = fakeRoom(PHONE, opts.fail);
async function world(vars: Record<string, string> = {}, opts: { fail?: boolean; features?: Record<string, boolean> } = {}) {
const room = fakeRoom(PHONE, opts.fail, opts.features);
const envRef = { env: {} as Env };
const ns = ledgers(envRef);
envRef.env = {
Expand Down Expand Up @@ -188,6 +188,15 @@ describe("mcp-usage-ledger.CREDITS the credit table", () => {
expect(creditsOf("query", "messages")).toBe(1);
});

it("kaption-links.MCP.5 — create_tracked_links is a send (2 credits), list_tracked_links and get_link_clicks are reads (1)", () => {
expect(creditClass("create_tracked_links", "")).toBe("send");
expect(creditsOf("create_tracked_links", "")).toBe(2);
expect(creditClass("list_tracked_links", "")).toBe("read");
expect(creditsOf("list_tracked_links", "")).toBe(1);
expect(creditClass("get_link_clicks", "")).toBe("read");
expect(creditsOf("get_link_clicks", "")).toBe(1);
});

it("advanced-analytics.MCP.6 — each new get_analytics section costs one read credit", () => {
for (const section of ["community_activity", "channel_posts", "post_detail", "community_changes", "message_reads"]) {
const kind = usageKind("get_analytics", { section, chat_id: "120363000000000001@newsletter", post_id: "123" });
Expand Down Expand Up @@ -276,6 +285,21 @@ describe("mcp-usage-ledger.CREDITS a credits month", () => {
expect(((await read.json()) as any).month).toMatchObject({ credits: 3, from: "2026-11-25T00:00:00.000Z" });
});

it("kaption-links.MCP.5 — relayed Kaption Links calls weigh 2 (create) and 1 (list, clicks) in the month, cloud and local alike", async () => {
vi.useFakeTimers({ toFake: ["Date"], now: Date.UTC(2026, 11, 10, 12) });
vi.stubGlobal("fetch", restApi(planAnswer({ tier: "business", limit: 2000, enforced_by: "none", enforce: false })).fetcher);
const w = await world({}, { features: { kaption_links: true } });
// Cloud: 2 creates (4), 1 list (1), 1 clicks read (1) = 6 credits.
for (let i = 0; i < 2; i++) expect((await w.tool("create_tracked_links", { links: [{ url: "https://example.com/sale" }] })).isError).toBeFalsy();
expect((await w.tool("list_tracked_links", { q: "sale" })).isError).toBeFalsy();
expect((await w.tool("get_link_clicks", {})).isError).toBeFalsy();
expect(w.room.calls).toEqual(["create_tracked_links", "create_tracked_links", "list_tracked_links", "get_link_clicks"]);
expect(await w.month()).toMatchObject({ counted: 4, credits: 6 });
// Local hub batch rows weigh the same.
expect((await postBatch(w, "batch_links_01", [{ tool: "create_tracked_links", calls: 3 }, { tool: "get_link_clicks" }])).status).toBe(200);
expect(await w.month()).toMatchObject({ counted: 8, credits: 13 });
});

it("mcp-usage-pricing.CREDITS_V2.4, mcp-usage-ledger.SINGLE.10 — a Pro month in credits is counted and shown, never refused", async () => {
vi.useFakeTimers({ toFake: ["Date"], now: Date.UTC(2026, 11, 3, 12) });
vi.stubGlobal("fetch", restApi(planAnswer({ tier: "pro", limit: 2, enforced_by: "none", enforce: false })).fetcher);
Expand Down
74 changes: 71 additions & 3 deletions src/manage-kaption.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { PLANS_UI_HTML } from "./plans-ui";
import { TOOLS, getToolsForMCP } from "./tools";
import channelsCanonical from "./test-support/mcp-channels-communities-tools.json";
import exportChatCanonical from "./test-support/mcp-export-chat-tools.json";
import linksCanonical from "./test-support/mcp-links-tools.json";
import { FakeKV } from "./test-support/fake-kv";

const flush = () => new Promise((resolve) => setTimeout(resolve, 10));
Expand Down Expand Up @@ -276,8 +277,8 @@ describe("whatsapp-channels-communities.HUB the channels and communities tools o
});

describe("chat-export.MCP export_chat on the relay", () => {
it("chat-export.MCP.2, MCP.4 — is the pinned kaptionai definition, verbatim (read-only), last in TOOLS", async () => {
expect(TOOLS[TOOLS.length - 1].name).toBe("export_chat");
it("chat-export.MCP.2, MCP.4 — is the pinned kaptionai definition, verbatim (read-only), right before the Kaption Links tools", async () => {
expect(TOOLS[TOOLS.length - 1 - LINK_TOOLS.length].name).toBe("export_chat");
const want = (exportChatCanonical as any[])[0];
const got = getToolsForMCP().find((t) => t.name === "export_chat")!;
expect({ name: got.name, title: got.title, description: got.description, inputSchema: normalized(got.inputSchema), annotations: got.annotations }).toEqual(want);
Expand Down Expand Up @@ -317,6 +318,73 @@ describe("chat-export.MCP export_chat on the relay", () => {
});
});

const LINK_TOOLS = ["create_tracked_links", "list_tracked_links", "get_link_clicks"];

describe("kaption-links.MCP the Kaption Links tools on the relay", () => {
it("kaption-links.MCP.1-3, MCP.10 — are the pinned kaptionai definitions, verbatim, last in TOOLS", async () => {
expect(TOOLS.slice(-LINK_TOOLS.length).map((t) => t.name)).toEqual(LINK_TOOLS);
expect((linksCanonical as any[]).map((t) => t.name)).toEqual(LINK_TOOLS);
const exported = getToolsForMCP();
const listed = (await (await session(fakeRoom({ kaption_links: true }))).client.listTools()).tools;
for (const want of linksCanonical as any[]) {
const got = exported.find((t) => t.name === want.name)!;
expect({ name: got.name, title: got.title, description: got.description, inputSchema: normalized(got.inputSchema), annotations: got.annotations }).toEqual(normalized(want));
const l = listed.find((t) => t.name === want.name)!;
expect(l.title, want.name).toBe(want.title);
expect(l.description, want.name).toBe(want.description);
expect(l.annotations, want.name).toEqual(want.annotations);
expect(normalized(l.inputSchema), want.name).toEqual(normalized(want.inputSchema));
}
});

it("kaption-links.MCP.10 — only features.kaption_links true shows them; false, absent or an older extension hides them", async () => {
expect([...visibleManageTools([{ kaption_links: true }])]).toEqual(LINK_TOOLS);
expect(readManageFeatures({ kaption_links: true, export_chat: "yes" })).toEqual({ kaption_links: true });
expect(readManageFeatures({ kaption_links: 1 })).toEqual({});
for (const features of [{}, null, { manage_kaption: true, export_chat: true, channels_communities: true }, { kaption_links: false }]) {
const names = (await (await session(fakeRoom(features))).client.listTools()).tools.map((t) => t.name);
for (const name of LINK_TOOLS) expect(names, JSON.stringify(features)).not.toContain(name);
}
});

it("kaption-links.MCP.10 — appear with list_changed and are forwarded unchanged by name; hidden calls never reach the extension", async () => {
const room = fakeRoom({ manage_kaption: true });
const s = await session(room);
const hidden: any = await s.client.callTool({ name: "create_tracked_links", arguments: { links: [{ url: "https://example.com" }] } });
expect(hidden.isError).toBe(true);
expect(room.calls).toEqual([]);
room.features = { manage_kaption: true, kaption_links: true };
await s.agent.refreshManageVisibility();
await flush();
expect(await s.manage()).toEqual(expect.arrayContaining(LINK_TOOLS));
expect(s.changed.tools).toBeGreaterThan(0);
const calls: Array<[string, Record<string, unknown>]> = [
["create_tracked_links", { links: [{ url: "https://example.com/menu", title: "Menu", post_id: "weekly-menu-48", chat_id: "120363000000000001@newsletter" }] }],
["list_tracked_links", { q: "sale", limit: 10, cursor: "c_1", target_session: "s_2" }],
["get_link_clicks", { link: "l_0123456789abcdef", granularity: "hour", from: "2026-11-20" }],
["get_link_clicks", {}],
];
for (const [name, args] of calls) {
const res: any = await s.client.callTool({ name, arguments: args });
expect(res.isError, name).toBeFalsy();
}
expect(room.calls).toEqual(calls.map(([method, params]) => ({ method, params })));
// The pinned schemas are enforced before forwarding: 0 or 21 links, a 101 limit, an unknown field or granularity.
for (const [name, args] of [
["create_tracked_links", { links: [] }],
["create_tracked_links", { links: Array.from({ length: 21 }, () => ({ url: "https://example.com" })) }],
["create_tracked_links", { links: [{ url: "https://example.com", phone: "x" }] }],
["list_tracked_links", { limit: 101 }],
["list_tracked_links", { limit: 2.5 }],
["get_link_clicks", { granularity: "week" }],
] as Array<[string, Record<string, unknown>]>) {
const res: any = await s.client.callTool({ name, arguments: args });
expect(res.isError, `${name} ${JSON.stringify(args)}`).toBe(true);
}
expect(room.calls).toHaveLength(calls.length);
});
});

describe("mcp-manage-kaption.LIST.2 an MCP session lists the manage tools from its extension's features", () => {
it("hidden for an extension that said nothing, or when none is connected", async () => {
expect(await (await session(fakeRoom({}))).manage()).toEqual([]);
Expand All @@ -331,7 +399,7 @@ describe("mcp-manage-kaption.LIST.2 an MCP session lists the manage tools from i
expect(room.watchers).toEqual(["ab".repeat(32)]);
expect(await s.manage()).toEqual(["get_kaption_settings", "update_kaption_settings", "reconnect_kaption_connection", "kaption_help", "report_bug"]);

room.features = { manage_kaption: true, business_agent: true, plans: true, scheduled_status: true, channels_communities: true, export_chat: true };
room.features = { manage_kaption: true, business_agent: true, plans: true, scheduled_status: true, channels_communities: true, export_chat: true, kaption_links: true };
await s.agent.refreshManageVisibility();
await flush();
expect(await s.manage()).toEqual(MANAGE_KAPTION_TOOLS);
Expand Down
9 changes: 8 additions & 1 deletion src/manage-kaption.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ export interface ManageFeatures {
channels_communities?: boolean;
/** chat-export.MCP.6 — MCP_EXPORT_CHAT on for this account (export_chat). */
export_chat?: boolean;
/** kaption-links.MCP.10 — MCP_KAPTION_LINKS on for this account (create_tracked_links, list_tracked_links,
* get_link_clicks). */
kaption_links?: boolean;
}

/** mcp-manage-kaption.LIST.2 — which `features` key shows each tool. */
Expand All @@ -56,11 +59,15 @@ export const MANAGE_TOOL_FEATURE: Readonly<Record<string, keyof ManageFeatures>>
get_community: 'channels_communities',
get_community_digest: 'channels_communities',
export_chat: 'export_chat',
// kaption-links.MCP.10 — the Kaption Links tools, answered by the extension's account core.
create_tracked_links: 'kaption_links',
list_tracked_links: 'kaption_links',
get_link_clicks: 'kaption_links',
});

export const MANAGE_KAPTION_TOOLS: readonly string[] = Object.freeze(Object.keys(MANAGE_TOOL_FEATURE));

const FEATURE_KEYS: Array<keyof ManageFeatures> = ['manage_kaption', 'business_agent', 'plans', 'scheduled_status', 'channels_communities', 'export_chat'];
const FEATURE_KEYS: Array<keyof ManageFeatures> = ['manage_kaption', 'business_agent', 'plans', 'scheduled_status', 'channels_communities', 'export_chat', 'kaption_links'];

/** Only booleans are kept; anything else (missing, "yes", 1) is unknown, which counts as no. */
export function readManageFeatures(features: unknown): ManageFeatures {
Expand Down
9 changes: 6 additions & 3 deletions src/relay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,17 @@ describe("Tool registration", () => {
"get_community",
"get_community_digest",
"export_chat",
"create_tracked_links",
"list_tracked_links",
"get_link_clicks",
];

it("exports exactly 47 tools", () => {
expect(TOOLS).toHaveLength(47);
it("exports exactly 50 tools", () => {
expect(TOOLS).toHaveLength(50);
});

it("keeps local API credentials off the public cloud tool surface", () => {
expect(CLOUD_TOOLS).toHaveLength(46);
expect(CLOUD_TOOLS).toHaveLength(49);
expect(CLOUD_TOOLS.map((tool) => tool.name)).not.toContain("get_api_info");
});

Expand Down
Loading