mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-23 21:24:45 +01:00
feat(mcp): show live progress for long connected-app tool calls in the task chat (#21449)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents call tools from connected apps through the Paperclip MCP gateway > - Some tool calls take a long time: exports, builds, large searches > - The MCP progress utility lets an app report how far a call is, but Paperclip ignored it > - So the task chat showed only a spinner until the call finished, with no sign of life > - This pull request reads the app's progress and shows it on the tool's row while the call runs > - The benefit is that people can see that a long call is working, how far it is, and how long it has run ## Linked Issues or Issue Description **Subsystem affected** Connected apps (MCP gateway) and the task chat. **Problem or motivation** A long tool call from a connected MCP app shows only a spinner in the task chat. Paperclip does not send a `progressToken`, and it drops `notifications/progress` from the app. **Proposed solution** Send a `progressToken` on each `tools/call` that an agent run makes. Read the app's progress notifications from the call's response stream. Show a progress bar (or an indeterminate sweep), the latest message, and elapsed time on the running tool row. Keep the latest state so that a reload mid-call shows it. **Alternatives considered** A new transport for progress. The existing company live-events socket already carries per-run events with run read checks, so this change uses it. **Additional context** Spec: https://modelcontextprotocol.io/specification/2026-07-28/basic/utilities/progress ## What Changed - `mcp-http.ts`: `mcpHttpRequestInit` can add `_meta.progressToken`. `readMcpHttpResponse` gives each notification on the response stream to an observer before the result. The observer cannot fail or delay the call. New `mcpProgressNotificationOf` matches a notification to its token. - `tool-gateway.ts`: remote HTTP and local stdio `tools/call` from an agent run send a per-call token and forward progress to a reporter. Calls without a run send no token. - New `server/src/services/tool-call-progress.ts`: checks each update (finite, increasing, plain single-line text of at most 200 characters). It publishes a `heartbeat.run.tool_progress` live event at most every 250 ms (latest wins) and saves the latest update on the invocation at most every 1 s. Nothing is awaited by the call. A final `done` event goes out when the call ends. - DB: nullable `tool_invocations.progress` jsonb column (migration `0479`, `ADD COLUMN` only). A save never writes onto a finished call. - Live delivery: the new event follows its run like transcript output. A client gets it only for runs it follows, after the run read check, in the run's company only. - New route `GET /api/issues/:issueId/tool-call-progress` (task read check) returns the latest progress of the task's running calls, for a reload mid-call. Documented in `docs/api/issues.md`. - UI: `ToolCallProgressProvider` (one per chat) keeps the latest update per call. A running tool row subscribes and shows a bar or sweep, the message, the percent and elapsed time (design tokens, reduced motion honored). Finished rows drop it and never fetch or re-render for progress. `LiveUpdatesProvider` ignores the event for query invalidation. - `packages/kv-demo-mcp-server`: new `slow_with_progress` demo tool (`steps`, `stepMs`, `withTotal`) in its own file. - Storybook: `Tasks/Tool progress` stories (running with total, running without total, done). - Docs: new `doc/connections/MCP-PROGRESS.md`; `MCP-PROTOCOL-VERSIONS.md` no longer lists progress as unsupported. ## Verification - Red/green: on the original source, 5 of the new server tests fail (token in `_meta`, SSE with interleaved progress and result, notification matching, run-interest delivery, gateway end-to-end). With this change they pass. - `server/src/__tests__/mcp-http.test.ts` (13), `tool-call-progress.test.ts` (9: throttling, latest wins, bounded text, out-of-order drop, finish, failures never throw, company/run/tool scoping), `tool-call-progress-store.test.ts` (2, embedded Postgres: company and task scoping, no write onto a finished call), `realtime/live-event-delivery.test.ts` (run interest), `tool-gateway.test.ts` end-to-end against the real SDK kv demo server over Streamable HTTP: 6 provider updates over about 1.2 s give 3 to 7 throttled events, all for the right company, run, task and tool, the last one `done`; no event reaches another company; the invocation keeps the progress; the result is unchanged. - UI: `tool-call-progress.test.tsx` (10: name matching, row states, plain-text rendering, drop on complete, restore after reload, no fetch for finished rows). All 67 task-chat test files pass. - `packages/kv-demo-mcp-server`: 13 tests, including progress over HTTP with and without a total. - Storybook: checked the three stories in a browser. The bar fills to 40%, the sweep animates, the elapsed time ticks, and the done row shows no progress. - `pnpm verify`: see the CI checks for the final revision. ## Risks - Low. The migration adds one nullable column. - An SSE response is now bounded per message, not per stream, so handled notifications (such as progress) do not use up the result's size limit. Each message is still bounded. - Progress code runs only while a run's tool call is in flight. It adds a few bytes to the request and throttled, fire-and-forget work. Agent boot and time to first token do not change. - A row finds its call by run and tool name. If one run calls the same tool twice at the same time, both rows show the newer call's progress. - Progress from a call that became an MCP Task is not shown. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5d0b27acca
commit
a726dce4f0
41 files changed
+1946
-22
No files matched your search
@@ -119,3 +119,93 @@ describe("parseMcpHttpResponseBody", () => {
|
||||
expect(() => parseMcpHttpResponseBody("event: ping\n\n", "text/event-stream")).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("MCP progress notifications", () => {
|
||||
it("sends the progress token in the request's _meta and keeps other metadata", async () => {
|
||||
const { mcpHttpRequestInit } = await import("../services/mcp-http.js");
|
||||
const init = mcpHttpRequestInit({ "MCP-Protocol-Version": "2026-07-28" }, {
|
||||
id: "call-1", method: "tools/call", params: { name: "export", arguments: {}, _meta: { other: true } },
|
||||
}, { progressToken: "token-1" });
|
||||
const meta = JSON.parse(init.body).params._meta;
|
||||
expect(meta.progressToken).toBe("token-1");
|
||||
expect(meta.other).toBe(true);
|
||||
expect(meta["io.modelcontextprotocol/protocolVersion"]).toBe("2026-07-28");
|
||||
const without = mcpHttpRequestInit(undefined, { id: "call-2", method: "tools/call", params: { name: "export" } });
|
||||
expect(JSON.parse(without.body).params._meta?.progressToken).toBeUndefined();
|
||||
});
|
||||
|
||||
it("reads progress interleaved with the result on one SSE stream, before the result", async () => {
|
||||
const { mcpProgressNotificationOf } = await import("../services/mcp-http.js");
|
||||
const frames = [
|
||||
{ jsonrpc: "2.0", method: "notifications/progress", params: { progressToken: "token-1", progress: 1, total: 3, message: "Exporting rows" } },
|
||||
{ jsonrpc: "2.0", method: "notifications/message", params: { level: "info", data: "unrelated" } },
|
||||
{ jsonrpc: "2.0", method: "notifications/progress", params: { progressToken: "someone-else", progress: 9 } },
|
||||
{ jsonrpc: "2.0", method: "notifications/progress", params: { progressToken: "token-1", progress: 2, total: 3 } },
|
||||
{ jsonrpc: "2.0", id: "call-1", result: { content: [{ type: "text", text: "done" }] } },
|
||||
{ jsonrpc: "2.0", method: "notifications/progress", params: { progressToken: "token-1", progress: 3, total: 3 } },
|
||||
];
|
||||
// Split mid-event so frames cross chunk boundaries.
|
||||
const text = frames.map((frame) => `event: message\r\ndata: ${JSON.stringify(frame)}\r\n\r\n`).join("");
|
||||
const encoded = new TextEncoder().encode(text);
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
for (let i = 0; i < encoded.length; i += 37) controller.enqueue(encoded.slice(i, i + 37));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
const seen: unknown[] = [];
|
||||
let resultSeenBeforeProgress = false;
|
||||
const result = await readMcpHttpResponse(new Response(body, { headers: { "content-type": "text/event-stream" } }), "call-1", {
|
||||
onNotification: (message) => {
|
||||
const update = mcpProgressNotificationOf(message, "token-1");
|
||||
if (update) seen.push(update);
|
||||
},
|
||||
onProgress: (progress) => { if (progress.matchedResponse && seen.length === 0) resultSeenBeforeProgress = true; },
|
||||
});
|
||||
expect(result).toMatchObject({ id: "call-1", result: { content: [{ text: "done" }] } });
|
||||
expect(resultSeenBeforeProgress).toBe(false);
|
||||
expect(seen).toEqual([
|
||||
{ progress: 1, total: 3, message: "Exporting rows" },
|
||||
{ progress: 2, total: 3, message: undefined },
|
||||
]);
|
||||
});
|
||||
|
||||
it("never lets a failing progress observer fail the call", async () => {
|
||||
const text = [
|
||||
{ jsonrpc: "2.0", method: "notifications/progress", params: { progressToken: "t", progress: 1 } },
|
||||
{ jsonrpc: "2.0", id: 7, result: { ok: true } },
|
||||
].map((frame) => `data: ${JSON.stringify(frame)}\n\n`).join("");
|
||||
const result = await readMcpHttpResponse(new Response(text, { headers: { "content-type": "text/event-stream" } }), 7, {
|
||||
onNotification: () => { throw new Error("observer broke"); },
|
||||
});
|
||||
expect(result).toMatchObject({ result: { ok: true } });
|
||||
});
|
||||
|
||||
it("ignores requests, responses and other tokens", async () => {
|
||||
const { mcpProgressNotificationOf } = await import("../services/mcp-http.js");
|
||||
expect(mcpProgressNotificationOf({ method: "notifications/progress", params: { progressToken: "t", progress: 1 } }, undefined)).toBeNull();
|
||||
expect(mcpProgressNotificationOf({ id: 1, method: "notifications/progress", params: { progressToken: "t", progress: 1 } }, "t")).toBeNull();
|
||||
expect(mcpProgressNotificationOf({ method: "notifications/progress", params: { progressToken: "x", progress: 1 } }, "t")).toBeNull();
|
||||
expect(mcpProgressNotificationOf({ method: "notifications/progress", params: { progressToken: "t", progress: 1 } }, "t")).toEqual({ progress: 1, total: undefined, message: undefined });
|
||||
});
|
||||
|
||||
it("does not count handled progress against the result's size limit", async () => {
|
||||
const note = `data: ${JSON.stringify({ jsonrpc: "2.0", method: "notifications/progress", params: { progressToken: "t", progress: 1, message: "x".repeat(200) } })}\n\n`;
|
||||
const text = note.repeat(50) + `data: ${JSON.stringify({ jsonrpc: "2.0", id: 1, result: { ok: true } })}\n\n`;
|
||||
expect(Buffer.byteLength(text)).toBeGreaterThan(5_000);
|
||||
const result = await readMcpHttpResponse(new Response(text, { headers: { "content-type": "text/event-stream" } }), 1, { maxBytes: 1_000, limitPerMessage: true });
|
||||
expect(result).toMatchObject({ result: { ok: true } });
|
||||
// Callers without an overall deadline (catalog discovery) keep the total limit,
|
||||
// so a stream of small notifications cannot keep them waiting forever.
|
||||
await expect(readMcpHttpResponse(new Response(text, { headers: { "content-type": "text/event-stream" } }), 1, { maxBytes: 1_000 }))
|
||||
.rejects.toMatchObject({ reason: "too_large" });
|
||||
});
|
||||
|
||||
it("still rejects one SSE message over the limit, complete or not", async () => {
|
||||
const big = `data: ${JSON.stringify({ jsonrpc: "2.0", id: 1, result: { text: "x".repeat(2_000) } })}`;
|
||||
for (const text of [`${big}\n\n`, big]) {
|
||||
await expect(readMcpHttpResponse(new Response(text, { headers: { "content-type": "text/event-stream" } }), 1, { maxBytes: 1_000, limitPerMessage: true }))
|
||||
.rejects.toMatchObject({ reason: "too_large" });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { agents, companies, createDb, heartbeatRuns, issues, toolInvocations, type Db } from "@paperclipai/db";
|
||||
import { listToolCallProgress, saveToolCallProgress } from "../services/tool-call-progress.js";
|
||||
import { assignedToolName } from "../services/native-runtime/assigned-mcp-tools.js";
|
||||
import { startRecoveryPostgres } from "./helpers/recovery-postgres.js";
|
||||
|
||||
describe("saved tool call progress", () => {
|
||||
let temporary: Awaited<ReturnType<typeof startRecoveryPostgres>>;
|
||||
let db: Db;
|
||||
|
||||
beforeAll(async () => {
|
||||
temporary = await startRecoveryPostgres("tool-call-progress-");
|
||||
db = createDb(temporary.connectionString);
|
||||
}, 120_000);
|
||||
afterAll(async () => { await temporary?.cleanup(); });
|
||||
|
||||
async function task(prefix: string) {
|
||||
const companyId = randomUUID();
|
||||
const issueId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: prefix, issuePrefix: prefix });
|
||||
const [agent] = await db.insert(agents).values({ companyId, name: "Agent", adapterType: "process" }).returning();
|
||||
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent!.id, status: "running" }).returning();
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Export" });
|
||||
const call = async (values: Partial<typeof toolInvocations.$inferInsert> = {}) => (await db.insert(toolInvocations).values({
|
||||
companyId, issueId, runId: run!.id, agentId: agent!.id, toolName: "kv_demo__slow_with_progress",
|
||||
status: "executing", startedAt: new Date("2026-11-13T10:00:00Z"), ...values,
|
||||
}).returning())[0]!;
|
||||
return { companyId, issueId, runId: run!.id, call };
|
||||
}
|
||||
const progress = (value: number) => ({ progress: value, total: 10, message: "Exporting", updatedAt: "2026-11-13T10:00:05.000Z" });
|
||||
|
||||
it("returns a task's running calls with their latest progress, and nothing from another company or task", async () => {
|
||||
const mine = await task("PRGA");
|
||||
const theirs = await task("PRGB");
|
||||
const running = await mine.call();
|
||||
await saveToolCallProgress(db, mine.companyId, running.id)(progress(3));
|
||||
await saveToolCallProgress(db, mine.companyId, running.id)(progress(4));
|
||||
const other = await theirs.call();
|
||||
await saveToolCallProgress(db, theirs.companyId, other.id)(progress(9));
|
||||
// A write naming the wrong company never lands.
|
||||
await saveToolCallProgress(db, mine.companyId, other.id)(progress(1));
|
||||
const now = new Date("2026-11-13T10:01:00Z");
|
||||
|
||||
expect(await listToolCallProgress(db, mine.companyId, mine.issueId, now)).toEqual([{
|
||||
invocationId: running.id, runId: mine.runId, toolName: "kv_demo__slow_with_progress",
|
||||
nativeToolName: assignedToolName("kv_demo__slow_with_progress"),
|
||||
startedAt: "2026-11-13T10:00:00.000Z", progress: 4, total: 10, message: "Exporting",
|
||||
updatedAt: "2026-11-13T10:00:05.000Z", done: false,
|
||||
}]);
|
||||
expect(await listToolCallProgress(db, mine.companyId, theirs.issueId, now)).toEqual([]);
|
||||
expect(await listToolCallProgress(db, theirs.companyId, mine.issueId, now)).toEqual([]);
|
||||
expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, other.id)))[0]!.progress).toMatchObject({ progress: 9 });
|
||||
});
|
||||
|
||||
it("never writes progress onto a finished call, and reports it as done", async () => {
|
||||
const mine = await task("PRGC");
|
||||
const running = await mine.call({ createdAt: new Date() });
|
||||
await saveToolCallProgress(db, mine.companyId, running.id)(progress(2));
|
||||
expect(await listToolCallProgress(db, mine.companyId, mine.issueId)).toHaveLength(1);
|
||||
await db.update(toolInvocations).set({ status: "succeeded", completedAt: new Date() }).where(eq(toolInvocations.id, running.id));
|
||||
// A late, throttled save after the result must not overwrite it.
|
||||
await saveToolCallProgress(db, mine.companyId, running.id)(progress(8));
|
||||
expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, running.id)))[0]!.progress).toMatchObject({ progress: 2 });
|
||||
// A chat that missed the end learns it; a call that never saved progress is reported too.
|
||||
const notSaved = await mine.call({ createdAt: new Date() });
|
||||
await db.update(toolInvocations).set({ status: "succeeded", completedAt: new Date() }).where(eq(toolInvocations.id, notSaved.id));
|
||||
const listed = await listToolCallProgress(db, mine.companyId, mine.issueId);
|
||||
expect(listed.map((entry) => [entry.invocationId, entry.done, entry.progress]).sort()).toEqual(
|
||||
[[running.id, true, 2], [notSaved.id, true, 0]].sort(),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { TOOL_CALL_PROGRESS_MESSAGE_MAX_LENGTH } from "@paperclipai/shared";
|
||||
import {
|
||||
createToolCallProgressReporter,
|
||||
TOOL_CALL_PROGRESS_PUBLISH_INTERVAL_MS,
|
||||
TOOL_CALL_PROGRESS_SAVE_INTERVAL_MS,
|
||||
} from "../services/tool-call-progress.js";
|
||||
import { assignedToolName } from "../services/native-runtime/assigned-mcp-tools.js";
|
||||
|
||||
function reporter() {
|
||||
const published: Array<{ companyId: string; type: string; payload: Record<string, unknown> }> = [];
|
||||
const saved: unknown[] = [];
|
||||
const instance = createToolCallProgressReporter({
|
||||
companyId: "company-a",
|
||||
runId: "run-a",
|
||||
issueId: "issue-a",
|
||||
agentId: "agent-a",
|
||||
invocationId: "invocation-a",
|
||||
toolName: "kv_demo__slow_with_progress",
|
||||
startedAt: new Date("2026-11-13T10:00:00Z"),
|
||||
publish: (event) => { published.push(event); },
|
||||
save: async (progress) => { saved.push(progress); },
|
||||
});
|
||||
return { instance, published, saved };
|
||||
}
|
||||
|
||||
describe("tool call progress reporter", () => {
|
||||
beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(new Date("2026-11-13T10:00:01Z")); });
|
||||
afterEach(() => { vi.useRealTimers(); });
|
||||
|
||||
it("publishes at most one update per interval and always the latest", () => {
|
||||
const { instance, published } = reporter();
|
||||
for (let step = 1; step <= 50; step++) instance.report({ progress: step, total: 50, message: `Step ${step}` });
|
||||
// The first update goes out at once; the rest wait for the interval.
|
||||
expect(published.map((event) => event.payload.progress)).toEqual([1]);
|
||||
vi.advanceTimersByTime(TOOL_CALL_PROGRESS_PUBLISH_INTERVAL_MS);
|
||||
expect(published.map((event) => event.payload.progress)).toEqual([1, 50]);
|
||||
vi.advanceTimersByTime(TOOL_CALL_PROGRESS_PUBLISH_INTERVAL_MS * 4);
|
||||
expect(published).toHaveLength(2);
|
||||
// A steady stream for one second publishes about four times, never per update.
|
||||
for (let tick = 0; tick < 100; tick++) {
|
||||
instance.report({ progress: 51 + tick, total: 200 });
|
||||
vi.advanceTimersByTime(10);
|
||||
}
|
||||
expect(published.length - 2).toBeLessThanOrEqual(1_000 / TOOL_CALL_PROGRESS_PUBLISH_INTERVAL_MS + 1);
|
||||
});
|
||||
|
||||
it("saves on the invocation less often than it publishes", async () => {
|
||||
const { instance, saved } = reporter();
|
||||
for (let tick = 0; tick < 200; tick++) {
|
||||
instance.report({ progress: tick, total: 200 });
|
||||
await vi.advanceTimersByTimeAsync(10);
|
||||
}
|
||||
expect(saved.length).toBeLessThanOrEqual(2_000 / TOOL_CALL_PROGRESS_SAVE_INTERVAL_MS + 1);
|
||||
expect(saved.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it("ties every event to its company, run and tool call", () => {
|
||||
const { instance, published } = reporter();
|
||||
instance.report({ progress: 1, total: 4, message: "Reading" });
|
||||
expect(published[0]).toEqual({
|
||||
companyId: "company-a",
|
||||
type: "heartbeat.run.tool_progress",
|
||||
payload: {
|
||||
invocationId: "invocation-a",
|
||||
runId: "run-a",
|
||||
issueId: "issue-a",
|
||||
agentId: "agent-a",
|
||||
toolName: "kv_demo__slow_with_progress",
|
||||
nativeToolName: assignedToolName("kv_demo__slow_with_progress"),
|
||||
startedAt: "2026-11-13T10:00:00.000Z",
|
||||
updatedAt: "2026-11-13T10:00:01.000Z",
|
||||
progress: 1,
|
||||
total: 4,
|
||||
message: "Reading",
|
||||
done: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("treats provider text as untrusted: plain, single-line and bounded", () => {
|
||||
const { instance, published } = reporter();
|
||||
instance.report({ progress: 1, message: `<b>bold</b>\n\u0007line${"x".repeat(1_000)}` });
|
||||
const message = published[0]!.payload.message as string;
|
||||
expect(message.startsWith("<b>bold</b> line ")).toBe(true);
|
||||
expect(message).not.toMatch(/[\n\u0007]/);
|
||||
expect(message.length).toBe(TOOL_CALL_PROGRESS_MESSAGE_MAX_LENGTH);
|
||||
});
|
||||
|
||||
it("drops unusable and out-of-order updates", () => {
|
||||
const { instance, published } = reporter();
|
||||
instance.report({ progress: "1", total: 2 });
|
||||
instance.report({ progress: Number.NaN });
|
||||
instance.report({ progress: -1 });
|
||||
expect(published).toEqual([]);
|
||||
instance.report({ progress: 5, total: 2 });
|
||||
expect(published[0]!.payload).toMatchObject({ progress: 5, total: null });
|
||||
vi.advanceTimersByTime(TOOL_CALL_PROGRESS_PUBLISH_INTERVAL_MS);
|
||||
instance.report({ progress: 3, total: 10 });
|
||||
vi.advanceTimersByTime(TOOL_CALL_PROGRESS_PUBLISH_INTERVAL_MS);
|
||||
expect(published).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("on finish stops pending work and tells viewers to drop the progress", () => {
|
||||
const { instance, published, saved } = reporter();
|
||||
instance.report({ progress: 1, total: 3 });
|
||||
instance.report({ progress: 2, total: 3 });
|
||||
instance.finish();
|
||||
vi.advanceTimersByTime(TOOL_CALL_PROGRESS_SAVE_INTERVAL_MS * 3);
|
||||
expect(published.map((event) => [event.payload.progress, event.payload.done])).toEqual([[1, false], [2, true]]);
|
||||
expect(saved).toHaveLength(1);
|
||||
instance.report({ progress: 3, total: 3 });
|
||||
expect(published).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("a call that never reported progress finishes silently", () => {
|
||||
const { instance, published } = reporter();
|
||||
instance.finish();
|
||||
expect(published).toEqual([]);
|
||||
});
|
||||
|
||||
it("never throws into the call when publishing or saving fails", async () => {
|
||||
const instance = createToolCallProgressReporter({
|
||||
companyId: "c", runId: "r", issueId: null, agentId: null, invocationId: "i", toolName: "t",
|
||||
publish: () => { throw new Error("socket gone"); },
|
||||
save: async () => { throw new Error("db gone"); },
|
||||
});
|
||||
expect(() => instance.report({ progress: 1 })).not.toThrow();
|
||||
expect(() => instance.finish()).not.toThrow();
|
||||
await vi.runAllTimersAsync();
|
||||
});
|
||||
|
||||
it("keeps one save in flight, only the newest update waits, and finish drops it", async () => {
|
||||
let release!: () => void;
|
||||
const saves: number[] = [];
|
||||
const instance = createToolCallProgressReporter({
|
||||
companyId: "c", runId: "r", issueId: null, agentId: null, invocationId: "i", toolName: "t",
|
||||
publish: () => undefined,
|
||||
save: (progress) => { saves.push(progress.progress); return new Promise<void>((resolve) => { release = resolve; }); },
|
||||
});
|
||||
instance.report({ progress: 1 });
|
||||
// The database is slow: three more save intervals pass while the first write runs.
|
||||
for (let step = 2; step <= 4; step++) {
|
||||
vi.advanceTimersByTime(TOOL_CALL_PROGRESS_SAVE_INTERVAL_MS);
|
||||
instance.report({ progress: step });
|
||||
}
|
||||
vi.advanceTimersByTime(TOOL_CALL_PROGRESS_SAVE_INTERVAL_MS);
|
||||
expect(saves).toEqual([1]);
|
||||
release();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(saves).toEqual([1, 4]);
|
||||
instance.report({ progress: 5 });
|
||||
vi.advanceTimersByTime(TOOL_CALL_PROGRESS_SAVE_INTERVAL_MS);
|
||||
instance.finish();
|
||||
release();
|
||||
await vi.advanceTimersByTimeAsync(TOOL_CALL_PROGRESS_SAVE_INTERVAL_MS * 3);
|
||||
expect(saves).toEqual([1, 4]);
|
||||
});
|
||||
|
||||
it("names the tool the way native runners name it, so their rows can find the call", () => {
|
||||
const instance = createToolCallProgressReporter({
|
||||
companyId: "c", runId: "r", issueId: null, agentId: null, invocationId: "i",
|
||||
toolName: "mcp.kv-demo-1a2b3c4d:slow-with-progress",
|
||||
publish: (event) => { names.push(event.payload.nativeToolName); },
|
||||
});
|
||||
const names: unknown[] = [];
|
||||
instance.report({ progress: 1 });
|
||||
expect(names).toEqual(["app_mcp_kv_demo_1a2b3c4d_slow_with_progress_889fb9a8d98e"]);
|
||||
});
|
||||
|
||||
it("gives each call its own progress token", () => {
|
||||
expect(reporter().instance.token).not.toBe(reporter().instance.token);
|
||||
});
|
||||
});
|
||||
@@ -3297,7 +3297,7 @@ describeEmbeddedPostgres("tool gateway service", () => {
|
||||
const calls = provider.mock.calls.map(([, init]) => JSON.parse(String(init.body)))
|
||||
.filter((payload) => payload.method === "tools/call");
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0].params).toEqual({ name: "search_messages", arguments: parameters });
|
||||
expect(calls[0].params).toEqual({ name: "search_messages", arguments: parameters, _meta: { progressToken: expect.stringMatching(/^paperclip-progress-/) } });
|
||||
});
|
||||
|
||||
it("explains Google Workspace preview enrollment when a tool call is denied", async () => {
|
||||
|
||||
@@ -6,6 +6,9 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import express from "express";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import type { LiveEvent } from "@paperclipai/shared";
|
||||
import { subscribeCompanyLiveEvents } from "../services/live-events.js";
|
||||
import { assignedToolName as nativeAssignedToolName } from "../services/native-runtime/assigned-mcp-tools.js";
|
||||
import request from "supertest";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
@@ -3584,6 +3587,7 @@ rl.on("line", (line) => {
|
||||
"kv_get",
|
||||
"kv_list",
|
||||
"kv_set",
|
||||
"slow_with_progress",
|
||||
]);
|
||||
|
||||
await allowAllToolsForAgent(db, company.id, agent.id);
|
||||
@@ -3618,6 +3622,61 @@ rl.on("line", (line) => {
|
||||
}
|
||||
});
|
||||
|
||||
it("shows a run's viewers the provider's progress for a long call, saves it on the call, and returns the same result", async () => {
|
||||
const company = await createCompany(db);
|
||||
const other = await createCompany(db);
|
||||
const agent = await createAgent(db, company.id);
|
||||
const { issue, run } = await createIssueAndRun(db, company.id, agent.id);
|
||||
const kvDemo: KvDemoHttpServer = createKvDemoHttpServer();
|
||||
const port = await kvDemo.listen(0, "127.0.0.1");
|
||||
const events: LiveEvent[] = [];
|
||||
const otherEvents: LiveEvent[] = [];
|
||||
const stop = subscribeCompanyLiveEvents(company.id, (event) => { events.push(event); });
|
||||
const stopOther = subscribeCompanyLiveEvents(other.id, (event) => { otherEvents.push(event); });
|
||||
try {
|
||||
const access = toolAccessService(db);
|
||||
const connection = await access.createConnection(company.id, {
|
||||
name: "KV demo progress fixture", connectionPurpose: "tool", transport: "mcp_remote", authKind: "none",
|
||||
ownership: "customer", connectionKind: "managed",
|
||||
config: { url: `http://127.0.0.1:${port}/mcp` }, transportConfig: { url: `http://127.0.0.1:${port}/mcp` },
|
||||
credentialSecretRefs: [], enabled: true, status: "active",
|
||||
});
|
||||
await access.refreshCatalog(connection.id, { actorType: "user", actorId: "board" });
|
||||
await allowAllToolsForAgent(db, company.id, agent.id);
|
||||
const gateway = createTestToolGatewayService(db);
|
||||
const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id, issueId: issue.id });
|
||||
const slowTool = (await gateway.listToolsForSession(session.token))
|
||||
.find((tool) => tool.upstreamToolName === "slow_with_progress");
|
||||
expect(slowTool).toBeTruthy();
|
||||
|
||||
const result = await gateway.executeTool({
|
||||
sessionToken: session.token,
|
||||
tool: slowTool!.name,
|
||||
parameters: { steps: 6, stepMs: 200 },
|
||||
});
|
||||
expect(result).toMatchObject({ status: "completed", result: { data: { isError: false, transport: "mcp_http" } } });
|
||||
|
||||
const progress = events.filter((event) => event.type === "heartbeat.run.tool_progress");
|
||||
// Throttled: six provider updates over ~1.2s, a handful of events, the last one marks the end.
|
||||
expect(progress.length).toBeGreaterThanOrEqual(3);
|
||||
expect(progress.length).toBeLessThanOrEqual(7);
|
||||
expect(progress.every((event) => event.companyId === company.id && event.payload.runId === run.id
|
||||
&& event.payload.issueId === issue.id && event.payload.toolName === slowTool!.name
|
||||
&& event.payload.nativeToolName === nativeAssignedToolName(slowTool!.name))).toBe(true);
|
||||
expect(progress[0]!.payload).toMatchObject({ progress: 1, total: 6, message: "Finished step 1 of 6", done: false });
|
||||
expect(progress.at(-1)!.payload).toMatchObject({ done: true });
|
||||
expect(otherEvents.filter((event) => event.type === "heartbeat.run.tool_progress")).toEqual([]);
|
||||
const [invocation] = await db.select().from(toolInvocations)
|
||||
.where(eq(toolInvocations.id, String(progress[0]!.payload.invocationId)));
|
||||
expect(invocation).toMatchObject({ companyId: company.id, runId: run.id, status: "succeeded" });
|
||||
expect(invocation!.progress).toMatchObject({ total: 6 });
|
||||
} finally {
|
||||
stop();
|
||||
stopOther();
|
||||
await kvDemo.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("expires legacy managed-connector approvals before provider dispatch", async () => {
|
||||
const company = await createCompany(db);
|
||||
const agent = await createAgent(db, company.id);
|
||||
|
||||
@@ -303,3 +303,15 @@ it("keeps a read set at 249 ms and replaces it at 250 ms", async () => {
|
||||
f.delivery.dispose();
|
||||
} finally { clock.mockRestore(); }
|
||||
});
|
||||
it("sends tool call progress only to clients watching that run", async () => {
|
||||
const f = fixture(); f.subscribe(["run-1"]);
|
||||
const progress = (id: number, runId: string): LiveEvent => ({ id, companyId: "company", type: "heartbeat.run.tool_progress",
|
||||
createdAt: "2026-11-13T00:00:00Z", payload: { runId, agentId: "agent", invocationId: `call-${id}`, progress: id, total: 10, message: "Exporting" } });
|
||||
f.delivery.enqueue(progress(1, "run-1")); f.delivery.enqueue(progress(2, "run-2")); await settle();
|
||||
const delivered = f.frames.filter(frame => frame.type === "heartbeat.run.tool_progress");
|
||||
expect(delivered.map(frame => frame.payload.runId)).toEqual(["run-1"]);
|
||||
// Another run's progress carries no content to this client.
|
||||
expect(JSON.stringify(f.frames)).not.toContain("call-2");
|
||||
expect(f.decorate).not.toHaveBeenCalled();
|
||||
f.delivery.dispose();
|
||||
});
|
||||
@@ -16,7 +16,10 @@ export function sharedDeliveryRead<T>(reads: LiveDeliveryReads | undefined, key:
|
||||
pending.catch(() => { if (reads.get(key) === pending) reads.delete(key); });
|
||||
return pending;
|
||||
}
|
||||
const transcript = (event: LiveEvent) => event.type === "heartbeat.run.event" || event.type === "heartbeat.run.log";
|
||||
// Per-run streams: sent only to clients that asked for the run. Tool progress
|
||||
// follows its run's transcript, since only an open transcript shows it.
|
||||
const transcript = (event: LiveEvent) => event.type === "heartbeat.run.event" || event.type === "heartbeat.run.log"
|
||||
|| event.type === "heartbeat.run.tool_progress";
|
||||
const runId = (event: LiveEvent) => typeof event.payload.runId === "string" ? event.payload.runId : null;
|
||||
interface Socket {
|
||||
readyState: number;
|
||||
|
||||
@@ -315,7 +315,7 @@ export function setupLiveEventsWebSocketServer(
|
||||
: payload.entityType === "issue" && typeof payload.entityId === "string" ? payload.entityId : null;
|
||||
const runId = typeof payload.runId === "string" ? payload.runId
|
||||
: payload.entityType === "heartbeat_run" && typeof payload.entityId === "string" ? payload.entityId : null;
|
||||
if (event.type === "heartbeat.run.event" || event.type === "heartbeat.run.log") {
|
||||
if (event.type === "heartbeat.run.event" || event.type === "heartbeat.run.log" || event.type === "heartbeat.run.tool_progress") {
|
||||
const allowed = await sharedDeliveryRead(reads, "transcript-scope", async () => (await access.decide({
|
||||
actor: context!.actor, action: "company_scope:read",
|
||||
resource: { type: "company", companyId: event.companyId } })).allowed);
|
||||
|
||||
@@ -15,6 +15,7 @@ import { assertBoard, getAccessibleResource } from "./authz.js";
|
||||
import { connectionRequestUserId } from "./connection-management-authz.js";
|
||||
import { authorizationService } from "../services/authorization.js";
|
||||
import { mcpAppViewsService, toMcpAppViewSummary } from "../services/mcp-app-views.js";
|
||||
import { listToolCallProgress } from "../services/tool-call-progress.js";
|
||||
import { ToolGatewayHttpError, type ToolGatewayService } from "../services/tool-gateway.js";
|
||||
|
||||
const uuidSchema = z.string().uuid();
|
||||
@@ -34,7 +35,7 @@ export function mcpAppsRoutes(db: Db, toolGateway: McpAppsGateway) {
|
||||
const router = Router();
|
||||
const views = mcpAppViewsService(db);
|
||||
|
||||
router.use("/issues/:issueId/mcp-app-views", async (req, res, next) => {
|
||||
const readableTask = async (req: Request, res: Response, next: () => void) => {
|
||||
assertBoard(req);
|
||||
if (!uuidSchema.safeParse(req.params.issueId).success) {
|
||||
res.status(404).json({ error: "Task not found" });
|
||||
@@ -57,7 +58,9 @@ export function mcpAppsRoutes(db: Db, toolGateway: McpAppsGateway) {
|
||||
res.locals.mcpAppIssue = issue;
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
next();
|
||||
});
|
||||
};
|
||||
router.use("/issues/:issueId/mcp-app-views", readableTask);
|
||||
router.use("/issues/:issueId/tool-call-progress", readableTask);
|
||||
|
||||
async function viewFor(req: Request, res: Response) {
|
||||
const issue = res.locals.mcpAppIssue as { id: string; companyId: string };
|
||||
@@ -162,6 +165,12 @@ export function mcpAppsRoutes(db: Db, toolGateway: McpAppsGateway) {
|
||||
res.status(201).json({ commentId: comment.id });
|
||||
});
|
||||
|
||||
// The latest progress of the task's running app tool calls (and recently finished ones, as done), for a reload mid-call.
|
||||
router.get("/issues/:issueId/tool-call-progress", async (_req, res) => {
|
||||
const issue = res.locals.mcpAppIssue as { id: string; companyId: string };
|
||||
res.json(await listToolCallProgress(db, issue.companyId, issue.id));
|
||||
});
|
||||
|
||||
router.get("/issues/:issueId/mcp-app-views", async (req, res) => {
|
||||
const issue = res.locals.mcpAppIssue as { id: string; companyId: string };
|
||||
res.json(await views.listForIssue(issue.companyId, issue.id));
|
||||
|
||||
@@ -1447,6 +1447,7 @@ const browserUseOperations = [
|
||||
// MCP Apps views in the task chat. Board only; reads follow task read access.
|
||||
const mcpAppsOperations = [
|
||||
["get", "/api/issues/{issueId}/mcp-app-views", "List a task's MCP Apps views", undefined],
|
||||
["get", "/api/issues/{issueId}/tool-call-progress", "Read the latest progress of a task's running app tool calls", undefined],
|
||||
["get", "/api/issues/{issueId}/mcp-app-views/{viewId}", "Read an MCP Apps view with its document", undefined],
|
||||
["post", "/api/issues/{issueId}/mcp-app-views/{viewId}/tool-calls", "Call a tool from an MCP Apps view", mcpAppToolCallSchema],
|
||||
["put", "/api/issues/{issueId}/mcp-app-views/{viewId}/model-context", "Store an MCP Apps view's context for the task's next run", mcpAppModelContextUpdateSchema],
|
||||
|
||||
@@ -209,11 +209,13 @@ export type McpJsonRpcRequest = { id?: string | number; method: string; params?:
|
||||
export function mcpHttpRequestInit(
|
||||
headers: Record<string, string> | undefined,
|
||||
message: McpJsonRpcRequest,
|
||||
options: { toolInputSchema?: unknown; declareTasks?: boolean; elicitationForm?: boolean } = {},
|
||||
options: { toolInputSchema?: unknown; declareTasks?: boolean; elicitationForm?: boolean; progressToken?: string } = {},
|
||||
): { method: "POST"; headers: Record<string, string>; body: string } {
|
||||
const requestHeaders = mcpHttpRequestHeaders(headers);
|
||||
const protocolVersion = mcpProtocolVersionOf(headers);
|
||||
let params = message.params ?? {};
|
||||
// Asks the server to stream `notifications/progress` for this request.
|
||||
if (options.progressToken) params = { ...params, _meta: { ...record(params._meta), progressToken: options.progressToken } };
|
||||
if (isModernMcpProtocolVersion(protocolVersion)) {
|
||||
params = {
|
||||
...params,
|
||||
@@ -666,6 +668,15 @@ export function parseMcpHttpResponseBody(bodyText: string, contentType: string |
|
||||
throw new SyntaxError("MCP SSE response contained no data events");
|
||||
}
|
||||
|
||||
/** A `notifications/progress` for this request's token, or null for any other message. */
|
||||
export function mcpProgressNotificationOf(message: unknown, progressToken: string | undefined): { progress: unknown; total: unknown; message: unknown } | null {
|
||||
const payload = record(message);
|
||||
if (!progressToken || !payload || payload.method !== "notifications/progress" || "id" in payload) return null;
|
||||
const params = record(payload.params);
|
||||
if (!params || params.progressToken !== progressToken) return null;
|
||||
return { progress: params.progress, total: params.total, message: params.message };
|
||||
}
|
||||
|
||||
export type McpHttpResponseProgress = {
|
||||
bytesReceived: number;
|
||||
chunksReceived: number;
|
||||
@@ -683,6 +694,15 @@ export async function readMcpHttpResponse(
|
||||
maxBytes?: number;
|
||||
onRequest?: (message: Record<string, unknown>) => Promise<void>;
|
||||
onProgress?: (progress: McpHttpResponseProgress) => void;
|
||||
/**
|
||||
* Bound an SSE stream per message instead of in total, so handled
|
||||
* notifications (such as progress) do not use up the result's limit. Only
|
||||
* for callers with an overall deadline: a stream of small notifications
|
||||
* could otherwise never end.
|
||||
*/
|
||||
limitPerMessage?: boolean;
|
||||
/** Notifications sent on this request's stream before its result. Must not block. */
|
||||
onNotification?: (message: Record<string, unknown>) => void;
|
||||
} = {},
|
||||
): Promise<unknown> {
|
||||
const progress: McpHttpResponseProgress = { bytesReceived: 0, chunksReceived: 0, eventsReceived: 0, matchedResponse: false, ended: false };
|
||||
@@ -714,6 +734,10 @@ export async function readMcpHttpResponse(
|
||||
return record;
|
||||
}
|
||||
if ("method" in record && "id" in record) await options.onRequest?.(record);
|
||||
else if ("method" in record) {
|
||||
// A notification observer never fails or delays the call.
|
||||
try { options.onNotification?.(record); } catch { /* ignored */ }
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
const event = async (value: string) => {
|
||||
@@ -729,17 +753,22 @@ export async function readMcpHttpResponse(
|
||||
progress.bytesReceived = bytes;
|
||||
if (value) progress.chunksReceived += 1;
|
||||
progress.ended = done;
|
||||
if (bytes > maxBytes) throw new McpHttpResponseError("too_large", "MCP response exceeded the size limit");
|
||||
// A JSON body is one message. An SSE stream is bounded in total unless the
|
||||
// caller asks for a per-message bound (see limitPerMessage).
|
||||
const perMessage = isStream && options.limitPerMessage === true;
|
||||
if (!perMessage && bytes > maxBytes) throw new McpHttpResponseError("too_large", "MCP response exceeded the size limit");
|
||||
buffer += decoder.decode(value, { stream: !done });
|
||||
if (isStream) {
|
||||
// Normalize CRLF after concatenating chunks, including split CR/LF pairs.
|
||||
buffer = buffer.replace(/\r\n/g, "\n");
|
||||
let boundary: number;
|
||||
while ((boundary = buffer.indexOf("\n\n")) >= 0) {
|
||||
if (perMessage && Buffer.byteLength(buffer.slice(0, boundary), "utf8") > maxBytes) throw new McpHttpResponseError("too_large", "MCP response exceeded the size limit");
|
||||
const result = await event(buffer.slice(0, boundary));
|
||||
buffer = buffer.slice(boundary + 2);
|
||||
if (result !== undefined) return result;
|
||||
}
|
||||
if (perMessage && Buffer.byteLength(buffer, "utf8") > maxBytes) throw new McpHttpResponseError("too_large", "MCP response exceeded the size limit");
|
||||
}
|
||||
if (done) break;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, desc, eq, gte, isNotNull, isNull } from "drizzle-orm";
|
||||
import { toolInvocations, type Db } from "@paperclipai/db";
|
||||
import {
|
||||
normalizeToolCallProgress,
|
||||
type LiveEventType,
|
||||
type ToolCallProgress,
|
||||
type ToolCallProgressSnapshot,
|
||||
} from "@paperclipai/shared";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { publishLiveEvent } from "./live-events.js";
|
||||
import { assignedToolName } from "./native-runtime/assigned-mcp-tools.js";
|
||||
|
||||
/**
|
||||
* Live progress for a connected-app tool call that an agent run made.
|
||||
*
|
||||
* The provider streams MCP `notifications/progress` on the call's response.
|
||||
* Each update is published to the run's viewers at most every
|
||||
* PUBLISH_INTERVAL_MS (the latest one wins) and saved on the invocation at
|
||||
* most every SAVE_INTERVAL_MS, so a reload mid-call shows the latest state.
|
||||
* Nothing here is awaited by the call: the result is never delayed.
|
||||
*/
|
||||
export const TOOL_CALL_PROGRESS_PUBLISH_INTERVAL_MS = 250;
|
||||
export const TOOL_CALL_PROGRESS_SAVE_INTERVAL_MS = 1_000;
|
||||
export const TOOL_CALL_PROGRESS_EVENT: LiveEventType = "heartbeat.run.tool_progress";
|
||||
/** Progress older than this is not shown after a reload (the call is long gone). */
|
||||
const SNAPSHOT_MAX_AGE_MS = 24 * 60 * 60_000;
|
||||
|
||||
export interface ToolCallProgressReporter {
|
||||
/** Sent as the request's `_meta.progressToken`. */
|
||||
readonly token: string;
|
||||
/** Records a provider update. Never throws, never blocks. */
|
||||
report(update: { progress: unknown; total?: unknown; message?: unknown }): void;
|
||||
/** The call ended: stop timers and tell viewers to drop the progress. */
|
||||
finish(): void;
|
||||
}
|
||||
|
||||
type Publish = (input: { companyId: string; type: LiveEventType; payload: Record<string, unknown> }) => void;
|
||||
type Save = (progress: ToolCallProgress) => Promise<void>;
|
||||
|
||||
/** Leading-edge throttle that keeps only the latest value for its trailing run. */
|
||||
function latestThrottle<T>(intervalMs: number, run: (value: T) => void) {
|
||||
let lastAt = -Infinity;
|
||||
let pending: { value: T } | null = null;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
const flush = () => {
|
||||
timer = null;
|
||||
if (!pending) return;
|
||||
const { value } = pending;
|
||||
pending = null;
|
||||
lastAt = Date.now();
|
||||
run(value);
|
||||
};
|
||||
return {
|
||||
push(value: T) {
|
||||
pending = { value };
|
||||
if (timer) return;
|
||||
const wait = lastAt + intervalMs - Date.now();
|
||||
if (wait <= 0) flush();
|
||||
else { timer = setTimeout(flush, wait); timer.unref?.(); }
|
||||
},
|
||||
cancel() {
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = null;
|
||||
pending = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createToolCallProgressReporter(input: {
|
||||
companyId: string;
|
||||
runId: string;
|
||||
issueId: string | null;
|
||||
agentId: string | null;
|
||||
invocationId: string;
|
||||
toolName: string;
|
||||
startedAt?: Date;
|
||||
publish?: Publish;
|
||||
save?: Save;
|
||||
}): ToolCallProgressReporter {
|
||||
const publish: Publish = input.publish ?? ((event) => { publishLiveEvent(event); });
|
||||
const startedAt = (input.startedAt ?? new Date()).toISOString();
|
||||
const token = `paperclip-progress-${randomUUID()}`;
|
||||
let finished = false;
|
||||
let last: ToolCallProgress | null = null;
|
||||
const snapshot = (progress: ToolCallProgress, done: boolean): ToolCallProgressSnapshot => ({
|
||||
...progress, invocationId: input.invocationId, runId: input.runId, toolName: input.toolName,
|
||||
nativeToolName: assignedToolName(input.toolName), startedAt, done,
|
||||
});
|
||||
const send = (value: ToolCallProgressSnapshot) => {
|
||||
try {
|
||||
publish({
|
||||
companyId: input.companyId,
|
||||
type: TOOL_CALL_PROGRESS_EVENT,
|
||||
payload: { ...value, issueId: input.issueId, agentId: input.agentId },
|
||||
});
|
||||
} catch (err) {
|
||||
logger.debug({ err, invocationId: input.invocationId }, "tool call progress publish failed");
|
||||
}
|
||||
};
|
||||
const live = latestThrottle<ToolCallProgress>(TOOL_CALL_PROGRESS_PUBLISH_INTERVAL_MS, (progress) => send(snapshot(progress, false)));
|
||||
// At most one save in flight; while it runs only the newest update waits.
|
||||
let saving = false;
|
||||
let queuedSave: ToolCallProgress | null = null;
|
||||
const save = (progress: ToolCallProgress) => {
|
||||
if (!input.save || finished) return;
|
||||
if (saving) { queuedSave = progress; return; }
|
||||
saving = true;
|
||||
input.save(progress)
|
||||
.catch((err) => logger.debug({ err, invocationId: input.invocationId }, "tool call progress save failed"))
|
||||
.finally(() => {
|
||||
saving = false;
|
||||
const next = queuedSave;
|
||||
queuedSave = null;
|
||||
if (next) save(next);
|
||||
});
|
||||
};
|
||||
const saved = latestThrottle<ToolCallProgress>(TOOL_CALL_PROGRESS_SAVE_INTERVAL_MS, save);
|
||||
return {
|
||||
token,
|
||||
report(update) {
|
||||
if (finished) return;
|
||||
const progress = normalizeToolCallProgress(update);
|
||||
// Progress must increase; a lower value is out of order and is dropped.
|
||||
if (!progress || (last && progress.progress < last.progress)) return;
|
||||
last = progress;
|
||||
live.push(progress);
|
||||
if (input.save) saved.push(progress);
|
||||
},
|
||||
finish() {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
live.cancel();
|
||||
saved.cancel();
|
||||
queuedSave = null;
|
||||
if (last) send(snapshot(last, true));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Saves a running call's latest progress. A finished call is never touched. */
|
||||
export function saveToolCallProgress(db: Db, companyId: string, invocationId: string): Save {
|
||||
return async (progress) => {
|
||||
await db.update(toolInvocations)
|
||||
.set({ progress })
|
||||
.where(and(eq(toolInvocations.id, invocationId), eq(toolInvocations.companyId, companyId), isNull(toolInvocations.completedAt)));
|
||||
};
|
||||
}
|
||||
|
||||
/** Finished calls are reported for this long, so a chat that missed their end learns it. */
|
||||
const FINISHED_REPORT_MS = 60 * 60_000;
|
||||
|
||||
/**
|
||||
* The latest progress of a task's running tool calls, for a reload mid-call,
|
||||
* plus its recently finished calls marked `done`. A chat drops a call only on
|
||||
* `done`: a running call may not have saved its first update yet.
|
||||
*/
|
||||
export async function listToolCallProgress(db: Db, companyId: string, issueId: string, now = new Date()): Promise<ToolCallProgressSnapshot[]> {
|
||||
const columns = {
|
||||
id: toolInvocations.id,
|
||||
runId: toolInvocations.runId,
|
||||
toolName: toolInvocations.toolName,
|
||||
progress: toolInvocations.progress,
|
||||
startedAt: toolInvocations.startedAt,
|
||||
createdAt: toolInvocations.createdAt,
|
||||
completedAt: toolInvocations.completedAt,
|
||||
};
|
||||
const task = and(eq(toolInvocations.companyId, companyId), eq(toolInvocations.issueId, issueId), isNotNull(toolInvocations.runId));
|
||||
const [running, finished] = await Promise.all([
|
||||
db.select(columns).from(toolInvocations).where(and(task,
|
||||
isNull(toolInvocations.completedAt),
|
||||
isNotNull(toolInvocations.progress),
|
||||
gte(toolInvocations.createdAt, new Date(now.getTime() - SNAPSHOT_MAX_AGE_MS)),
|
||||
)).orderBy(desc(toolInvocations.createdAt)).limit(50),
|
||||
db.select(columns).from(toolInvocations).where(and(task,
|
||||
gte(toolInvocations.completedAt, new Date(now.getTime() - FINISHED_REPORT_MS)),
|
||||
)).orderBy(desc(toolInvocations.completedAt)).limit(50),
|
||||
]);
|
||||
return [...running, ...finished].flatMap((row) => {
|
||||
const done = row.completedAt !== null;
|
||||
const savedAt = row.progress ? Date.parse(String(row.progress.updatedAt)) : NaN;
|
||||
const at = done ? row.completedAt! : Number.isFinite(savedAt) ? new Date(savedAt) : now;
|
||||
const progress = normalizeToolCallProgress(row.progress ?? (done ? { progress: 0 } : {}), at);
|
||||
if (!progress || !row.runId) return [];
|
||||
return [{
|
||||
...progress,
|
||||
invocationId: row.id,
|
||||
runId: row.runId,
|
||||
toolName: row.toolName,
|
||||
nativeToolName: assignedToolName(row.toolName),
|
||||
startedAt: (row.startedAt ?? row.createdAt).toISOString(),
|
||||
done,
|
||||
}];
|
||||
});
|
||||
}
|
||||
@@ -203,7 +203,9 @@ import {
|
||||
type McpInputRequired,
|
||||
mcpHttpRequestHeaders,
|
||||
parseMcpHttpResponseBody,
|
||||
mcpProgressNotificationOf,
|
||||
} from "./mcp-http.js";
|
||||
import { createToolCallProgressReporter, saveToolCallProgress, type ToolCallProgressReporter } from "./tool-call-progress.js";
|
||||
import {
|
||||
buildElicitationQuestionSet,
|
||||
elicitationQuestionHash,
|
||||
@@ -5505,6 +5507,8 @@ export function createToolGatewayService(
|
||||
protocolMethod?: string;
|
||||
protocolParams?: Record<string, unknown>;
|
||||
timeoutMs: number;
|
||||
/** Receives the call's `notifications/progress`; its token is sent with tools/call. */
|
||||
progressReporter?: ToolCallProgressReporter | null;
|
||||
},
|
||||
/** One restart and one deadline are shared by every protocol recovery in a call. */
|
||||
recovery: { restarted: boolean; deadline: number } = { restarted: false, deadline: Date.now() + input.timeoutMs },
|
||||
@@ -5585,6 +5589,8 @@ export function createToolGatewayService(
|
||||
try {
|
||||
const message = JSON.parse(line) as Record<string, unknown>;
|
||||
const id = typeof message.id === "number" ? message.id : null;
|
||||
const progressUpdate = mcpProgressNotificationOf(message, input.progressReporter?.token);
|
||||
if (progressUpdate) input.progressReporter!.report(progressUpdate);
|
||||
if (id !== null && pending.has(id)) {
|
||||
const waiter = pending.get(id)!;
|
||||
pending.delete(id);
|
||||
@@ -5760,6 +5766,7 @@ export function createToolGatewayService(
|
||||
withMeta(protocolVersion, input.protocolParams ?? {
|
||||
name: input.entry?.toolName,
|
||||
arguments: input.parameters ?? {},
|
||||
...(input.progressReporter ? { _meta: { progressToken: input.progressReporter.token } } : {}),
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
@@ -7816,6 +7823,7 @@ export function createToolGatewayService(
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), ms);
|
||||
timer.unref?.();
|
||||
const progressReporter = toolCallProgressReporterFor(session, tool, invocationId);
|
||||
// The cached MCP session this call used, so a failure resets only this
|
||||
// identity's session and leaves other agents on the connection alone.
|
||||
let mcpSession: { scope: string; headers: Record<string, string>; sessionId: string } | undefined;
|
||||
@@ -8026,6 +8034,7 @@ export function createToolGatewayService(
|
||||
toolInputSchema: entry.inputSchema ?? undefined,
|
||||
// Paperclip can wait on a task here, durably (see waitForMcpTask).
|
||||
declareTasks: tasksOn,
|
||||
progressToken: progressReporter?.token,
|
||||
// A person can answer the app's form questions in the task chat.
|
||||
elicitationForm: Boolean(elicitationCall),
|
||||
}),
|
||||
@@ -8245,7 +8254,13 @@ export function createToolGatewayService(
|
||||
const body = response.ok
|
||||
? JSON.stringify(await readMcpHttpResponse(response, callRequestId, {
|
||||
maxBytes: MAX_REMOTE_MCP_RESPONSE_BYTES,
|
||||
// The call has a deadline (controller), so progress may outlast the total limit.
|
||||
limitPerMessage: true,
|
||||
onProgress: (progress) => { execution.stream = progress; },
|
||||
onNotification: (message) => {
|
||||
const update = mcpProgressNotificationOf(message, progressReporter?.token);
|
||||
if (update) progressReporter!.report(update);
|
||||
},
|
||||
onRequest: async (message) => {
|
||||
const pending = extractRemoteMcpPending(message);
|
||||
if (pending) {
|
||||
@@ -8508,15 +8523,31 @@ export function createToolGatewayService(
|
||||
);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
progressReporter?.finish();
|
||||
}
|
||||
}
|
||||
|
||||
/** Progress is shown to the run's viewers, so only a call made by a run reports it. */
|
||||
function toolCallProgressReporterFor(session: ToolGatewaySession, tool: ToolGatewayDescriptor, invocationId: string | undefined) {
|
||||
if (!session.runId || !invocationId) return null;
|
||||
return createToolCallProgressReporter({
|
||||
companyId: session.companyId,
|
||||
runId: session.runId,
|
||||
issueId: session.issueId,
|
||||
agentId: session.agentId,
|
||||
invocationId,
|
||||
toolName: tool.name,
|
||||
save: saveToolCallProgress(db, session.companyId, invocationId),
|
||||
});
|
||||
}
|
||||
|
||||
async function executeLocalStdioTool(
|
||||
session: ToolGatewaySession,
|
||||
tool: ToolGatewayDescriptor,
|
||||
parameters: unknown,
|
||||
ms: number,
|
||||
useProviderDefaultTimeout = false,
|
||||
invocationId?: string,
|
||||
): Promise<RemoteHttpExecutionResult> {
|
||||
const { entry, connection } = await resolveConnectedLocalStdioTool(
|
||||
session,
|
||||
@@ -8530,8 +8561,10 @@ export function createToolGatewayService(
|
||||
template,
|
||||
grant,
|
||||
);
|
||||
const invoke = () => callLocalStdioMcp({ connection, entry, template, env, parameters,
|
||||
timeoutMs: useProviderDefaultTimeout && template.templateId === "paperclip.cognee-cloud" ? 60_000 : ms });
|
||||
const progressReporter = template.templateId === "paperclip.cognee-cloud" ? null : toolCallProgressReporterFor(session, tool, invocationId);
|
||||
const invoke = () => callLocalStdioMcp({ connection, entry, template, env, parameters, progressReporter,
|
||||
timeoutMs: useProviderDefaultTimeout && template.templateId === "paperclip.cognee-cloud" ? 60_000 : ms })
|
||||
.finally(() => progressReporter?.finish());
|
||||
// Cognee is a bundled HTTP client. Provider failures are tool failures, not
|
||||
// crashed local processes, and must never consume slots or restart budgets.
|
||||
const result = template.templateId === "paperclip.cognee-cloud"
|
||||
@@ -9579,6 +9612,7 @@ export function createToolGatewayService(
|
||||
args.parameters,
|
||||
executionTimeoutMs,
|
||||
args.timeoutMs === undefined,
|
||||
args.invocationId,
|
||||
)
|
||||
: null;
|
||||
if (!connectedMcpExecution) {
|
||||
@@ -10456,6 +10490,8 @@ export function createToolGatewayService(
|
||||
tool,
|
||||
parameters,
|
||||
executionTimeoutMs,
|
||||
false,
|
||||
invocation.id,
|
||||
)
|
||||
: null;
|
||||
const result = connectedMcpExecution
|
||||
@@ -13432,6 +13468,7 @@ export function createToolGatewayService(
|
||||
effectiveParameters,
|
||||
executionTimeoutMs,
|
||||
input.timeoutMs === undefined,
|
||||
invocationId,
|
||||
)
|
||||
: null;
|
||||
const result = recoveredGitHubPublication ?? (connectedMcpExecution
|
||||
|
||||
Reference in new issue
Block a user