Artifact read tools: nexus_list_artifacts and nexus_get_artifact #175

Closed
opened 2026-09-17 17:33:34 +02:00 by lz · 0 comments
Owner

The structural gap in this milestone. Depends on #174 (the tool contract). Scope: nexus:read, both tools.

Why this exists

The loop on a phone is:

  1. "is anything waiting on me?" → #155 plans this
  2. "what does it want?" → nothing, planned or shipped
  3. "here's my answer" → #158 plans this

We are building 1 and 3 and skipping 2, which is the step that makes the other two worth anything. As it stands the operator gets a notification and must open the web UI to act on it — precisely the thing the milestone exists to avoid.

ArtifactDTO already exists ({ id, session_id, path, label, kind, source, created_at, updated_at, comment_counts }), agents already register plans, reports and screenshots through notify-artifact, and no tool exposes any of it. comment_counts already distinguishes an artifact awaiting review from one already handled.

Design record: .agent/docs/mcp-tool-surface.md finding 5; plan docs/superpowers/plans/2026-09-17-mcp-tool-surface.md "PR B".

The contract to build on

#174 shipped it, and AGENTS.md fact #40 states it. A new tool is a file under nexus/src/lib/server/mcp/tools/, and:

  • name is typed `nexus_${string}` — the prefix is a compile error to omit.
  • annotations requires all four hints explicitly (readOnlyHint, destructiveHint, idempotentHint, openWorldHint). Both tools here are readOnly: true, destructive: false, idempotent: true, openWorld: false.
  • outputSchema is mandatory, and run returns the payload typed against it.
  • Anything that lists spreads PAGE_INPUT / pageOutputFields from paging.ts.
  • Nothing under tools/ may import registry.ts — the cycle would be a ReferenceError under Rollup and silently undefined under esbuild (fact #31).

Add McpArtifactSchema / mcpArtifact to projection.ts beside the other two. ArtifactDTO carries nothing host-shaped so it is close to identity — keep the projection anyway, and use it to say on the wire that path is relative to the session's worktree, which reads as an absolute-ish path to a model otherwise.


Task 1 — nexus_list_artifacts(session?, limit, offset)

Make listArtifacts' session filter optional (nexus/src/lib/server/artifacts/service.ts:100), exactly as #174 did for listSessions:

export async function listArtifacts(
  deps: ArtifactsServiceDeps,
  sessionId?: string
): Promise<ArtifactDTO[]> {
  let q = deps.db.selectFrom('artifacts').selectAll();
  if (sessionId !== undefined) q = q.where('session_id', '=', sessionId);
  const rows = await q.orderBy('created_at', 'desc').execute();
  return Promise.all(rows.map((r) => rowToDTO(deps.db, r)));
}

The if has to stay an if. Written as .where('session_id', '=', sessionId!) behind a conditional expression, an undefined bound parameter matches nothing in SQLite, so the fleet-wide listing comes back empty with no error and nothing logged. Seed two sessions with one artifact each and assert the fleet case is non-empty — with one session, "the fleet" and "this session" agree and a dropped where passes both.

Add listArtifacts: (session?: string) => Promise<unknown[]> to ToolDeps, wire it in deps.ts, and extend deps.test.ts's "binds each tool dependency to its service" with both the named and the omitted case — asserted on the ARGUMENT, since listArtifacts(deps, undefined) and listArtifacts(deps, 'undefined') are indistinguishable from the result.

Description should name what comment_counts means: open is feedback the operator has written but not submitted, submitted has been sent back to the agent.

Task 2 — nexus_get_artifact(artifact)

The only tool in either PR that reads a file out of a worker container, so the only one with a real failure surface.

Keep SvelteKit's error() inside the dep

resolveWorkerFs throws an HttpError, which is not an Error. Reaching the SDK's error instanceof Error ? error.message : String(error) it surfaces as {"message":"worker container not found"} — a JSON blob where an actionable sentence belongs. Convert at the boundary:

export type ReadArtifactResult =
  | { ok: true; artifact: ArtifactDTO; text: string; truncated: boolean; size: number }
  | { ok: false; reason: string };

In deps.ts, roughly:

readArtifact: async (artifactId) => {
  const artifact = await getArtifact(artifactsServiceDeps(), artifactId);
  if (!artifact) return { ok: false, reason: 'no artifact with that id' };
  const sess = await getSession(db, artifact.session_id);
  if (!sess) return { ok: false, reason: 'the session that owns it is gone' };
  if (artifact.kind === 'image' || artifact.kind === 'video') {
    return { ok: false, reason: `this artifact is ${artifact.kind}; open it in the Nexus web UI` };
  }
  try {
    const svc = await resolveWorkerFs(docker, sess.worker_id);
    const base = sess.worktree_name === WORKSPACE_WINDOW
      ? '/workspace'
      : `${WORKTREES_ROOT}/${sess.worktree_name}`;
    const r = await svc.readFile(base, artifact.path, { maxBytes: MCP_TEXT_MAX });
    const text = Buffer.from(r.contentBase64, 'base64').toString('utf8');
    return { ok: true, artifact, text, truncated: r.size > MCP_TEXT_MAX, size: r.size };
  } catch (err) {
    return { ok: false, reason: describeReadFailure(err) };
  }
}

describeReadFailure maps VolumeFsError codes (NOT_FOUND → "the file is no longer in the worktree", TOO_LARGE → "too large to read through MCP") and an HttpError's status (404 → "the workspace container is gone", 503 → "the workspace is not running — start it first"), falling back to a generic sentence plus a logger.warn carrying the real error. Log it: without that the sentence is all anyone ever sees.

MCP_TEXT_MAX is a module constant, not max_file_bytes

The two exist for different consumers: 256 KiB is a sane editor limit and roughly 64k tokens of a model's context. Start at 64 KiB and say why in a comment. Report the full size alongside truncated: true, never the truncated length — a caller has to be able to tell how much it is missing.

The tool

outputSchema: z.object({
  artifact: McpArtifactSchema,
  content: z.string(),
  truncated: z.boolean(),
  size: z.number().int()
}),
run: async (args, deps) => {
  const r = await deps.readArtifact(args.artifact);
  if (!r.ok) throw new Error(r.reason);
  return { artifact: mcpArtifact(r.artifact), content: r.text, truncated: r.truncated, size: r.size };
}

Throwing is correct, and worth knowing why: the registry's wrapper logs and rethrows, the SDK turns a rejecting executor into isError: true content on a 200 — the right wire answer for "this call failed", distinct from a protocol error — and an isError result skips output validation, so the refusal does not have to satisfy the schema.

Tests, each proven able to fail

  1. A text artifact round-trips its content.
  2. Truncation sets truncated: true and reports the full size.
  3. An image artifact refuses by kind without touching the worker fs — assert the fs dep was never called, or a large screenshot is read into memory to be thrown away.
  4. An HttpError from resolveWorkerFs becomes a sentence naming the workspace state, and the body never contains {"message".
  5. A VolumeFsError NOT_FOUND becomes a sentence, and the underlying error reaches logger.warn.
  6. An unknown artifact id refuses without querying the worker.
  7. The fleet-wide listing spans sessions (see the if/where trap above).

Add the new guards to the mutation gate. Watch specifically for one that cannot fail: the "refuses by kind" test passes trivially if the fs dep is a stub that returns something — assert the call count.

nexus/src/lib/server/oauth/consent.ts:18 reads "See workspaces, sessions, and what needs your attention". Artifact contents are agent output the operator has not seen described. Change to something like "See workspaces, sessions, what needs your attention, and what agents have written".

State the caveat explicitly: scopes are coarse, so every already-issued nexus:read token gains artifact reading the moment this deploys, including the one authorized on 2026-09-17. The copy fixes what the next operator sees, not what the current grant agreed to. The remedy — revoking a grant — is #171 §1 and does not exist yet.

Live verification

Register an artifact in a real worker with notify-artifact, then read it back through MCP end to end:

  1. nexus_list_artifacts with no session spans sessions.
  2. nexus_get_artifact returns the bytes the file actually holds — diff against cat, do not eyeball a prefix.
  3. A registered screenshot refuses by kind with a sentence.
  4. A stopped workspace's artifact refuses naming the workspace state, not with a JSON blob.

Drive both protocol legs. A modern tools/call needs Mcp-Name as well as Mcp-Method; a legacy POST needs Accept: application/json, text/event-stream and frames its success as SSE.

Deliberately out of scope

  • Inlining images as MCP image content blocks. Genuinely useful — a screenshot is often exactly what "what does it want?" means — but the media cap is 10 MiB, whose base64 is ~13 MB of context. It needs a second, much smaller cap and a refusal path above it: a design decision, not a line of code. Text closes the loop for plans, reports and diffs today.
  • Submitting artifact feedback through MCP. The write half of the same loop, and it belongs with #158: both are "say something back to an agent", and #158 already establishes the inbox socket as the delivery mechanism that survives a second principal.
  • Anything under /api/config-explorer/*, /api/tokens, /api/connections, /api/settings/environment. A stolen MCP token must not become control-plane compromise; TOKEN_ROUTES' exclusions are the precedent.

Done when

Claude can ask what needs attention, read the plan or report the agent produced, and do it from a phone — with a refusal for every failure mode that names the thing to do about it, and a mutation gate proving each new guard bites.

The structural gap in this milestone. Depends on #174 (the tool contract). Scope: `nexus:read`, both tools. ## Why this exists The loop on a phone is: 1. *"is anything waiting on me?"* → #155 plans this 2. *"what does it want?"* → **nothing, planned or shipped** 3. *"here's my answer"* → #158 plans this We are building 1 and 3 and skipping 2, which is the step that makes the other two worth anything. As it stands the operator gets a notification and must open the web UI to act on it — precisely the thing the milestone exists to avoid. `ArtifactDTO` already exists (`{ id, session_id, path, label, kind, source, created_at, updated_at, comment_counts }`), agents already register plans, reports and screenshots through `notify-artifact`, and no tool exposes any of it. `comment_counts` already distinguishes an artifact awaiting review from one already handled. Design record: `.agent/docs/mcp-tool-surface.md` finding 5; plan `docs/superpowers/plans/2026-09-17-mcp-tool-surface.md` "PR B". ## The contract to build on #174 shipped it, and AGENTS.md fact #40 states it. A new tool is a file under `nexus/src/lib/server/mcp/tools/`, and: - `name` is typed ``` `nexus_${string}` ``` — the prefix is a compile error to omit. - `annotations` requires all four hints explicitly (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`). Both tools here are `readOnly: true, destructive: false, idempotent: true, openWorld: false`. - `outputSchema` is mandatory, and `run` returns the payload typed against it. - Anything that lists spreads `PAGE_INPUT` / `pageOutputFields` from `paging.ts`. - Nothing under `tools/` may import `registry.ts` — the cycle would be a `ReferenceError` under Rollup and silently `undefined` under esbuild (fact #31). Add `McpArtifactSchema` / `mcpArtifact` to `projection.ts` beside the other two. `ArtifactDTO` carries nothing host-shaped so it is close to identity — keep the projection anyway, and use it to say on the wire that `path` is **relative to the session's worktree**, which reads as an absolute-ish path to a model otherwise. --- ## Task 1 — `nexus_list_artifacts(session?, limit, offset)` **Make `listArtifacts`' session filter optional** (`nexus/src/lib/server/artifacts/service.ts:100`), exactly as #174 did for `listSessions`: ```ts export async function listArtifacts( deps: ArtifactsServiceDeps, sessionId?: string ): Promise<ArtifactDTO[]> { let q = deps.db.selectFrom('artifacts').selectAll(); if (sessionId !== undefined) q = q.where('session_id', '=', sessionId); const rows = await q.orderBy('created_at', 'desc').execute(); return Promise.all(rows.map((r) => rowToDTO(deps.db, r))); } ``` **The `if` has to stay an `if`.** Written as `.where('session_id', '=', sessionId!)` behind a conditional expression, an undefined bound parameter matches **nothing** in SQLite, so the fleet-wide listing comes back empty with no error and nothing logged. Seed two sessions with one artifact each and assert the fleet case is non-empty — with one session, "the fleet" and "this session" agree and a dropped `where` passes both. Add `listArtifacts: (session?: string) => Promise<unknown[]>` to `ToolDeps`, wire it in `deps.ts`, and extend `deps.test.ts`'s "binds each tool dependency to its service" with **both** the named and the omitted case — asserted on the ARGUMENT, since `listArtifacts(deps, undefined)` and `listArtifacts(deps, 'undefined')` are indistinguishable from the result. Description should name what `comment_counts` means: `open` is feedback the operator has written but not submitted, `submitted` has been sent back to the agent. ## Task 2 — `nexus_get_artifact(artifact)` The only tool in either PR that reads a file out of a worker container, so the only one with a real failure surface. ### Keep SvelteKit's `error()` inside the dep **`resolveWorkerFs` throws an `HttpError`, which is not an `Error`.** Reaching the SDK's `error instanceof Error ? error.message : String(error)` it surfaces as `{"message":"worker container not found"}` — a JSON blob where an actionable sentence belongs. Convert at the boundary: ```ts export type ReadArtifactResult = | { ok: true; artifact: ArtifactDTO; text: string; truncated: boolean; size: number } | { ok: false; reason: string }; ``` In `deps.ts`, roughly: ```ts readArtifact: async (artifactId) => { const artifact = await getArtifact(artifactsServiceDeps(), artifactId); if (!artifact) return { ok: false, reason: 'no artifact with that id' }; const sess = await getSession(db, artifact.session_id); if (!sess) return { ok: false, reason: 'the session that owns it is gone' }; if (artifact.kind === 'image' || artifact.kind === 'video') { return { ok: false, reason: `this artifact is ${artifact.kind}; open it in the Nexus web UI` }; } try { const svc = await resolveWorkerFs(docker, sess.worker_id); const base = sess.worktree_name === WORKSPACE_WINDOW ? '/workspace' : `${WORKTREES_ROOT}/${sess.worktree_name}`; const r = await svc.readFile(base, artifact.path, { maxBytes: MCP_TEXT_MAX }); const text = Buffer.from(r.contentBase64, 'base64').toString('utf8'); return { ok: true, artifact, text, truncated: r.size > MCP_TEXT_MAX, size: r.size }; } catch (err) { return { ok: false, reason: describeReadFailure(err) }; } } ``` `describeReadFailure` maps `VolumeFsError` codes (`NOT_FOUND` → "the file is no longer in the worktree", `TOO_LARGE` → "too large to read through MCP") and an `HttpError`'s status (404 → "the workspace container is gone", 503 → "the workspace is not running — start it first"), falling back to a generic sentence **plus a `logger.warn` carrying the real error**. Log it: without that the sentence is all anyone ever sees. ### `MCP_TEXT_MAX` is a module constant, not `max_file_bytes` The two exist for different consumers: 256 KiB is a sane editor limit and roughly 64k tokens of a model's context. Start at **64 KiB** and say why in a comment. Report the **full** `size` alongside `truncated: true`, never the truncated length — a caller has to be able to tell how much it is missing. ### The tool ```ts outputSchema: z.object({ artifact: McpArtifactSchema, content: z.string(), truncated: z.boolean(), size: z.number().int() }), run: async (args, deps) => { const r = await deps.readArtifact(args.artifact); if (!r.ok) throw new Error(r.reason); return { artifact: mcpArtifact(r.artifact), content: r.text, truncated: r.truncated, size: r.size }; } ``` **Throwing is correct**, and worth knowing why: the registry's wrapper logs and rethrows, the SDK turns a rejecting executor into `isError: true` content on a 200 — the right wire answer for "this call failed", distinct from a protocol error — and an `isError` result **skips output validation**, so the refusal does not have to satisfy the schema. ## Tests, each proven able to fail 1. A text artifact round-trips its content. 2. Truncation sets `truncated: true` and reports the full `size`. 3. An image artifact refuses by kind **without touching the worker fs** — assert the fs dep was never called, or a large screenshot is read into memory to be thrown away. 4. An `HttpError` from `resolveWorkerFs` becomes a sentence naming the workspace state, and the body **never** contains `{"message"`. 5. A `VolumeFsError` `NOT_FOUND` becomes a sentence, and the underlying error reaches `logger.warn`. 6. An unknown artifact id refuses without querying the worker. 7. The fleet-wide listing spans sessions (see the `if`/`where` trap above). Add the new guards to the mutation gate. Watch specifically for one that cannot fail: the "refuses by kind" test passes trivially if the fs dep is a stub that returns something — assert the call count. ## Consent copy, and a caveat that belongs in the PR body `nexus/src/lib/server/oauth/consent.ts:18` reads *"See workspaces, sessions, and what needs your attention"*. Artifact contents are agent output the operator has not seen described. Change to something like *"See workspaces, sessions, what needs your attention, and what agents have written"*. **State the caveat explicitly:** scopes are coarse, so **every already-issued `nexus:read` token gains artifact reading the moment this deploys**, including the one authorized on 2026-09-17. The copy fixes what the *next* operator sees, not what the current grant agreed to. The remedy — revoking a grant — is #171 §1 and does not exist yet. ## Live verification Register an artifact in a real worker with `notify-artifact`, then read it back through MCP end to end: 1. `nexus_list_artifacts` with no `session` spans sessions. 2. `nexus_get_artifact` returns the bytes the file actually holds — diff against `cat`, do not eyeball a prefix. 3. A registered screenshot refuses by kind with a sentence. 4. A stopped workspace's artifact refuses naming the workspace state, not with a JSON blob. Drive **both** protocol legs. A modern `tools/call` needs `Mcp-Name` as well as `Mcp-Method`; a legacy POST needs `Accept: application/json, text/event-stream` and frames its success as SSE. ## Deliberately out of scope - **Inlining images as MCP `image` content blocks.** Genuinely useful — a screenshot is often exactly what *"what does it want?"* means — but the media cap is 10 MiB, whose base64 is ~13 MB of context. It needs a second, much smaller cap and a refusal path above it: a design decision, not a line of code. Text closes the loop for plans, reports and diffs today. - **Submitting artifact feedback through MCP.** The write half of the same loop, and it belongs with #158: both are "say something back to an agent", and #158 already establishes the inbox socket as the delivery mechanism that survives a second principal. - **Anything under `/api/config-explorer/*`, `/api/tokens`, `/api/connections`, `/api/settings/environment`.** A stolen MCP token must not become control-plane compromise; `TOKEN_ROUTES`' exclusions are the precedent. ## Done when Claude can ask what needs attention, read the plan or report the agent produced, and do it from a phone — with a refusal for every failure mode that names the thing to do about it, and a mutation gate proving each new guard bites.
lz added this to the MCP support (#140) milestone 2026-09-17 17:33:34 +02:00
lz closed this issue 2026-09-23 18:46:28 +02:00
Sign in to join this conversation.
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
lz/agent-nexus#175
No description provided.