@openshain/mcp 0.3.1 → 0.4.1

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/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ openshain
2
+ Copyright 2026 openshain contributors
3
+
4
+ Licensed under the Apache License, Version 2.0.
package/dist/server.js CHANGED
@@ -1,6 +1,7 @@
1
+ import { relative } from "node:path";
1
2
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
3
  import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
3
- import { ASK_USER, compileInputValidator, countToolCalls, createToolCaller, createToolRegistry, isKnownEventType, isOpenshainError, isTerminal, loadConfig, parsePayloadFile, parseWorkId, pendingQuestions, RUNTIME_PROVIDER_ID, resolveWorkspacePath, SESSION_WORK_TYPE, uuidv7, verifyArtifact, WorkStore, workHistory, } from "@openshain/core";
4
+ import { ASK_USER, businessDate, companyTime, compileInputValidator, countToolCalls, createToolCaller, createToolRegistry, DecisionFileSchema, isKnownEventType, isOpenshainError, isTerminal, loadAuthority, loadConfig, parsePayloadFile, parseWorkId, pendingApprovals, pendingQuestions, RUNTIME_PROVIDER_ID, resolveWorkspacePath, SESSION_WORK_TYPE, uuidv7, verifyArtifact, WorkStore, workHistory, writeDecision, } from "@openshain/core";
4
5
  import pkg from "../package.json" with { type: "json" };
5
6
  import { Session } from "./session.js";
6
7
  /** The tools every session has, before the workspace's own. Their names are reserved in the runtime. */
@@ -116,6 +117,67 @@ const WORK_TOOLS = [
116
117
  additionalProperties: false,
117
118
  },
118
119
  },
