@50arms/platform-mcp 0.1.562 → 0.1.564

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -46,14 +46,14 @@ All exposed as `mcp__platform__<name>` once wired through the workspace `mcp.tem
46
46
 
47
47
  | Tool | Purpose |
48
48
  |---|---|
49
- | `50arms_api` | `{method, path, query?, body?}` — calls any dashboard route the caller's credential may reach (card/plan CRUD, comments, dependencies, problems/solutions, quality gates, retro, triage, transitions, …). Returns `{ok, status, body}`; `body` carries the route's own response, or its structured error verbatim when `ok:false`. While this session is plan-connected, the dashboard's own reminders for it (today: `plan_list.listener_unattached`, attached by the server to `GET /api/plan-sessions/me/listener-health` when the event listener is unattached past the startup grace, DX-3997) are relayed into the body's `reminders[]`; the MCP carries no reminder text or state of its own and re-reads at most every 30s. |
49
+ | `50arms_api` | `{method, path, query?, body?}` — calls any dashboard route the caller's credential may reach (card/plan CRUD, comments, dependencies, problems/solutions, quality gates, retro, triage, transitions, …). Returns `{ok, status, body}`; `body` carries the route's own response, or its structured error verbatim when `ok:false`. While this session is plan-connected, the dashboard's own reminders for it (the behavior policies the server attaches to `GET /api/plan-sessions/me/listener-health`'s events: the listener-down warning when the event listener is unattached past the startup grace, DX-3997, and the owed-comments reminder, DX-7801) are relayed into the body's `reminders[]`, each `{key, text}` keyed by the policy's ref; the MCP carries no reminder text or state of its own and re-reads at most every 30s. |
50
50
  | `50arms_api_list` | No args. Lists the routes this caller's credential may reach as `{routes: ["METHOD /path"]}` (one bare string per route, exactly what `50arms_api_spec` takes; a dispatch's own callbacks are in it) — call this first when you don't know the route for what you need to do. |
51
51
  | `50arms_api_spec` | `{endpoints}` (comma-joined `METHOD /path` list, required, min 1). Returns the exact OpenAPI contract for those routes — call this when you know the route but not its exact request/response shape. |
52
52
  | `attach_file` | `{target?, card_id, path, replaces?, primary?, filename?, content_type?}` — the server reads the LOCAL file at `path` (absolute, `/tmp/a.png` or `C:\x\a.png`) and uploads it, so its bytes never pass through the agent's context. `replaces: <attachment id>` swaps that attachment's file in place (`PUT /api/issues/:id/attachments/:aid`: same id, name and cover flag) instead of adding one; `primary: true` makes it the card's single cover, atomically with the write. Reply: `{issue: <compact row>, attachment_id, url, thumbnail_url, is_primary}`. `target: "inline_image"` (DX-5241) instead uploads a local png/jpg/gif/webp/avif (25 MB, no SVG) to `POST /api/uploads/images` with no card, takes only `path`, and replies `{url, markdown}` for embedding in any markdown body such as a `POST /api/feedback` body. Shown to a key holding `cards.edit` (DX-4523); a dispatch profile still receives it only when its catalog selection names it (`slack-agent` and `work`, DX-4386, through `extraTools`). A screenshot of browser-visible work: first `primary: true`, then `replaces` at each milestone. |
53
53
  | `mini_app_publish` | `{target: {repo?, name}, dir, note, destination: {kind: "card_design", card_id, design_no | design_title + design_element}}` — builds a page with the repo's OWN mini app and publishes it as a revision of one of an existing card's designs, or as a new design on it (DX-5294, replacing `design_publish`; DX-4077, DX-5164, DX-5193). A card holds several designs: pass exactly one of `destination.design_no` (add a revision to that design, `POST /api/issues/<card>/designs/<no>/revisions`) or `destination.design_title` (start a new design, `POST /api/issues/<card>/designs`; the title is fixed for good), both-or-neither is refused before anything is built; `destination.design_element` (DX-5856) is required with `design_title` and refused with `design_no`: it names the one thing the design decides ("Indicator pill") and is sent as `element`, and the design joins that element's open design problem or opens one (a card has one open design problem per element); the answer carries `{card_id, design_no, revision_no, dashboard_url, local_html_path, screenshot}`. `target.name` names one of the repo's mini app targets, read from the dashboard (`GET /api/repos/<repo>`, `mini_app_targets`, edited in Settings > Board > General), never from a file; `target.repo` (a repo's name) defaults to the repo of the card's board (`GET /api/boards/<board>`) and names another repo's mini app (danxbot's own) when given. A target is `{name, command}`: a build `command` (an argument list, run in the repo root with NO shell: a bare program name, then a committed repo-relative script, then its own arguments). For each build the tool makes a fresh empty folder in the OS temp area (never inside the repo) and runs the command with the design folder's repo-relative path (forward slashes) and that output folder (absolute) appended as its LAST TWO arguments; the command writes `index.html`, one `.js` and one `.css` into it, the tool reads them and deletes the folder, so two builds never share a folder, nothing in the person's checkout is ever deleted, and no leftover output can exist. The command runs in a short-lived child process with a 5-minute limit, so the server never holds the design's checkout files open (DX-4727); once the process exits its pipes get 2 s to close, then the call stops waiting and a leftover child is killed on POSIX only (its process group; on Windows `taskkill /T` cannot reach an orphan whose parent has exited, so it may keep running); the command's own output comes back verbatim when it fails (only its last 1 MiB is kept, and the message says so when it was cut), and nothing is read or posted then. Refused before anything is built or posted, naming the target and field: a program with a path separator or whitespace, an unsafe script path (a `..` segment, a backslash, an absolute path or a drive letter), a `.cmd`/`.bat` shim on Windows (`npm`, `npx`, `yarn`, `pnpm`: name `node` and a committed script), a script that is not tracked by git or has changes against HEAD (the named script only, not what it imports), and a design folder that is tracked by git or not ignored by it. The page is written to `<tmpdir>/danx-design/<build-id>.html` before the upload, the revision carries `design_dir` (the folder, repo-relative) and the folder's text files as `source_files`, and a 1280x800 screenshot is taken when Playwright resolves from the repo or this server's cwd (`screenshot: "none: <reason>"` otherwise, never a failed publish). A new design may carry `problem_statement`, `problem_summary` and `problem_context` (DX-6000): the designer's own text for the element's design problem, REQUIRED by the server when the publish opens that problem (the card has no open design problem for that element: its first design, or the first after one was chosen) and refused when it adds a design to an open one; the tool passes them verbatim and judges nothing. `destination.card_id` is required and names an existing card (any but an Epic or Feature); the tool never creates a card, and a refused revision comes back verbatim with the `card_id`. Shown to a key holding `cards.edit`; opt-in, so a dispatch profile receives it only when its catalog selection names it (none does yet). |
54
54
  | `plugin_publish` | `{dir, plugin, note, name?}` — builds a card-type plugin project with its own `npm run build` in a short-lived child process, archives its source (`source.tar.gz`: git-tracked plus untracked-unignored files, else what the top-level `.gitignore` leaves, minus `node_modules`, `.git`, `dist`; never `.env*`; a lockfile is required) and uploads both as a new revision of the plugin `plugin` (created on the first publish), `POST /api/plugins/<id>/revisions` (DX-5237). The build, archive and upload are `@50arms/plugin-sdk/publish`, the code `danx-plugin publish` runs too. The answer carries `{plugin, plugin_id, revision_id, revision_no, approval_url, screenshot}`; `approval_url` is Settings > Plugins, where a team admin approves the revision. A 1280x800 screenshot of the plugin's own render is taken when Playwright resolves from the project or this server's cwd: a headless browser opens the dashboard's public `/plugin-preview` page, which draws the built plugin's `CardView` on the app's own runtime (React, `@50arms/ui`, the card kit) with a sample card, the build served from memory so nothing is uploaded first, and the capture waits until the page reports `ready` (`screenshot: "none: <reason>"` when there is no browser, the dashboard predates the page, or the plugin fails to render; never a failed publish). A refused upload comes back verbatim with the `step` refused. Shown to a key holding `plugins.publish`; opt-in like `mini_app_publish`. |
55
55
  | `docs_search` | `{source, query, limit?}` — searches a docs root with the shared `@50arms/docs` engine and answers `{query, results: [{id, type, title, summary, file, bytes, lines, look_in?}]}`, best first, **never a page body** (DX-5582). `source` is `{kind: "local"}` (this checkout's `docs/pages`, the server's cwd), `{kind: "dir", path}` (another docs root on this machine) or `{kind: "remote", repo}` (`repo` is the repo's name; a team repo's hosted docs, `GET /api/docs/<repo>/search`, `docs.view`, the repo must be on the caller's team's boards) or `{kind: "product"}` (50 Arms' own product docs, which every team reads, `GET /api/product-docs/search`; a repo can be named `danxbot` and is still an ordinary repo). A local or dir `file` is an absolute path; a remote `file` is the page's path inside that repo's docs. `bytes` and `lines` let the agent read the file whole or with offset/limit. A remote search validates the repo's docs strictly (422 when a page is invalid), while a local or dir search skips files it cannot read or parse and reports how many as `skipped_files` (DX-5597). A whitespace-only query is refused 400 for every source. Shown to a key holding `docs.view`; opt-in like `plugin_publish`. |
56
- | `docs_read` | `{source, id}` — answers `{id, path, bytes, lines}`: the page as a file on this machine, never its text. A local or dir page is read where it is (nothing copied); a remote page is fetched from `GET /api/docs/<repo>/pages/<id>` and written to `<tmp>/danx-docs/<repo>/<id>.md`, and a product page from `GET /api/product-docs/pages/<id>` to `<tmp>/danx-product-docs/<id>.md` (named by the requested id, written under a temp name and renamed into place), replaced on every call. The agent then reads it with its own file tools. An unknown id is refused with the nearest ids. Same gate and opt-in as `docs_search` (DX-5582). |
56
+ | `docs_read` | `{source, id}` — answers `{id, path, bytes, lines}`: the page as a file on this machine, never its text. A local or dir page is read where it is (nothing copied); a remote page is fetched from `GET /api/docs/<repo>/pages/<id>` and written to `<reply root>/danx-docs/<repo>/<id>.md`, and a product page from `GET /api/product-docs/pages/<id>` to `<reply root>/danx-product-docs/<id>.md` (named by the requested id, written under a temp name and renamed into place), replaced on every call. The agent then reads it with its own file tools. An unknown id is refused with the nearest ids. Same gate and opt-in as `docs_search` (DX-5582). |
57
57
  | `request_permission` | `{permissions, reason}` — asks a person to grant this key ONE MORE permission (see "Asking for one more permission" above). Answers at once with the approval URL and confirm code; the grant is picked up in the background. |
58
58
 
59
59
  There is no dedicated `resource_fields` tool (removed DX-3465 — it was a thin wrapper `50arms_api` already reaches with no agent-specific behavior earning it its own tool). What an opt-in field TREE may name for one resource (`{resource, description, always, hashes, fields, relations}`) is `50arms_api({method:"GET", path:"/api/resources/<resource>/fields"})` — install-global, no `board`; `resource: "issue"` is the root, and a relation's own `resource` in the response is what to call this again with, one level deeper.
@@ -12,17 +12,16 @@
12
12
  *
13
13
  * The ranking is one engine (`@50arms/docs` `search.ts`): in-process for local and dir, on the dashboard for remote and product. A local or dir
14
14
  * answer's `file` is an ABSOLUTE path, usable as it stands; a hosted answer's `file` is the page's path inside its docs, and
15
- * `docs_read` is what brings it to disk. A hosted page is written to `<tmp>/danx-docs/<repo>/<id>.md` (`<tmp>/danx-product-docs/<id>.md`), replaced on every read, so the
15
+ * `docs_read` is what brings it to disk. A hosted page is written to `<reply root>/danx-docs/<repo>/<id>.md` (`<reply root>/danx-product-docs/<id>.md`), replaced on every read, so the
16
16
  * agent never reads a stale copy and re-reads of one page share one path. The file is written under a temp name and renamed into place
17
17
  * (DX-5597), so a reader never sees half a page.
18
18
  */
19
19
  import { statSync } from "node:fs";
20
- import os from "node:os";
21
20
  import path from "node:path";
22
21
  import { z } from "zod";
23
22
  import { MAX_SEARCH_LIMIT, UnknownNodeIdError, loadLocalDocs, locateLocalPage, searchLocalDocs, } from "@50arms/docs/agent";
24
23
  import { repoNameArgSchema } from "./board-id.js";
25
- import { writeFileDurable } from "./durable-write.js";
24
+ import { writeReplyFile } from "./reply-files.js";
26
25
  /** The tools' shared `source` argument (one flat object so the schema stays plain: `path` goes with `dir`, `repo` with `remote`; `sourceProblem` enforces it). */
27
26
  export const docsSourceShape = z
28
27
  .object({
@@ -140,11 +139,10 @@ export async function docsRead(client, args, deps) {
140
139
  return fetched;
141
140
  const page = fetched.body;
142
141
  // DX-5597: the file is named by the id this call validated, never by a field of the answer, and lands whole: a temp name, then a rename.
143
- const tmp = deps.tmpDir ?? os.tmpdir();
142
+ // DX-8228: through `writeReplyFile`.
144
143
  const file = args.source.kind === "product"
145
- ? path.join(tmp, "danx-product-docs", `${args.id}.md`)
146
- : path.join(tmp, "danx-docs", args.source.repo, `${args.id}.md`);
147
- writeFileDurable(file, page.content);
144
+ ? writeReplyFile("danx-product-docs", [`${args.id}.md`], page.content, deps)
145
+ : writeReplyFile("danx-docs", [args.source.repo, `${args.id}.md`], page.content, deps);
148
146
  const body = {
149
147
  id: args.id,
150
148
  path: file,
package/dist/index.js CHANGED
@@ -107,6 +107,7 @@ import { miniAppRestore } from "./mini-app-restore.js";
107
107
  import { pluginPublish } from "./plugin-publish.js";
108
108
  import { docsRead, docsSearch, docsSourceShape } from "./docs-tools.js";
109
109
  import { spillRoleInstruction } from "./role-instruction-file.js";
110
+ import { removeStaleReplyFiles } from "./reply-files.js";
110
111
  import { DEFAULT_LIMIT, MAX_SEARCH_LIMIT } from "@50arms/docs/agent";
111
112
  import { boundedResultText } from "./result-limit.js";
112
113
  import { BEHAVIOR_SIGNOFFS_DESCRIPTION, behaviorSignoffsSchema, } from "./behavior-signoffs.js";
@@ -188,6 +189,8 @@ let sessionHostClaim;
188
189
  * argument, or the dashboard answers 400 (DX-4592: the client no longer refuses on its behalf). A value that is not a positive integer fails loud.
189
190
  */
190
191
  async function boot() {
192
+ // DX-8228: the one moment reply files older than their age limit are removed.
193
+ removeStaleReplyFiles(Date.now());
191
194
  const dashboardUrl = readEnvOrDie("DANXBOT_DASHBOARD_URL");
192
195
  const board = readBoardId();
193
196
  const session = readSessionConfig();
@@ -556,9 +559,14 @@ function jsonResult(value) {
556
559
  content: [{ type: "text", text: JSON.stringify(value) }],
557
560
  };
558
561
  }
559
- /** DX-4400 / DX-6117 — a dashboard route's result, its body delivered as a file when over `MCP_MAX_RESULT_CHARS`. */
560
- function boundedJsonResult(result) {
561
- return { content: [{ type: "text", text: boundedResultText(result) }] };
562
+ /**
563
+ * DX-4400 / DX-6117 — a dashboard route's result, its body delivered as a file when over `MCP_MAX_RESULT_CHARS`,
564
+ * or always as a file when the caller asked for one (`reply_to_file`, DX-8226).
565
+ */
566
+ function boundedJsonResult(result, opts) {
567
+ return {
568
+ content: [{ type: "text", text: boundedResultText(result, opts) }],
569
+ };
562
570
  }
563
571
  /** DX-4523 - every tool `strictTool` registered, by name: what `ToolSurface` switches. */
564
572
  const registeredTools = new Map();
@@ -682,6 +690,11 @@ renamedTool("50arms_api",
682
690
  .min(1)
683
691
  .optional()
684
692
  .describe("Absolute path of an image file (png, jpg, webp, svg; max 1 MB) sent as the raw body instead of `body`."),
693
+ // DX-8226 — a caller that must not carry the reply inline (a plugin hook; Claude Code refuses a tool result over its limit): the answer is always the file form.
694
+ reply_to_file: z
695
+ .boolean()
696
+ .optional()
697
+ .describe("Write the reply's JSON body to a local file and answer only where it is, whatever its size: the tool result is `{ok, status, reply_file: {path, bytes, chars, sha256, instruction}}`."),
685
698
  // DX-7947 (AC 76323): the agent's sign-offs of the behavior rules a write needs; where they go (the body, or the header of a `body_file` write) is `placeSignoffs`'s.
686
699
  behavior_rule_signoffs: behaviorSignoffsSchema
687
700
  .optional()
@@ -716,13 +729,16 @@ renamedTool("50arms_api",
716
729
  // DX-6089: `GET /api/plan-sessions/me/role`'s role text lands in a local file; the reply names it.
717
730
  const spilled = spillRoleInstruction(result);
718
731
  // DX-6556: a manual pickup that connected the session is a connect, whatever tool carried it.
719
- if (isPickupConnect(spilled))
720
- return finishConnect(calledAs, spilled, false);
732
+ if (isPickupConnect(spilled)) {
733
+ // DX-8226 (82640, DEC-2598): the connect's answer reaches the caller through the same bounded path as every other `50arms_api` answer, with what the connect adds beside `body`.
734
+ const outcome = await finishConnect(calledAs, spilled, false);
735
+ return boundedJsonResult(outcome.kind === "connected" ? outcome.answer : outcome.result, { toFile: args.reply_to_file === true });
736
+ }
721
737
  // DX-7110: an answer that says 50 Arms is unreachable is not followed by a health read of it; either way the notices no relay carried ride on it.
722
738
  const answered = isUnreachableAnswer(spilled)
723
739
  ? spilled
724
740
  : await listenerReminder.apply(spilled);
725
- return boundedJsonResult(mergeReminders(answered, client.reachability.takePending()));
741
+ return boundedJsonResult(mergeReminders(answered, client.reachability.takePending()), { toFile: args.reply_to_file === true });
726
742
  });
727
743
  // ---------------- 50arms_api_list (DX-3465 A5, PLN-11 R-25) ----------------
728
744
  renamedTool("50arms_api_list",
@@ -1180,7 +1196,11 @@ async (args) => {
1180
1196
  if (result.status === 401 && access.dropKey(result)) {
1181
1197
  return accessReply(await access.ensureAccess(args.title, args.role), "the dashboard no longer accepted this session's key");
1182
1198
  }
1183
- return finishConnect("session_connect", result, args.disconnect === true);
1199
+ const outcome = await finishConnect("session_connect", result, args.disconnect === true);
1200
+ // R-25: `session_connect` answers inline and whole, never through the bounded path.
1201
+ if (outcome.kind === "blocked")
1202
+ return jsonResult(withAppVersion(outcome.result.body, outcome.result));
1203
+ return jsonResult(outcome.kind === "left" ? outcome.result : outcome.answer);
1184
1204
  });
1185
1205
  // DX-6735: started by each connect that holds an agent, and never awaited by it.
1186
1206
  const reportCheckoutDocsRoot = createCheckoutDocsRootReporter(() => client, process.cwd());
@@ -1196,27 +1216,31 @@ async function finishConnect(tool, result, disconnect) {
1196
1216
  if (!disconnect) {
1197
1217
  agentGate.record(result.body);
1198
1218
  if (agentGate.current() !== null)
1199
- return jsonResult(withAppVersion(result.body, result));
1219
+ return { kind: "blocked", result };
1200
1220
  void reportCheckoutDocsRoot();
1201
1221
  }
1202
1222
  if (disconnect) {
1203
1223
  removeSessionConnectionAfterLeave(result, config.session?.id);
1204
- return jsonResult(result);
1224
+ return { kind: "left", result };
1205
1225
  }
1206
1226
  const connection = access.connection();
1207
1227
  if (connection === null)
1208
1228
  throw new Error(`${tool}: no credential after a successful connect`);
1209
- return jsonResult({
1210
- ...result,
1211
- dashboard: connectedDashboard(),
1212
- ...recordSessionConnectionAfterConnect(result, {
1213
- sessionId: config.session?.id,
1214
- projectKey: projectKeyOf(process.cwd()),
1215
- dashboardUrl: connection.dashboardUrl,
1216
- source: connection.source,
1217
- fingerprint: connection.fingerprint,
1218
- }),
1219
- });
1229
+ return {
1230
+ kind: "connected",
1231
+ // DEC-2598: what the MCP adds to a connect's answer sits in the envelope beside `body`, as `app_version` does.
1232
+ answer: {
1233
+ ...result,
1234
+ dashboard: connectedDashboard(),
1235
+ ...recordSessionConnectionAfterConnect(result, {
1236
+ sessionId: config.session?.id,
1237
+ projectKey: projectKeyOf(process.cwd()),
1238
+ dashboardUrl: connection.dashboardUrl,
1239
+ source: connection.source,
1240
+ fingerprint: connection.fingerprint,
1241
+ }),
1242
+ },
1243
+ };
1220
1244
  }
1221
1245
  // ---------------- plan_events_wait (DX-4233) ----------------
1222
1246
  strictTool("plan_events_wait",
@@ -612,7 +612,7 @@ var readOwnManifest = () => JSON.parse(
612
612
  readFileSync(new URL("../../package.json", import.meta.url), "utf8")
613
613
  ).version;
614
614
  var TOOLKIT_VERSION = resolveToolkitVersion(
615
- false ? void 0 : "0.1.562",
615
+ false ? void 0 : "0.1.564",
616
616
  readOwnManifest
617
617
  );
618
618
  function envelope(now) {
@@ -0,0 +1,150 @@
1
+ /**
2
+ * DX-8228 - the one place this package saves a reply to a temporary file and hands the path back (`result-limit.ts`, `docs-tools.ts`,
3
+ * `role-instruction-file.ts`). The files hold whole reply bodies (card text, role texts, the behavior bundle), so each is readable only by the
4
+ * user that wrote it, and a stale one is removed when the server starts. The four folders keep the names DX-8226 and earlier wrote under, and sit
5
+ * under a root only this user owns (`replyRoot`), because the temporary folder of Linux is shared by every user and one user's 0700 folder there
6
+ * would stop the next user's server. On Windows the root is the temp folder itself, so the paths do not change and the files already there are
7
+ * swept. Elsewhere the files DX-8226 and earlier wrote sit in the old folders directly under the temp folder, outside the root: they stay until
8
+ * the system clears its temp folder (accepted: no code for an old layout). The writer and the sweep act on the root only through `verifiedRoot`,
9
+ * and the sweep never follows a link.
10
+ * The sweep runs only at server start, before this process has written any file, so it never removes a file this server handed back; a file
11
+ * another session of the same user handed back survives until it is older than `REPLY_FILE_MAX_AGE_MS`.
12
+ */
13
+ import { chmodSync, lstatSync, mkdirSync, readdirSync, unlinkSync, } from "node:fs";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import { writeFileDurable } from "./durable-write.js";
17
+ /** The folders, under the reply root, that reply files live in: `docs_read` writes `danx-docs/<repo>/<id>.md`, the others write flat files. */
18
+ export const REPLY_FOLDERS = [
19
+ "danx-api",
20
+ "danx-role",
21
+ "danx-docs",
22
+ "danx-product-docs",
23
+ ];
24
+ /**
25
+ * How old a reply file must be before the server's start removes it. A session reads a path it was handed within that session, and a
26
+ * session that outlives a week is rare; the files hold whole reply bodies, so they should not stay longer than that.
27
+ */
28
+ export const REPLY_FILE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
29
+ /** Owner-only: the folders the helper creates (rwx) and the files it writes (rw). */
30
+ const DIR_MODE = 0o700;
31
+ const FILE_MODE = 0o600;
32
+ /**
33
+ * The folder the four reply folders live in, and which only this user owns: the OS temporary folder where the platform has no user id
34
+ * (`process.getuid` is undefined on Windows, where that folder is already the user's own), else `<tmp>/danx-<uid>`. Never `os.userInfo()`,
35
+ * which throws for a user with no passwd entry.
36
+ */
37
+ export function replyRoot(tmpDir = os.tmpdir()) {
38
+ return process.getuid === undefined
39
+ ? tmpDir
40
+ : path.join(tmpDir, `danx-${process.getuid()}`);
41
+ }
42
+ /**
43
+ * The one place that decides whether the reply root can be trusted: a real folder (never a link) owned by this user, which only this user can then
44
+ * have put anything in. Where the root is the temp folder itself (no user id) there is nothing to check. `create` makes it at 0700 and sets
45
+ * 0700 on one that exists (the writer); without it a missing root answers `null` (the sweep: nothing to clean). A root that fails the check throws,
46
+ * naming it: a writer lets that fail its call, the sweep reports it and deletes nothing.
47
+ */
48
+ function verifiedRoot(tmpDir, create) {
49
+ const root = replyRoot(tmpDir);
50
+ if (root === tmpDir)
51
+ return root;
52
+ if (create)
53
+ mkdirSync(root, { recursive: true, mode: DIR_MODE });
54
+ let stat;
55
+ try {
56
+ stat = lstatSync(root);
57
+ }
58
+ catch (err) {
59
+ if (!create && err.code === "ENOENT")
60
+ return null;
61
+ throw err;
62
+ }
63
+ if (!stat.isDirectory() || stat.uid !== process.getuid?.())
64
+ throw new Error(`the reply folder ${root} exists and is not a real directory owned by this user (uid ${process.getuid?.()}): it is not used`);
65
+ if (create)
66
+ chmodSync(root, DIR_MODE);
67
+ return root;
68
+ }
69
+ /**
70
+ * Write `data` whole to `<root>/<folder>/<rest...>` (a temp name, then a rename) with owner-only permissions on the file and on every folder from
71
+ * `<folder>` down to it, and return the path. `rest` are the caller's already-validated plain names; the last is the file name.
72
+ */
73
+ export function writeReplyFile(folder, rest, data, deps = {}) {
74
+ const tmpDir = deps.tmpDir ?? os.tmpdir();
75
+ const root = verifiedRoot(tmpDir, true);
76
+ const top = path.join(root, folder);
77
+ const file = path.join(top, ...rest);
78
+ // A recursive mkdir gives every folder it creates this mode; each folder on the way is also set explicitly in case it already existed wider.
79
+ mkdirSync(path.dirname(file), { recursive: true, mode: DIR_MODE });
80
+ for (let dir = path.dirname(file);; dir = path.dirname(dir)) {
81
+ chmodSync(dir, DIR_MODE);
82
+ if (dir === top)
83
+ break;
84
+ }
85
+ writeFileDurable(file, data, { mode: FILE_MODE });
86
+ return file;
87
+ }
88
+ /**
89
+ * Remove every regular file this user owns under the `REPLY_FOLDERS` last modified more than `REPLY_FILE_MAX_AGE_MS` before `now`. Run once at
90
+ * server start, before this process writes anything: no timer, no background process. It never follows a link: a linked folder among the four,
91
+ * and any linked entry below them, is skipped. A missing folder is nothing to clean; a file another server removed first is skipped. Housekeeping
92
+ * nobody reads must never stop a server from starting, so a root that cannot be trusted, or a folder whose cleanup fails, is reported on stderr
93
+ * (its path and the error) and the rest go on; a write that fails still fails its own call.
94
+ */
95
+ export function removeStaleReplyFiles(now, deps = {}) {
96
+ const report = (dir, err) => console.error(`platform-mcp: could not clean the reply folder ${dir}: ${err instanceof Error ? err.message : String(err)}`);
97
+ let root;
98
+ try {
99
+ root = verifiedRoot(deps.tmpDir ?? os.tmpdir(), false);
100
+ }
101
+ catch (err) {
102
+ report(replyRoot(deps.tmpDir), err);
103
+ return;
104
+ }
105
+ if (root === null)
106
+ return;
107
+ for (const folder of REPLY_FOLDERS) {
108
+ const dir = path.join(root, folder);
109
+ try {
110
+ sweep(dir, now - REPLY_FILE_MAX_AGE_MS, true);
111
+ }
112
+ catch (err) {
113
+ report(dir, err);
114
+ }
115
+ }
116
+ }
117
+ /** `top` is one of the four folders: it is walked only if it is itself a real folder, never a link. */
118
+ function sweep(dir, cutoff, top) {
119
+ let entries;
120
+ try {
121
+ if (top && !lstatSync(dir).isDirectory())
122
+ return;
123
+ entries = readdirSync(dir, { withFileTypes: true });
124
+ }
125
+ catch (err) {
126
+ if (err.code === "ENOENT")
127
+ return;
128
+ throw err;
129
+ }
130
+ for (const entry of entries) {
131
+ const entryPath = path.join(dir, entry.name);
132
+ // A Dirent reports a link as neither a directory nor a file, so a linked entry falls through both branches.
133
+ if (entry.isDirectory()) {
134
+ sweep(entryPath, cutoff, false);
135
+ continue;
136
+ }
137
+ if (!entry.isFile())
138
+ continue;
139
+ try {
140
+ const stat = lstatSync(entryPath);
141
+ const own = process.getuid === undefined || stat.uid === process.getuid();
142
+ if (stat.isFile() && own && stat.mtimeMs < cutoff)
143
+ unlinkSync(entryPath);
144
+ }
145
+ catch (err) {
146
+ if (err.code !== "ENOENT")
147
+ throw err;
148
+ }
149
+ }
150
+ }
@@ -12,7 +12,7 @@
12
12
  * permission) and only on a person's session (`tool-access.ts`).
13
13
  *
14
14
  * THE ANSWER (the plugin's hooks module reads it through `$.mcp.call`):
15
- * - `{notice: "<text>"}` - say this to the agent (the registry's `plan_restart.waiting_events` text; this module carries no
15
+ * - `{notice: "<text>"}` - say this to the agent (the rendered `reminders[]` texts of the restart-notice read, the locked restart behavior policy's, DX-7801; this module carries no
16
16
  * wording of its own).
17
17
  * - `{notice: null}` - nothing to say: no earlier session of this project connected a plan, or the plan is archived or
18
18
  * deleted, or the record is stale, or every predecessor is still live. The plugin stays silent, as PLN-11 R-10 requires of
@@ -112,8 +112,6 @@ export const RESTART_NOTICE_DEADLINE_MS = 8_000;
112
112
  * (it is not a predecessor), so the newest candidate is often not the one.
113
113
  */
114
114
  export const RESTART_NOTICE_MAX_CANDIDATES = 10;
115
- /** The registry row whose text is the notice (`src/issues/reminders/seed.yaml`). */
116
- export const RESTART_NOTICE_REMINDER_KEY = "plan_restart.waiting_events";
117
115
  /** One authenticated GET (`sendSessionRequest` above, so its bound and its failure names are the same), answering the notice text or `null`. */
118
116
  export async function fetchRestartNotice(target, deps) {
119
117
  // The bearer is the predecessor's; the session id header names the ASKING session.
@@ -140,15 +138,16 @@ export async function fetchRestartNotice(target, deps) {
140
138
  return { ok: false, reason: "bad_response" };
141
139
  if (body.restart === null)
142
140
  return { ok: true, text: null };
143
- // A notice exists, so the registry row MUST have answered with its text: a
144
- // missing one is a server/registry fault, reported rather than papered over.
141
+ // DX-7801 (AC 72317): the notice is every text the reply's `reminders[]` carries, in order (the dashboard's restart-notice policy and anything a team attached to the same event); no key is read. A notice exists, so the
142
+ // dashboard MUST have answered with text: none is a server fault, reported rather than papered over.
145
143
  const reminders = Array.isArray(body.reminders)
146
144
  ? body.reminders
147
145
  : [];
148
- const notice = reminders.find((r) => r.key === RESTART_NOTICE_REMINDER_KEY);
149
- if (typeof notice?.text !== "string" || notice.text === "")
146
+ const texts = reminders.map((r) => r.text);
147
+ if (texts.length === 0 ||
148
+ !texts.every((t) => typeof t === "string" && t !== ""))
150
149
  return { ok: false, reason: "bad_response" };
151
- return { ok: true, text: notice.text };
150
+ return { ok: true, text: texts.join("\n\n") };
152
151
  }
153
152
  /** The tool's arguments (`index.ts` registers exactly this shape). */
154
153
  export const RESTART_NOTICE_ARGS = {
@@ -1,38 +1,39 @@
1
1
  import { createHash } from "node:crypto";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import { writeFileDurable } from "./durable-write.js";
2
+ import { writeReplyFile } from "./reply-files.js";
5
3
  /**
6
4
  * DX-4400 — the most characters one `50arms_api`, `50arms_api_spec` or `50arms_api_list` result may carry
7
- * back to the agent. Every character is context the agent pays for on every later call, and Claude Code itself
8
- * saves a larger result to a file with only a short preview, after the cost is paid. A deliberate, narrow
9
- * exception to PLAN-11 rule R-25 (verbatim forwarding): `session_connect` and the lifecycle tools never pass here.
5
+ * back to the agent. Every character is context the agent pays for on every later call. DX-8226: measured, Claude
6
+ * Code refused a 63,012-character result (EV-192), so this cap sits below that size and a reply above it is written
7
+ * to a file instead. Claude Code's documented default for an MCP tool result (25,000 tokens) is not verified in
8
+ * this repo's code. Hex-heavy JSON runs near 2 characters per token, which is why the cap is in characters.
9
+ * A deliberate, narrow exception to PLAN-11 rule R-25 (verbatim forwarding): `session_connect` and the lifecycle
10
+ * tools never pass here.
10
11
  */
11
- export const MCP_MAX_RESULT_CHARS = 100_000;
12
+ export const MCP_MAX_RESULT_CHARS = 40_000;
12
13
  const FILE_INSTRUCTION = "The reply was over the inline limit, so its body is this file, whole: read it with Read (in parts with offset and limit when it is long), or grep it.";
13
14
  /**
14
- * The text the agent receives for `result`: its compact JSON when that fits `MCP_MAX_RESULT_CHARS`, otherwise
15
- * `{ok, status, reply_file:{path, bytes, chars, instruction}}`, the body written whole to
16
- * `<tmp>/danx-api/<content hash>.json` (DX-6117, as `docs_read` and the role text do). Never truncates, never forwards a part. `ok`
17
- * and `status` stay so a write that already committed is still reported as committed.
15
+ * The text the agent receives for `result`: its compact JSON when that fits `MCP_MAX_RESULT_CHARS` and the caller
16
+ * did not ask for a file (`toFile`, DX-8226), otherwise the envelope with `reply_file:{path, bytes, chars, sha256, instruction}`
17
+ * in place of `body`: the body written whole to `<reply root>/danx-api/<first 16 hex of sha256>.json` (DX-6117, DX-8228: through `writeReplyFile`, as `docs_read` and
18
+ * the role text do). `sha256` is the full hex digest of the file's bytes. Never truncates, never forwards a part. Every other
19
+ * field of the envelope (`ok` and `status`, so a write that already committed is still reported as committed, `app_version`, and
20
+ * what the MCP adds beside `body` such as a connect's `dashboard`, DEC-2598) stays beside `reply_file`; the file holds only the route's reply.
18
21
  */
19
- export function boundedResultText(result, deps = {}) {
22
+ export function boundedResultText(result, options = {}, deps = {}) {
20
23
  const text = JSON.stringify(result);
21
- if (text.length <= MCP_MAX_RESULT_CHARS)
24
+ if (!options.toFile && text.length <= MCP_MAX_RESULT_CHARS)
22
25
  return text;
23
- const body = JSON.stringify(result.body);
24
- const file = path.join(deps.tmpDir ?? os.tmpdir(), "danx-api", `${createHash("sha256").update(body).digest("hex").slice(0, 16)}.json`);
25
- writeFileDurable(file, body);
26
+ const { body: replyBody, ...envelope } = result;
27
+ const body = JSON.stringify(replyBody);
28
+ const sha256 = createHash("sha256").update(body, "utf8").digest("hex");
29
+ const file = writeReplyFile("danx-api", [`${sha256.slice(0, 16)}.json`], body, deps);
26
30
  return JSON.stringify({
27
- ok: result.ok,
28
- status: result.status,
29
- ...(result.app_version === undefined
30
- ? {}
31
- : { app_version: result.app_version }),
31
+ ...envelope,
32
32
  reply_file: {
33
33
  path: file,
34
34
  bytes: Buffer.byteLength(body, "utf8"),
35
35
  chars: body.length,
36
+ sha256,
36
37
  instruction: FILE_INSTRUCTION,
37
38
  },
38
39
  });
@@ -2,15 +2,13 @@
2
2
  * DX-6089 - a session's role text reaches it as a local file, never inline. The dashboard answers `roleInstruction: {profile, text}` on
3
3
  * `session_connect` and `GET /api/plan-sessions/me/role`; the text runs to tens of KB, and a tool reply that large is
4
4
  * saved to a file by the client with only a short preview, which also hides every field after it (the briefing, the agent instruction, the
5
- * reminders). So this server writes the text to `<tmp>/danx-role/<profile>-<content hash>.md` and answers `{profile, path, bytes, instruction}`
5
+ * reminders). So this server writes the text to `<reply root>/danx-role/<profile>-<content hash>.md` and answers `{profile, path, bytes, instruction}`
6
6
  * in its place, leaving every other field inline, as `docs_read` does for a docs page (`docs-tools.ts`). The name carries the content hash, so a
7
7
  * changed text never overwrites a file a session is reading, and the file is written under a temp name and renamed into place, so a reader never
8
8
  * sees half of it.
9
9
  */
10
10
  import { createHash } from "node:crypto";
11
- import os from "node:os";
12
- import path from "node:path";
13
- import { writeFileDurable } from "./durable-write.js";
11
+ import { writeReplyFile } from "./reply-files.js";
14
12
  export const ROLE_FILE_INSTRUCTION = "Read this file in full now, with Read (in parts with offset and limit when it is long): it is your role's workflow, the procedure you work by.";
15
13
  // The profile names the file, so it must be a plain name: never a path a reply could steer. DX-7462: a card type's own profile is a team profile, whose name may hold `_` (`AGENT_NAME_SHAPE`).
16
14
  const PROFILE_NAME = /^[a-z][a-z0-9_-]*$/;
@@ -33,8 +31,9 @@ export function spillRoleInstruction(result, deps = {}) {
33
31
  typeof text !== "string") {
34
32
  throw new Error(`the dashboard answered a roleInstruction that is not {profile, text}: ${JSON.stringify(role).slice(0, 200)}`);
35
33
  }
36
- const file = path.join(deps.tmpDir ?? os.tmpdir(), "danx-role", `${profile}-${createHash("sha256").update(text).digest("hex").slice(0, 16)}.md`);
37
- writeFileDurable(file, text);
34
+ const file = writeReplyFile("danx-role", [
35
+ `${profile}-${createHash("sha256").update(text).digest("hex").slice(0, 16)}.md`,
36
+ ], text, deps);
38
37
  const spilled = {
39
38
  profile,
40
39
  path: file,
@@ -8,6 +8,7 @@ export const GET_ROUTE_BOARD_SCOPE = [
8
8
  ["/api/behavior-events", "refuse"],
9
9
  ["/api/behavior-events/:event/attachments", "refuse"],
10
10
  ["/api/behavior-events/bundle", "refuse"],
11
+ ["/api/behavior-events/requested-endpoints", "refuse"],
11
12
  ["/api/behavior-policies", "refuse"],
12
13
  ["/api/behavior-policies/:ref/comments", "refuse"],
13
14
  ["/api/behavior-policy-groups", "refuse"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@50arms/platform-mcp",
3
- "version": "0.1.562",
3
+ "version": "0.1.564",
4
4
  "description": "Stdio MCP server fronting the 50 Arms dashboard API for agents (operator sessions and dispatched workers alike): the generic 50arms_api/50arms_api_list/50arms_api_spec tools reach any route the caller's credential may call, plus dedicated agent-specific tools (session_connect, request_permission, attach_file, and 50arms_slack_reply) (DX-3465, PLN-11 R-25).",
5
5
  "license": "MIT",
6
6
  "type": "module",