@sleep2agi/commhub-server 0.9.0-preview.82 → 0.9.0-preview.83

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sleep2agi/commhub-server",
3
- "version": "0.9.0-preview.82",
3
+ "version": "0.9.0-preview.83",
4
4
  "description": "CommHub Server — AI Agent communication hub with MCP protocol, multi-network isolation, user auth, and MCP tools (17 collaboration-core + node/provider ops tools; authoritative list: docs-site/docs/api/mcp-tools.md).",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
@@ -475,4 +475,9 @@ export const RESTRICTED_MEMBER_TOOLS: ReadonlySet<string> = new Set([
475
475
  "requirements_checklist_toggle",
476
476
  "requirements_upsert_by_external_ref",
477
477
  "projects_list",
478
+ // 2026-10-02(app 任务页审计 M3):和 app「管理项目」/「动态」同一个 REST 处理,权限也同一套 —— 项目管理对仅相关任务的
479
+ // 成员和 viewer 一律 403;动态按任务可见性过滤,受限成员看不见的节点在里面隐去(listEvents 的 hiddenNodeFilter)。
480
+ "projects_create",
481
+ "projects_update",
482
+ "requirements_events",
478
483
  ]);
@@ -0,0 +1,162 @@
1
+ // MCP projects_create / projects_update / requirements_events(app 任务页审计 2026-10-02 M3:Agent 能做人能做的)。
2
+ // HTTP 集成测试(真实 Bun.serve,私有端口,临时库)。三个工具都走 app 用的同一套 REST 处理(handleRequirementsRequest),
3
+ // 所以这里不另抄一份权限规则:对每类调用者(网络 owner、全部任务成员、仅相关任务成员、viewer、节点令牌)都同时调
4
+ // MCP 和 REST,断言状态码 / 结果逐项一致。再钉住正向行为(建 / 改名 / 归档 / 取消归档、读流水、"#N")和工具出现在 tools/list 里。
5
+
6
+ import { describe, expect, test, beforeAll, afterAll } from "bun:test";
7
+ import { mkdtempSync, rmSync } from "fs";
8
+ import { join } from "path";
9
+ import { tmpdir } from "os";
10
+ import { register, createNetworkTokenForNode } from "./auth.js";
11
+ import { db } from "./db.js";
12
+
13
+ const DIR = mkdtempSync(join(tmpdir(), "anet-mcp-projects-events-"));
14
+ let BASE = "";
15
+ let hub: any = null;
16
+ const PW = "McpProjectsEventsPassw0rd!x";
17
+ let NET = "";
18
+ const U: Record<string, { token: string; id: string }> = {};
19
+
20
+ async function rest(token: string, method: string, path: string, body?: unknown) {
21
+ const res = await fetch(`${BASE}${path}`, { method, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
22
+ const text = await res.text();
23
+ let json: any = null;
24
+ try { json = JSON.parse(text); } catch {}
25
+ return { status: res.status, body: json };
26
+ }
27
+ async function rpc(token: string, method: string, params?: unknown): Promise<any> {
28
+ const res = await fetch(`${BASE}/mcp`, {
29
+ method: "POST",
30
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-03-26" },
31
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, ...(params === undefined ? {} : { params }) }),
32
+ });
33
+ const raw = await res.text();
34
+ const lines = raw.split("\n").filter(x => x.startsWith("data:"));
35
+ return lines.length ? JSON.parse(lines.at(-1)!.slice(5).trim()) : JSON.parse(raw);
36
+ }
37
+ async function mcp(token: string, name: string, args: Record<string, unknown>): Promise<any> {
38
+ const out = await rpc(token, "tools/call", { name, arguments: args });
39
+ return JSON.parse(out.result.content[0].text);
40
+ }
41
+ // MCP error bodies from the REST handler carry its status (requirementsCall). Anything else that isn't ok (e.g. a tool-level
42
+ // gate) is NOT a success — a body without `status` must never be read as the 2xx (that hid a gate in the first draft).
43
+ const mcpStatus = (r: any, okStatus: number) => (r?.ok === true || (r && r.ok === undefined && (r.project || r.events)) ? okStatus : typeof r?.status === "number" ? r.status : -1);
44
+
45
+ beforeAll(async () => {
46
+ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
47
+ process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
48
+ process.env.HOST = "127.0.0.1";
49
+ const a = register(`mpe_owner_${Date.now()}`, PW, undefined, "Owner");
50
+ expect(a.ok).toBe(true);
51
+ U.owner = { token: a.token!, id: a.user!.user_id };
52
+ NET = a.network_id!;
53
+ db.run("UPDATE users SET role = 'admin' WHERE user_id = ?1", [U.owner.id]);
54
+ const mod: any = await import("./server.js");
55
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
56
+ BASE = `http://127.0.0.1:${hub.port}`;
57
+ const mk = async (username: string, role: string) => {
58
+ expect((await rest(U.owner.token, "POST", "/api/admin/users", { username, password: PW, network_id: NET, role })).status).toBe(200);
59
+ const login = await rest("", "POST", "/api/auth/login", { username, password: PW });
60
+ expect(login.status).toBe(200);
61
+ return { token: login.body.token as string, id: login.body.user.user_id as string };
62
+ };
63
+ const stamp = Date.now();
64
+ U.member = await mk(`mpe_member_${stamp}`, "member");
65
+ U.scoped = await mk(`mpe_scoped_${stamp}`, "member");
66
+ U.viewer = await mk(`mpe_viewer_${stamp}`, "viewer");
67
+ db.run("UPDATE network_members SET task_access = 'all' WHERE network_id = ?1 AND user_id = ?2", [NET, U.member.id]);
68
+ expect((await rest(U.owner.token, "PUT", `/api/networks/${NET}/members/${U.scoped.id}/task-grants`, { task_access: "scoped", project_grants: [] })).status).toBe(200);
69
+ const node = createNetworkTokenForNode(U.owner.id, NET, "mpe-node", "node_mpe");
70
+ U.node = { token: node.token!, id: "node_mpe" };
71
+ }, 30_000);
72
+
73
+ afterAll(() => {
74
+ try { hub?.stop?.(true); } catch {}
75
+ try { rmSync(DIR, { recursive: true, force: true }); } catch {}
76
+ });
77
+
78
+ describe("discoverable", () => {
79
+ test("tools/list carries the three tools with descriptions", async () => {
80
+ const list = await rpc(U.owner.token, "tools/list");
81
+ const byName = new Map((list.result.tools as any[]).map(t => [t.name, t]));
82
+ for (const n of ["projects_create", "projects_update", "requirements_events"]) {
83
+ expect(byName.has(n)).toBe(true);
84
+ expect(String(byName.get(n).description).length).toBeGreaterThan(40);
85
+ }
86
+ expect(String(byName.get("projects_list").description)).toContain("projects_create");
87
+ });
88
+ });
89
+
90
+ describe("projects_create / projects_update", () => {
91
+ test("owner: create, rename, recolour, archive, unarchive — same rows the app sees", async () => {
92
+ const created = await mcp(U.owner.token, "projects_create", { network_id: NET, name: "mpe-项目甲" });
93
+ expect(created.ok).toBe(true);
94
+ const id = created.project.id as string;
95
+ expect(created.project.name).toBe("mpe-项目甲");
96
+ const renamed = await mcp(U.owner.token, "projects_update", { network_id: NET, id, name: "mpe-项目乙", color: "#16a34a" });
97
+ expect(renamed.project.name).toBe("mpe-项目乙");
98
+ expect(renamed.project.color).toBe("#16a34a");
99
+ expect((await mcp(U.owner.token, "projects_update", { network_id: NET, id, archived: true })).project.archived).toBe(true);
100
+ const seen = await rest(U.owner.token, "GET", `/api/requirements/projects?network_id=${NET}`);
101
+ expect(seen.body.projects.find((p: any) => p.id === id).archived).toBe(true);
102
+ expect((await mcp(U.owner.token, "projects_update", { network_id: NET, id, archived: false })).project.archived).toBe(false);
103
+ });
104
+
105
+ test("validation comes from the REST handler: duplicate name 409, unknown id 404", async () => {
106
+ await mcp(U.owner.token, "projects_create", { network_id: NET, name: "mpe-重名" });
107
+ const dup = await mcp(U.owner.token, "projects_create", { network_id: NET, name: "mpe-重名" });
108
+ expect(dup.ok).toBe(false);
109
+ expect(dup.status).toBe(409);
110
+ const missing = await mcp(U.owner.token, "projects_update", { network_id: NET, id: "proj_nobody", name: "x" });
111
+ expect(missing.status).toBe(404);
112
+ });
113
+
114
+ test("permission parity with the app's REST path, for every kind of caller", async () => {
115
+ const results: Record<string, { mcp: number; rest: number }> = {};
116
+ for (const who of ["owner", "member", "scoped", "viewer", "node"]) {
117
+ const name = `mpe-parity-${who}`;
118
+ const viaMcp = await mcp(U[who].token, "projects_create", { network_id: NET, name: `${name}-mcp` });
119
+ const viaRest = await rest(U[who].token, "POST", `/api/requirements/projects?network_id=${NET}`, { name: `${name}-rest` });
120
+ results[who] = { mcp: mcpStatus(viaMcp, 201), rest: viaRest.status };
121
+ }
122
+ for (const r of Object.values(results)) expect(r.mcp).toBe(r.rest);
123
+ // the rule itself (RFC-038 §9): task-scoped members and viewers can't manage projects; the others can
124
+ expect(results.owner.rest).toBe(201);
125
+ expect(results.member.rest).toBe(201);
126
+ expect(results.scoped.rest).toBe(403);
127
+ expect(results.viewer.rest).toBe(403);
128
+ });
129
+ });
130
+
131
+ describe("requirements_events", () => {
132
+ test("one task's timeline by id and by #N, same rows as GET /api/requirements/events", async () => {
133
+ const card = await rest(U.owner.token, "POST", "/api/requirements", { network_id: NET, name: "mpe-流水示例" });
134
+ expect(card.status).toBe(201);
135
+ const id = card.body.requirement.id as string, seq = card.body.requirement.seq as number;
136
+ expect((await rest(U.owner.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, { priority: "high" })).status).toBe(200);
137
+ const viaMcp = await mcp(U.owner.token, "requirements_events", { network_id: NET, requirement_id: id });
138
+ const viaRest = await rest(U.owner.token, "GET", `/api/requirements/events?network_id=${NET}&requirement_id=${id}`);
139
+ expect(viaMcp.ok).toBe(true);
140
+ expect(viaMcp.events.length).toBeGreaterThan(0);
141
+ expect(viaMcp.events.map((e: any) => e.id)).toEqual(viaRest.body.events.map((e: any) => e.id));
142
+ expect(viaMcp.events.every((e: any) => e.requirement_id === id)).toBe(true);
143
+ const bySeq = await mcp(U.owner.token, "requirements_events", { network_id: NET, requirement_id: `#${seq}` });
144
+ expect(bySeq.events.map((e: any) => e.id)).toEqual(viaMcp.events.map((e: any) => e.id));
145
+ // paging / bad input come from the REST handler too
146
+ expect((await mcp(U.owner.token, "requirements_events", { network_id: NET, since: "not-a-date" })).status).toBe(400);
147
+ expect((await mcp(U.owner.token, "requirements_events", { network_id: NET, requirement_id: "#999999" })).status).toBe(404);
148
+ });
149
+
150
+ test("visibility parity: a task-scoped member doesn't get events for a task they can't see", async () => {
151
+ const hidden = await rest(U.owner.token, "POST", "/api/requirements", { network_id: NET, name: "mpe-看不见的" });
152
+ const id = hidden.body.requirement.id as string;
153
+ await rest(U.owner.token, "PATCH", `/api/requirements/${id}?network_id=${NET}`, { priority: "low" });
154
+ for (const who of ["scoped", "member", "node"]) {
155
+ const viaMcp = await mcp(U[who].token, "requirements_events", { network_id: NET, requirement_id: id });
156
+ const viaRest = await rest(U[who].token, "GET", `/api/requirements/events?network_id=${NET}&requirement_id=${id}`);
157
+ expect((viaMcp.events ?? []).map((e: any) => e.id)).toEqual((viaRest.body?.events ?? []).map((e: any) => e.id));
158
+ }
159
+ expect((await mcp(U.scoped.token, "requirements_events", { network_id: NET, requirement_id: id })).events ?? []).toHaveLength(0);
160
+ expect((await mcp(U.member.token, "requirements_events", { network_id: NET, requirement_id: id })).events.length).toBeGreaterThan(0);
161
+ });
162
+ });
package/src/tools.ts CHANGED
@@ -5888,10 +5888,67 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
5888
5888
 