120
+ {
121
+ name: "context",
122
+ description: "Where and when you are working: the current time with its offset, the time zone, today's business date, the company folder, the company, the person you work for, and the current work. Call it when a date or a time matters; the answer is recorded.",
123
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
124
+ annotations: { readOnlyHint: true },
125
+ },
126
+ {
127
+ name: "approval_list",
128
+ description: "Every tool call held for a person's approval across the works of this workspace, oldest first: approval_id, work_id, the call, the rule, and who may approve.",
129
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
130
+ annotations: { readOnlyHint: true },
131
+ },
132
+ {
133
+ name: "approval_decide",
134
+ description: "Decide a held tool call as the person this connection acts for. approve runs the call now and returns its result; reject refuses it. Either way the work continues.",
135
+ inputSchema: {
136
+ type: "object",
137
+ properties: {
138
+ approval_id: { type: "string", maxLength: 100 },
139
+ decision: { type: "string", enum: ["approve", "reject"] },
140
+ comment: { type: "string", maxLength: 2000 },
141
+ },
142
+ required: ["approval_id", "decision"],
143
+ additionalProperties: false,
144
+ },
145
+ },
146
+ {
147
+ name: "review_decide",
148
+ description: "Record what a qualified reviewer decided about a call the policy held for review. approve and modify write a decision under authority/decisions/ and run the call (modify runs the reviewer's input); reject refuses it. The reviewer is named by the company; openshain does not verify a qualification.",
149
+ inputSchema: {
150
+ type: "object",
151
+ properties: {
152
+ approval_id: { type: "string", maxLength: 100 },
153
+ decision: { type: "string", enum: ["approve", "reject", "modify"] },
154
+ reviewer: {
155
+ type: "object",
156
+ properties: {
157
+ name: { type: "string", maxLength: 200 },
158
+ role: { type: "string", maxLength: 100 },
159
+ qualification: { type: "string", maxLength: 500 },
160
+ },
161
+ required: ["name", "role"],
162
+ additionalProperties: false,
163
+ },
164
+ interpretation: { type: "string", maxLength: 20_000 },
165
+ modified_input: { type: "object" },
166
+ effective_from: { type: "string", maxLength: 10 },
167
+ effective_until: { type: "string", maxLength: 10 },
168
+ applies_to: {
169
+ type: "object",
170
+ properties: {
171
+ action: { type: "string", maxLength: 200 },
172
+ path: { type: "string", maxLength: 1000 },
173
+ },
174
+ additionalProperties: false,
175
+ },
176
+ },
177
+ required: ["approval_id", "decision", "reviewer"],
178
+ additionalProperties: false,
179
+ },
180
+ },
119
181
  {
120
182
  name: "work_record",
121
183
  description: "Record an event of the client itself on a work: what the person said (human.message), a prompt command expanded for the model (prompt.expanded), a model call (model.requested, model.completed, model.failed) or its usage (usage.recorded with kind model_inference). The payload is in the file form of spec/schemas/events.v1.json. Tool calls are recorded by the runtime and cannot be recorded here.",
@@ -164,7 +226,14 @@ export async function createMcpServer(options) {
164
226
  const { workspaceRoot } = options;
165
227
  const config = await loadConfig(workspaceRoot);
166
228
  const registry = await createToolRegistry(workspaceRoot, config, options.tools);
167
- const callTool = createToolCaller({ registry, config, workspaceRoot });
229
+ // Reloaded when a reviewer writes a decision, so the next call can cite it.
230
+ let authority = await loadAuthority(workspaceRoot);
231
+ const callTool = createToolCaller({
232
+ registry,
233
+ config,
234
+ workspaceRoot,
235
+ authority: () => authority,
236
+ });
168
237
  const works = new WorkStore(workspaceRoot);
169
238
  const session = new Session();
170
239
  const server = new Server({ name: "openshain", version: pkg.version }, { capabilities: { tools: {} } });
@@ -315,6 +384,200 @@ export async function createMcpServer(options) {
315
384
  await opened.close();
316
385
  }
317
386
  }
387
+ case "context": {
388
+ const now = new Date();
389
+ const timezone = config.company.timezone;
390
+ const info = {
391
+ now: companyTime(timezone, now),
392
+ timezone,
393
+ business_date: businessDate(timezone, now),
394
+ workspace: workspaceRoot,
395
+ company: config.company.name,
396
+ principal: { id: config.principal.id, name: config.principal.name },
397
+ profession: config.profession.id,
398
+ work: session.current ?? null,
399
+ };
400
+ const result = json(info);
401
+ // Recorded on the current work when there is one, even a session: it touches no file.
402
+ const current = session.current;
403
+ if (current && !isTerminal((await works.get(current)).status)) {
404
+ const callId = newCallId();
405
+ const opened = await works.open(current);
406
+ try {
407
+ await opened.append({
408
+ type: "tool.called",
409
+ payload: { callId, provider: RUNTIME_PROVIDER_ID, name: "context", input: {} },
410
+ });
411
+ await opened.append({
412
+ type: "tool.completed",
413
+ payload: { callId, content: [{ type: "json", value: info }], isError: false },
414
+ });
415
+ }
416
+ finally {
417
+ await opened.close();
418
+ }
419
+ }
420
+ return result;
421
+ }
422
+ case "approval_list": {
423
+ const held = [];
424
+ const { works: all } = await works.list();
425
+ for (const w of all) {
426
+ if (w.status !== "waiting_approval")
427
+ continue;
428
+ for (const a of pendingApprovals(await works.events(w.id))) {
429
+ held.push({ ...a, work_id: w.id, objective: w.objective });
430
+ }
431
+ }
432
+ return json({ approvals: held });
433
+ }
434
+ case "approval_decide": {
435
+ const { approval_id: approvalId, decision, comment, } = input;
436
+ const found = await findApproval(works, approvalId);
437
+ if (!found)
438
+ return failure(`no pending approval ${approvalId}`);
439
+ const { workId, approval } = found;
440
+ const by = config.principal.id;
441
+ if (approval.kind === "review") {
442
+ return failure(`${approvalId} waits for a qualified reviewer, not a person's approval; use review_decide`);
443
+ }
444
+ if (approval.approvers && !approval.approvers.includes(by)) {
445
+ return failure(`${by} may not decide ${approvalId}; approvers: ${approval.approvers.join(", ")}`);
446
+ }
447
+ const opened = await works.open(workId);
448
+ try {
449
+ // Under the lock: another connection may have decided this approval in between.
450
+ if (!pendingApprovals(await opened.events()).some((a) => a.approvalId === approvalId)) {
451
+ return failure(`approval ${approvalId} was already decided`);
452
+ }
453
+ await opened.append({
454
+ type: "approval.decided",
455
+ payload: { approvalId, decision, by, ...(comment !== undefined && { comment }) },
456
+ });
457
+ if (decision === "reject") {
458
+ await opened.append({
459
+ type: "tool.rejected",
460
+ payload: {
461
+ callId: approval.call.callId,
462
+ name: approval.call.name,
463
+ code: "rejected_by_person",
464
+ reason: comment ?? `${by} rejected ${approvalId}`,
465
+ },
466
+ });
467
+ await opened.transition("in_progress", `${by} rejected ${approvalId}`);
468
+ return json({ approval_id: approvalId, decision, work_id: workId });
469
+ }
470
+ await opened.transition("in_progress", `${by} approved ${approvalId}`);
471
+ const result = await callTool(opened, { id: approval.call.callId, name: approval.call.name, input: approval.call.input }, { approvedBy: approvalId });
472
+ return json({
473
+ approval_id: approvalId,
474
+ decision,
475
+ work_id: workId,
476
+ result: { content: result.content, isError: result.isError ?? false },
477
+ });
478
+ }
479
+ finally {
480
+ await opened.close();
481
+ }
482
+ }
483
+ case "review_decide": {
484
+ const { approval_id: approvalId, decision, reviewer, interpretation, modified_input: modifiedInput, effective_from: effectiveFrom, effective_until: effectiveUntil, applies_to: appliesTo, } = input;
485
+ const found = await findApproval(works, approvalId);
486
+ if (!found)
487
+ return failure(`no pending approval ${approvalId}`);
488
+ const { workId, approval } = found;
489
+ if (approval.kind !== "review") {
490
+ return failure(`${approvalId} waits for a person's approval, not a review; use approval_decide`);
491
+ }
492
+ if (decision !== "reject" && (interpretation ?? "") === "") {
493
+ return failure("a decision needs the reviewer's interpretation in their own words");
494
+ }
495
+ if (approval.reviewer && approval.reviewer.role !== reviewer.role) {
496
+ return failure(`rule ${approval.ruleId} asks for a ${approval.reviewer.role}; the decision names a ${reviewer.role}`);
497
+ }
498
+ if (decision === "modify" && modifiedInput) {
499
+ // Checked before anything is recorded: a refused input leaves the approval pending.
500
+ const before = (approval.call.input ?? {});
501
+ const after = modifiedInput;
502
+ if (before.path !== after.path) {
503
+ return failure(`a modified call must touch the same path: ${String(before.path)} was held, ${String(after.path)} was given`);
504
+ }
505
+ }
506
+ // Built and checked before anything is recorded: an input the decision refuses must not
507
+ // consume the approval and leave the work waiting with nobody able to move it.
508
+ const today = new Date();
509
+ let record;
510
+ if (decision !== "reject") {
511
+ const parsed = DecisionFileSchema.safeParse({
512
+ id: `dec_${uuidv7()}`,
513
+ reviewer,
514
+ approval_id: approvalId,
515
+ decided_at: today.toISOString(),
516
+ effective_from: effectiveFrom ?? today.toISOString().slice(0, 10),
517
+ effective_until: effectiveUntil ?? null,
518
+ interpretation,
519
+ applies_to: appliesTo ?? {},
520
+ });
521
+ if (!parsed.success) {
522
+ return failure(`the decision is not well formed: ${parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`);
523
+ }
524
+ record = parsed.data;
525
+ }
526
+ const opened = await works.open(workId);
527
+ try {
528
+ // Under the lock: another connection may have decided this approval in between.
529
+ if (!pendingApprovals(await opened.events()).some((a) => a.approvalId === approvalId)) {
530
+ return failure(`approval ${approvalId} was already decided`);
531
+ }
532
+ await opened.append({
533
+ type: "approval.decided",
534
+ payload: {
535
+ approvalId,
536
+ decision,
537
+ by: reviewer.name,
538
+ ...(interpretation !== undefined && { comment: interpretation }),
539
+ ...(decision === "modify" && modifiedInput && { modifiedInput }),
540
+ },
541
+ });
542
+ if (decision === "reject") {
543
+ await opened.append({ type: "review.decided", payload: { approvalId } });
544
+ await opened.append({
545
+ type: "tool.rejected",
546
+ payload: {
547
+ callId: approval.call.callId,
548
+ name: approval.call.name,
549
+ code: "rejected_by_person",
550
+ reason: interpretation ?? `${reviewer.name} did not approve ${approvalId}`,
551
+ },
552
+ });
553
+ await opened.transition("in_progress", `${reviewer.name} rejected ${approvalId}`);
554
+ return json({ approval_id: approvalId, decision, work_id: workId });
555
+ }
556
+ const written = record;
557
+ const file = await writeDecision(workspaceRoot, written);
558
+ await opened.append({
559
+ type: "review.decided",
560
+ payload: { approvalId, decisionId: written.id },
561
+ });
562
+ await opened.transition("in_progress", `${reviewer.name} decided ${approvalId}`);
563
+ const ranWith = decision === "modify" && modifiedInput ? modifiedInput : approval.call.input;
564
+ const ran = await callTool(opened, { id: approval.call.callId, name: approval.call.name, input: ranWith }, { approvedBy: approvalId });
565
+ // The decision is on disk; a rule that cites its id can use it from here on. Reloaded
566
+ // so that a rule already written for it takes effect without a restart.
567
+ authority = await loadAuthority(workspaceRoot);
568
+ return json({
569
+ approval_id: approvalId,
570
+ decision,
571
+ work_id: workId,
572
+ decision_id: written.id,
573
+ decision_file: relative(workspaceRoot, file),
574
+ result: { content: ran.content, isError: ran.isError ?? false },
575
+ });
576
+ }
577
+ finally {
578
+ await opened.close();
579
+ }
580
+ }
318
581
  case "work_list": {
319
582
  const { works: all, problems } = await works.list();
320
583
  return json({
@@ -368,6 +631,9 @@ export async function createMcpServer(options) {
368
631
  if (work.status === "waiting_input") {
369
632
  return failure(`work ${gate.id} is waiting for the person's answer; record it with work_answer before calling tools`);
370
633
  }
634
+ if (work.status === "waiting_approval") {
635
+ return failure(`work ${gate.id} is waiting for an approval; decide it with approval_decide (see approval_list) before calling tools`);
636
+ }
371
637
  const opened = await works.open(gate.id);
372
638
  try {
373
639
  const limit = config.limits.maxToolCalls;
@@ -471,3 +737,15 @@ function failure(text) {
471
737
  function newCallId() {
472
738
  return `call_${uuidv7()}`;
473
739
  }
740
+ /** The work holding a pending approval, found by scanning the works that wait for one. */
741
+ async function findApproval(works, approvalId) {
742
+ const { works: all } = await works.list();
743
+ for (const w of all) {
744
+ if (w.status !== "waiting_approval")
745
+ continue;
746
+ const approval = pendingApprovals(await works.events(w.id)).find((a) => a.approvalId === approvalId);
747
+ if (approval)
748
+ return { workId: w.id, approval };
749
+ }
750
+ return undefined;
751
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openshain/mcp",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "description": "MCP server that exposes an openshain workspace to any agent",
5
5
  "keywords": [
6
6
  "openshain",
@@ -30,7 +30,8 @@
30
30
  "!src/**/*.test.ts",
31
31
  "!src/**/*.test.tsx",
32
32
  "README.md",
33
- "LICENSE"
33
+ "LICENSE",
34
+ "NOTICE"
34
35
  ],
35
36
  "exports": {
36
37
  ".": {
@@ -45,10 +46,10 @@
45
46
  },
46
47
  "dependencies": {
47
48
  "@modelcontextprotocol/sdk": "1.30.0",
48
- "@openshain/core": "0.3.1"
49
+ "@openshain/core": "0.4.1"
49
50
  },
50
51
  "devDependencies": {
51
- "@openshain/tools": "0.3.1"
52
+ "@openshain/tools": "0.4.1"
52
53
  },
53
54
  "publishConfig": {
54
55
  "access": "public"
package/src/server.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { relative } from "node:path";
1
2
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
3
  import {
3
4
  CallToolRequestSchema,
@@ -9,19 +10,26 @@ import {
9
10
  type AnyEvent,
10
11
  type Artifact,
11
12
  ASK_USER,
13
+ businessDate,
14
+ companyTime,
12
15
  compileInputValidator,
13
16
  countToolCalls,
14
17
  createToolCaller,
15
18
  createToolRegistry,
19
+ DecisionFileSchema,
20
+ type DecisionRecord,
16
21
  type Event,
17
22
  type EventType,
18
23
  type InputValidation,
19
24
  isKnownEventType,
20
25
  isOpenshainError,
21
26
  isTerminal,
27
+ loadAuthority,
22
28
  loadConfig,
29
+ type PendingApproval,
23
30
  parsePayloadFile,
24
31
  parseWorkId,
32
+ pendingApprovals,
25
33
  pendingQuestions,
26
34
  RUNTIME_PROVIDER_ID,
27
35
  type RuntimeProviders,
@@ -35,6 +43,7 @@ import {
35
43
  type WorkId,
36
44
  WorkStore,
37
45
  workHistory,
46
+ writeDecision,
38
47
  } from "@openshain/core";
39
48
  import pkg from "../package.json" with { type: "json" };
40
49
  import { Session } from "./session.ts";
@@ -163,6 +172,71 @@ const WORK_TOOLS: Tool[] = [
163
172
  additionalProperties: false,
164
173
  },
165
174
  },
175
+ {
176
+ name: "context",
177
+ description:
178
+ "Where and when you are working: the current time with its offset, the time zone, today's business date, the company folder, the company, the person you work for, and the current work. Call it when a date or a time matters; the answer is recorded.",
179
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
180
+ annotations: { readOnlyHint: true },
181
+ },
182
+ {
183
+ name: "approval_list",
184
+ description:
185
+ "Every tool call held for a person's approval across the works of this workspace, oldest first: approval_id, work_id, the call, the rule, and who may approve.",
186
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
187
+ annotations: { readOnlyHint: true },
188
+ },
189
+ {
190
+ name: "approval_decide",
191
+ description:
192
+ "Decide a held tool call as the person this connection acts for. approve runs the call now and returns its result; reject refuses it. Either way the work continues.",
193
+ inputSchema: {
194
+ type: "object",
195
+ properties: {
196
+ approval_id: { type: "string", maxLength: 100 },
197
+ decision: { type: "string", enum: ["approve", "reject"] },
198
+ comment: { type: "string", maxLength: 2000 },
199
+ },
200
+ required: ["approval_id", "decision"],
201
+ additionalProperties: false,
202
+ },
203
+ },
204
+ {
205
+ name: "review_decide",
206
+ description:
207
+ "Record what a qualified reviewer decided about a call the policy held for review. approve and modify write a decision under authority/decisions/ and run the call (modify runs the reviewer's input); reject refuses it. The reviewer is named by the company; openshain does not verify a qualification.",
208
+ inputSchema: {
209
+ type: "object",
210
+ properties: {
211
+ approval_id: { type: "string", maxLength: 100 },
212
+ decision: { type: "string", enum: ["approve", "reject", "modify"] },
213
+ reviewer: {
214
+ type: "object",
215
+ properties: {
216
+ name: { type: "string", maxLength: 200 },
217
+ role: { type: "string", maxLength: 100 },
218
+ qualification: { type: "string", maxLength: 500 },
219
+ },
220
+ required: ["name", "role"],
221
+ additionalProperties: false,
222
+ },
223
+ interpretation: { type: "string", maxLength: 20_000 },
224
+ modified_input: { type: "object" },
225
+ effective_from: { type: "string", maxLength: 10 },
226
+ effective_until: { type: "string", maxLength: 10 },
227
+ applies_to: {
228
+ type: "object",
229
+ properties: {
230
+ action: { type: "string", maxLength: 200 },
231
+ path: { type: "string", maxLength: 1000 },
232
+ },
233
+ additionalProperties: false,
234
+ },
235
+ },
236
+ required: ["approval_id", "decision", "reviewer"],
237
+ additionalProperties: false,
238
+ },
239
+ },
166
240
  {
167
241
  name: "work_record",
168
242
  description:
@@ -222,7 +296,14 @@ export async function createMcpServer(options: McpServerOptions): Promise<Server
222
296
  const { workspaceRoot } = options;
223
297
  const config = await loadConfig(workspaceRoot);
224
298
  const registry = await createToolRegistry(workspaceRoot, config, options.tools);
225
- const callTool = createToolCaller({ registry, config, workspaceRoot });
299
+ // Reloaded when a reviewer writes a decision, so the next call can cite it.
300
+ let authority = await loadAuthority(workspaceRoot);
301
+ const callTool = createToolCaller({
302
+ registry,
303
+ config,
304
+ workspaceRoot,
305
+ authority: () => authority,
306
+ });
226
307
  const works = new WorkStore(workspaceRoot);
227
308
  const session = new Session();
228
309
  const server = new Server(
@@ -385,6 +466,237 @@ export async function createMcpServer(options: McpServerOptions): Promise<Server
385
466
  await opened.close();
386
467
  }
387
468
  }
469
+ case "context": {
470
+ const now = new Date();
471
+ const timezone = config.company.timezone;
472
+ const info = {
473
+ now: companyTime(timezone, now),
474
+ timezone,
475
+ business_date: businessDate(timezone, now),
476
+ workspace: workspaceRoot,
477
+ company: config.company.name,
478
+ principal: { id: config.principal.id, name: config.principal.name },
479
+ profession: config.profession.id,
480
+ work: session.current ?? null,
481
+ };
482
+ const result = json(info);
483
+ // Recorded on the current work when there is one, even a session: it touches no file.
484
+ const current = session.current;
485
+ if (current && !isTerminal((await works.get(current)).status)) {
486
+ const callId = newCallId();
487
+ const opened = await works.open(current);
488
+ try {
489
+ await opened.append({
490
+ type: "tool.called",
491
+ payload: { callId, provider: RUNTIME_PROVIDER_ID, name: "context", input: {} },
492
+ });
493
+ await opened.append({
494
+ type: "tool.completed",
495
+ payload: { callId, content: [{ type: "json", value: info }], isError: false },
496
+ });
497
+ } finally {
498
+ await opened.close();
499
+ }
500
+ }
501
+ return result;
502
+ }
503
+ case "approval_list": {
504
+ const held: unknown[] = [];
505
+ const { works: all } = await works.list();
506
+ for (const w of all) {
507
+ if (w.status !== "waiting_approval") continue;
508
+ for (const a of pendingApprovals(await works.events(w.id))) {
509
+ held.push({ ...a, work_id: w.id, objective: w.objective });
510
+ }
511
+ }
512
+ return json({ approvals: held });
513
+ }
514
+ case "approval_decide": {
515
+ const {
516
+ approval_id: approvalId,
517
+ decision,
518
+ comment,
519
+ } = input as { approval_id: string; decision: "approve" | "reject"; comment?: string };
520
+ const found = await findApproval(works, approvalId);
521
+ if (!found) return failure(`no pending approval ${approvalId}`);
522
+ const { workId, approval } = found;
523
+ const by = config.principal.id;
524
+ if (approval.kind === "review") {
525
+ return failure(
526
+ `${approvalId} waits for a qualified reviewer, not a person's approval; use review_decide`,
527
+ );
528
+ }
529
+ if (approval.approvers && !approval.approvers.includes(by)) {
530
+ return failure(
531
+ `${by} may not decide ${approvalId}; approvers: ${approval.approvers.join(", ")}`,
532
+ );
533
+ }
534
+ const opened = await works.open(workId);
535
+ try {
536
+ // Under the lock: another connection may have decided this approval in between.
537
+ if (!pendingApprovals(await opened.events()).some((a) => a.approvalId === approvalId)) {
538
+ return failure(`approval ${approvalId} was already decided`);
539
+ }
540
+ await opened.append({
541
+ type: "approval.decided",
542
+ payload: { approvalId, decision, by, ...(comment !== undefined && { comment }) },
543
+ });
544
+ if (decision === "reject") {
545
+ await opened.append({
546
+ type: "tool.rejected",
547
+ payload: {
548
+ callId: approval.call.callId,
549
+ name: approval.call.name,
550
+ code: "rejected_by_person",
551
+ reason: comment ?? `${by} rejected ${approvalId}`,
552
+ },
553
+ });
554
+ await opened.transition("in_progress", `${by} rejected ${approvalId}`);
555
+ return json({ approval_id: approvalId, decision, work_id: workId });
556
+ }
557
+ await opened.transition("in_progress", `${by} approved ${approvalId}`);
558
+ const result = await callTool(
559
+ opened,
560
+ { id: approval.call.callId, name: approval.call.name, input: approval.call.input },
561
+ { approvedBy: approvalId },
562
+ );
563
+ return json({
564
+ approval_id: approvalId,
565
+ decision,
566
+ work_id: workId,
567
+ result: { content: result.content, isError: result.isError ?? false },
568
+ });
569
+ } finally {
570
+ await opened.close();
571
+ }
572
+ }
573
+ case "review_decide": {
574
+ const {
575
+ approval_id: approvalId,
576
+ decision,
577
+ reviewer,
578
+ interpretation,
579
+ modified_input: modifiedInput,
580
+ effective_from: effectiveFrom,
581
+ effective_until: effectiveUntil,
582
+ applies_to: appliesTo,
583
+ } = input as {
584
+ approval_id: string;
585
+ decision: "approve" | "reject" | "modify";
586
+ reviewer: { name: string; role: string; qualification?: string };
587
+ interpretation?: string;
588
+ modified_input?: Record<string, unknown>;
589
+ effective_from?: string;
590
+ effective_until?: string;
591
+ applies_to?: { action?: string; path?: string };
592
+ };
593
+ const found = await findApproval(works, approvalId);
594
+ if (!found) return failure(`no pending approval ${approvalId}`);
595
+ const { workId, approval } = found;
596
+ if (approval.kind !== "review") {
597
+ return failure(
598
+ `${approvalId} waits for a person's approval, not a review; use approval_decide`,
599
+ );
600
+ }
601
+ if (decision !== "reject" && (interpretation ?? "") === "") {
602
+ return failure("a decision needs the reviewer's interpretation in their own words");
603
+ }
604
+ if (approval.reviewer && approval.reviewer.role !== reviewer.role) {
605
+ return failure(
606
+ `rule ${approval.ruleId} asks for a ${approval.reviewer.role}; the decision names a ${reviewer.role}`,
607
+ );
608
+ }
609
+ if (decision === "modify" && modifiedInput) {
610
+ // Checked before anything is recorded: a refused input leaves the approval pending.
611
+ const before = (approval.call.input ?? {}) as { path?: unknown };
612
+ const after = modifiedInput as { path?: unknown };
613
+ if (before.path !== after.path) {
614
+ return failure(
615
+ `a modified call must touch the same path: ${String(before.path)} was held, ${String(after.path)} was given`,
616
+ );
617
+ }
618
+ }
619
+ // Built and checked before anything is recorded: an input the decision refuses must not
620
+ // consume the approval and leave the work waiting with nobody able to move it.
621
+ const today = new Date();
622
+ let record: DecisionRecord | undefined;
623
+ if (decision !== "reject") {
624
+ const parsed = DecisionFileSchema.safeParse({
625
+ id: `dec_${uuidv7()}`,
626
+ reviewer,
627
+ approval_id: approvalId,
628
+ decided_at: today.toISOString(),
629
+ effective_from: effectiveFrom ?? today.toISOString().slice(0, 10),
630
+ effective_until: effectiveUntil ?? null,
631
+ interpretation,
632
+ applies_to: appliesTo ?? {},
633
+ });
634
+ if (!parsed.success) {
635
+ return failure(
636
+ `the decision is not well formed: ${parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`,
637
+ );
638
+ }
639
+ record = parsed.data;
640
+ }
641
+ const opened = await works.open(workId);
642
+ try {
643
+ // Under the lock: another connection may have decided this approval in between.
644
+ if (!pendingApprovals(await opened.events()).some((a) => a.approvalId === approvalId)) {
645
+ return failure(`approval ${approvalId} was already decided`);
646
+ }
647
+ await opened.append({
648
+ type: "approval.decided",
649
+ payload: {
650
+ approvalId,
651
+ decision,
652
+ by: reviewer.name,
653
+ ...(interpretation !== undefined && { comment: interpretation }),
654
+ ...(decision === "modify" && modifiedInput && { modifiedInput }),
655
+ },
656
+ });
657
+ if (decision === "reject") {
658
+ await opened.append({ type: "review.decided", payload: { approvalId } });
659
+ await opened.append({
660
+ type: "tool.rejected",
661
+ payload: {
662
+ callId: approval.call.callId,
663
+ name: approval.call.name,
664
+ code: "rejected_by_person",
665
+ reason: interpretation ?? `${reviewer.name} did not approve ${approvalId}`,
666
+ },
667
+ });
668
+ await opened.transition("in_progress", `${reviewer.name} rejected ${approvalId}`);
669
+ return json({ approval_id: approvalId, decision, work_id: workId });
670
+ }
671
+ const written = record as DecisionRecord;
672
+ const file = await writeDecision(workspaceRoot, written);
673
+ await opened.append({
674
+ type: "review.decided",
675
+ payload: { approvalId, decisionId: written.id },
676
+ });
677
+ await opened.transition("in_progress", `${reviewer.name} decided ${approvalId}`);
678
+ const ranWith =
679
+ decision === "modify" && modifiedInput ? modifiedInput : approval.call.input;
680
+ const ran = await callTool(
681
+ opened,
682
+ { id: approval.call.callId, name: approval.call.name, input: ranWith },
683
+ { approvedBy: approvalId },
684
+ );
685
+ // The decision is on disk; a rule that cites its id can use it from here on. Reloaded
686
+ // so that a rule already written for it takes effect without a restart.
687
+ authority = await loadAuthority(workspaceRoot);
688
+ return json({
689
+ approval_id: approvalId,
690
+ decision,
691
+ work_id: workId,
692
+ decision_id: written.id,
693
+ decision_file: relative(workspaceRoot, file),
694
+ result: { content: ran.content, isError: ran.isError ?? false },
695
+ });
696
+ } finally {
697
+ await opened.close();
698
+ }
699
+ }
388
700
  case "work_list": {
389
701
  const { works: all, problems } = await works.list();
390
702
  return json({
@@ -438,6 +750,11 @@ export async function createMcpServer(options: McpServerOptions): Promise<Server
438
750
  `work ${gate.id} is waiting for the person's answer; record it with work_answer before calling tools`,
439
751
  );
440
752
  }
753
+ if (work.status === "waiting_approval") {
754
+ return failure(
755
+ `work ${gate.id} is waiting for an approval; decide it with approval_decide (see approval_list) before calling tools`,
756
+ );
757
+ }
441
758
  const opened = await works.open(gate.id);
442
759
  try {
443
760
  const limit = config.limits.maxToolCalls;
@@ -556,3 +873,19 @@ function failure(text: string): CallToolResult {
556
873
  function newCallId(): string {
557
874
  return `call_${uuidv7()}`;
558
875
  }
876
+
877
+ /** The work holding a pending approval, found by scanning the works that wait for one. */
878
+ async function findApproval(
879
+ works: WorkStore,
880
+ approvalId: string,
881
+ ): Promise<{ workId: WorkId; approval: PendingApproval } | undefined> {
882
+ const { works: all } = await works.list();
883
+ for (const w of all) {
884
+ if (w.status !== "waiting_approval") continue;
885
+ const approval = pendingApprovals(await works.events(w.id)).find(
886
+ (a) => a.approvalId === approvalId,
887
+ );
888
+ if (approval) return { workId: w.id, approval };
889
+ }
890
+ return undefined;
891
+ }