5889
5889
  server.tool(
5890
5890
  "projects_list",
5891
- "List requirement projects in your network (id, name, color, sort, archived).",
5891
+ "List requirement projects in your network (id, name, color, sort, archived). Manage them with projects_create / projects_update.",
5892
5892
  { network_id: z.string().max(200).optional() },
5893
5893
  async ({ network_id }) => requirementsCall("GET", "/api/requirements/projects", network_id),
5894
5894
  );
5895
+
5896
+ // Agent parity (app task audit 2026-10-02 M3): what people do under 管理项目 and the task 动态 timeline. Both go
5897
+ // through the same REST handlers as the app, so every permission check is the app's own: project management needs
5898
+ // write access and is refused to 「仅相关任务」(task-scoped) members; events use the task list's visibility.
5899
+ server.tool(
5900
+ "projects_create",
5901
+ "Create a requirement project in your network (same as 管理项目 → 新建 in the app). name 1–40 characters, unique in the network; color #RRGGBB (default: next palette colour); sort integer. Returns { project }. Refused (403) for task-scoped members and read-only roles.",
5902
+ {
5903
+ network_id: z.string().max(200).optional(),
5904
+ name: z.string().min(1).max(40),
5905
+ color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),
5906
+ sort: z.number().int().optional(),
5907
+ },
5908
+ async (args) => requirementsCall("POST", "/api/requirements/projects", args.network_id, pick(args, ["name", "color", "sort"])),
5909
+ );
5910
+
5911
+ server.tool(
5912
+ "projects_update",
5913
+ "Rename, recolour, reorder, archive or unarchive a requirement project (same as 管理项目 in the app). Only the fields you pass change. archived=true hides it from pickers (its tasks keep project_id); archived=false brings it back. Returns { project }. Refused (403) for task-scoped members and read-only roles.",
5914
+ {
5915
+ network_id: z.string().max(200).optional(),
5916
+ id: z.string().min(1).max(200).describe("project id (proj_…), from projects_list"),
5917
+ name: z.string().min(1).max(40).optional(),
5918
+ color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),
5919
+ sort: z.number().int().optional(),
5920
+ archived: z.boolean().optional(),
5921
+ },
5922
+ async (args) => requirementsCall("PATCH", `/api/requirements/projects/${encodeURIComponent(args.id)}`, args.network_id, pick(args, ["name", "color", "sort", "archived"])),
5923
+ );
5924
+
5925
+ server.tool(
5926
+ "requirements_events",
5927
+ "Read the task activity timeline (the app's 动态): field-level changes — who, when, old → new — newest first. Pass requirement_id (req_… or \"#N\") for one task, or omit it for the whole network. since (ISO) = only changes after it; limit 1–500 (default 200); next_cursor → pass as cursor for the next page; server_time → use as the next since. Same visibility as requirements_list: tasks you can't see (and hidden Agents) are left out.",
5928
+ {
5929
+ network_id: z.string().max(200).optional(),
5930
+ requirement_id: z.string().min(1).max(200).optional(),
5931
+ since: z.string().max(40).optional(),
5932
+ limit: z.number().int().min(1).max(500).optional(),
5933
+ cursor: z.string().max(20).optional(),
5934
+ },
5935
+ async (args) => {
5936
+ let card = args.requirement_id;
5937
+ // "#N" → the card's id, resolved exactly like requirements_get (same scope; a card you can't see is a 404 here too).
5938
+ if (card && /^#\d+$/.test(card)) {
5939
+ const got = await requirementsCall("GET", `/api/requirements/${encodeURIComponent(card)}`, args.network_id);
5940
+ const parsed = JSON.parse(got.content[0].text) as { requirement?: { id?: string } };
5941
+ if (!parsed.requirement?.id) return got;
5942
+ card = parsed.requirement.id;
5943
+ }
5944
+ const q = new URLSearchParams();
5945
+ if (card) q.set("requirement_id", card);
5946
+ if (args.since) q.set("since", args.since);
5947
+ if (args.limit !== undefined) q.set("limit", String(args.limit));
5948
+ if (args.cursor) q.set("cursor", args.cursor);
5949
+ return requirementsCall("GET", `/api/requirements/events${q.size ? `?${q}` : ""}`, args.network_id);
5950
+ },
5951
+ );
5895
5952
  }
5896
5953
 
5897
5954
  // ────────────────────────────────────────────────────────────────────