@sanity/workflow-mcp 0.3.0
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/LICENSE +21 -0
- package/README.md +97 -0
- package/bin/run.js +9 -0
- package/dist/index.cjs +455 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +248 -0
- package/dist/index.d.ts +248 -0
- package/dist/index.js +456 -0
- package/dist/index.js.map +1 -0
- package/dist/stdio.d.ts +24 -0
- package/dist/stdio.js +70 -0
- package/dist/stdio.js.map +1 -0
- package/package.json +75 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
import { extractDocumentId, actionVerdict, isTerminalStage, validateDefinition, WORKFLOW_INSTANCE_TYPE, tagScopeFilter } from "@sanity/workflow-engine";
|
|
2
|
+
import { defineWorkflow } from "@sanity/workflow-engine/define";
|
|
3
|
+
const minimalExample = {
|
|
4
|
+
name: "quick-approval",
|
|
5
|
+
version: 1,
|
|
6
|
+
title: "Quick approval",
|
|
7
|
+
description: "One review stage with a single approve action, then a terminal stage.",
|
|
8
|
+
initialStage: "review",
|
|
9
|
+
fields: [{ type: "doc.ref", name: "subject", title: "Document", source: { type: "init" } }],
|
|
10
|
+
stages: [
|
|
11
|
+
{
|
|
12
|
+
name: "review",
|
|
13
|
+
title: "Review",
|
|
14
|
+
tasks: [
|
|
15
|
+
{
|
|
16
|
+
name: "decide",
|
|
17
|
+
title: "Decide",
|
|
18
|
+
activation: "auto",
|
|
19
|
+
actions: [{ name: "approve", title: "Approve", status: "done" }]
|
|
20
|
+
}
|
|
21
|
+
],
|
|
22
|
+
transitions: [{ name: "to-approved", title: "Approve and finish", to: "approved" }]
|
|
23
|
+
},
|
|
24
|
+
{ name: "approved", title: "Approved", description: "Terminal \u2014 no transitions out." }
|
|
25
|
+
]
|
|
26
|
+
}, reviewLoopExample = {
|
|
27
|
+
name: "doc-review",
|
|
28
|
+
version: 1,
|
|
29
|
+
title: "Document review",
|
|
30
|
+
description: "Draft, then editorial review that approves or rejects back to drafting.",
|
|
31
|
+
initialStage: "drafting",
|
|
32
|
+
fields: [{ type: "doc.ref", name: "subject", title: "Document", source: { type: "init" } }],
|
|
33
|
+
stages: [
|
|
34
|
+
{
|
|
35
|
+
name: "drafting",
|
|
36
|
+
title: "Drafting",
|
|
37
|
+
tasks: [
|
|
38
|
+
{
|
|
39
|
+
name: "write",
|
|
40
|
+
title: "Write the draft",
|
|
41
|
+
activation: "auto",
|
|
42
|
+
actions: [{ name: "submit", title: "Submit for review", status: "done" }]
|
|
43
|
+
}
|
|
44
|
+
],
|
|
45
|
+
transitions: [{ name: "to-review", title: "Send to review", to: "review" }]
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
name: "review",
|
|
49
|
+
title: "Editorial review",
|
|
50
|
+
tasks: [
|
|
51
|
+
{
|
|
52
|
+
name: "review",
|
|
53
|
+
title: "Review the draft",
|
|
54
|
+
activation: "auto",
|
|
55
|
+
actions: [
|
|
56
|
+
{ name: "approve", title: "Approve", status: "done" },
|
|
57
|
+
{ name: "reject", title: "Reject", status: "failed" }
|
|
58
|
+
]
|
|
59
|
+
}
|
|
60
|
+
],
|
|
61
|
+
transitions: [
|
|
62
|
+
{ name: "to-approved", title: "Approve and finish", to: "approved" },
|
|
63
|
+
// Reject flips the task to `failed`; this routes the instance back.
|
|
64
|
+
{
|
|
65
|
+
name: "to-drafting",
|
|
66
|
+
title: "Send back to drafting",
|
|
67
|
+
to: "drafting",
|
|
68
|
+
filter: "$anyTaskFailed"
|
|
69
|
+
}
|
|
70
|
+
]
|
|
71
|
+
},
|
|
72
|
+
{ name: "approved", title: "Approved", description: "Terminal \u2014 no transitions out." }
|
|
73
|
+
]
|
|
74
|
+
}, ORIENTATION = "# Authoring a workflow definition\n\nA workflow definition is a plain JSON object. There is no code in it \u2014 every\ncondition (filters, predicates, guards) is a GROQ *string*. Generate the JSON,\nthen call `validate_workflow_definition` to check it; fix the reported errors\nand re-validate until it returns `valid: true`. The validator returns the\n*desugared* definition under `definition` \u2014 that is exactly what would deploy.\n\n## Shape\n\n- **Workflow**: `{ name, version (positive int), title, description?, initialStage, fields?, stages[], predicates? }`.\n `initialStage` must be the `name` of a declared stage.\n- **Stage**: `{ name, title?, description?, tasks?, transitions? }`. A stage with\n no transitions is terminal. Reaching a terminal stage ends the workflow.\n- **Task**: `{ name, title?, activation?, actions? }`. `activation` is `'auto'`\n (starts when the stage is entered) or `'manual'` (default \u2014 a human starts it).\n- **Action**: `{ name, title?, status?, params?, ops? }`.\n `status: 'done' | 'skipped' | 'failed'` is sugar that flips the *firing task* to\n that status when the action fires. `ops` are mutations applied when the action\n fires (e.g. `{type:'field.set', target:{field:'x'}, value:{type:'param', param:'p'}}`).\n `params` are values the action collects from the caller (referenced by\n `{type:'param', param:'<name>'}` sources).\n- **Transition**: `{ name, title?, to, filter? }`. `to` must name a declared\n stage. `filter` is a GROQ condition gating the exit; omit it and it defaults\n to `$allTasksDone`.\n- **Field** (workflow- or stage-scoped persistent state): `{ type, name, title?, source }`.\n Common `type`s: `doc.ref`, `doc.refs`, `value.string`, `value.url`,\n `value.number`, `value.boolean`. `source` is where the value comes from:\n `{type:'init'}` (supplied when the instance starts), `{type:'write'}` (a user\n edits it), `{type:'param', param:'<actionParamName>'}`, `{type:'now'}`, `{type:'actor'}`.\n By convention a workflow has an `init`-sourced `doc.ref` named `subject` \u2014 the\n headline document it is about.\n\n## GROQ in conditions\n\nBuilt-in variables available in filters/predicates: `$allTasksDone`,\n`$anyTaskFailed` (booleans over the current stage's tasks), `$tasks` (the task\nlist), `$fields` (field values), `$now`, and the caller-scoped vars `$actor`\n(the acting user), `$assigned` (whether the caller is the task's assignee \u2014 the\nidiomatic permission gate, used as `filter: '$assigned'`), and `$can`. Define\nreusable named conditions under top-level `predicates: { name: '<groq>' }` and\nreference them as `$name` (e.g.\n`predicates: { ready: \"count($tasks[status != 'done']) == 0\" }` \u2192 `$ready`).\n\nConditions evaluate against an in-memory snapshot (the instance + its subject +\nfield-declared docs) \u2014 **never** scan by `_type` (e.g. `*[_type==\"article\"]`);\nthat is a discovery query and the validator rejects it. To bring a document into\nscope, declare a `doc.ref` field for it.\n\n## Sugars worth knowing\n\n- Action `status: 'done' | 'skipped' | 'failed'` \u2014 flips the firing task (shown above).\n- Omitted transition `filter` \u2014 defaults to `$allTasksDone`.\n- Omitted task `activation` \u2014 defaults to `'manual'`.\n\n## Modeling defaults\n\nValid is not the same as good. Prefer these unless the request says otherwise:\n\n- **A decline/reject loops back.** Route a rejected / changes-requested\n transition to an *earlier* stage for revision (e.g. `review \u2192 drafting` gated\n on `$anyTaskFailed`), not to a terminal stage. Reserve terminal stages for\n completion and for explicit cancellation/abandonment \u2014 a workflow should not\n dead-end just because something was declined.\n- **Prefer draft \u2192 review.** Model an author working in a drafting stage who\n submits, then a review stage that gates. Don't add more review stages unless\n the request asks for multiple approvers or rounds.\n- **When the shape is ambiguous, pick the conventional one and confirm** with the\n user rather than inventing extra stages.\n\n## Rules the validator enforces\n\n- Stage names, task names (per stage) and transition names are unique.\n- Every transition `to` and `initialStage` names a declared stage.\n- Custom `predicates` must not shadow a built-in (e.g. `allTasksDone`).\n- Every GROQ string must parse and must not be a `_type` discovery scan.", AUTHORING_GUIDE = `${ORIENTATION}
|
|
75
|
+
|
|
76
|
+
## Examples
|
|
77
|
+
|
|
78
|
+
### Example 1 \u2014 ${minimalExample.title} (minimal: one stage, one action)
|
|
79
|
+
\`\`\`json
|
|
80
|
+
${JSON.stringify(minimalExample, null, 2)}
|
|
81
|
+
\`\`\`
|
|
82
|
+
|
|
83
|
+
### Example 2 \u2014 ${reviewLoopExample.title} (review loop: reject routes back)
|
|
84
|
+
\`\`\`json
|
|
85
|
+
${JSON.stringify(reviewLoopExample, null, 2)}
|
|
86
|
+
\`\`\`
|
|
87
|
+
`, LIST_CAP = 25, TOOL_DESCRIPTORS = [
|
|
88
|
+
{
|
|
89
|
+
name: "list_workflow_instances",
|
|
90
|
+
description: "List workflow instances in the configured workspace. Use this when you need to find a workflow but don't already know its instance id, or to survey what's in flight. Returns a compact summary \u2014 id, workflow type id and human-readable `workflowTitle`, current stage, whether the instance is done, and (when the workflow has a conventional subject document) a `subject` field with the subject doc's ref and title. Use `workflowTitle` when the user names the workflow by type (e.g. \"article reviews\") and `subject.title` when they name a specific in-flight instance by what it's about (e.g. \"the article-review about pricing\"). Capped at " + String(25) + " results. Do NOT use this to inspect a single known instance \u2014 use get_workflow_state for that, the response will be richer.",
|
|
91
|
+
input_schema: {
|
|
92
|
+
type: "object",
|
|
93
|
+
properties: {
|
|
94
|
+
definition: {
|
|
95
|
+
type: "string",
|
|
96
|
+
description: "Optional. Restrict to instances of this workflow definition (e.g. 'article-review')."
|
|
97
|
+
},
|
|
98
|
+
status: {
|
|
99
|
+
type: "string",
|
|
100
|
+
enum: ["in_flight", "done", "any"],
|
|
101
|
+
description: "Optional. 'in_flight' returns instances not in a terminal stage; 'done' returns completed/aborted; 'any' returns both. Defaults to 'in_flight'."
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
additionalProperties: !1
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
name: "get_workflow_state",
|
|
109
|
+
description: "Get the current state of a single workflow instance, projected for action. Returns the workflow's id and human-readable `workflowTitle`, the current stage, the subject document the workflow is about (when the workflow has a conventional subject \u2014 its ref and title), every task on the current stage with its available actions (and whether each action is currently allowed), and the most recent history entries. Use this whenever you need to understand what's possible on an instance before deciding to act. This is a pure read \u2014 it does not change anything. If you only need to discover what instances exist, use list_workflow_instances instead; this tool requires you to know the instance id. list_workflow_instances also returns the same `workflowTitle` and `subject` fields, so prefer it for fan-out discovery rather than polling get_workflow_state per instance.",
|
|
110
|
+
input_schema: {
|
|
111
|
+
type: "object",
|
|
112
|
+
properties: {
|
|
113
|
+
instance_id: {
|
|
114
|
+
type: "string",
|
|
115
|
+
description: "The workflow instance id."
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
required: ["instance_id"],
|
|
119
|
+
additionalProperties: !1
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
name: "diagnose_workflow",
|
|
124
|
+
description: "Explain why a single workflow instance is or isn't progressing. Returns a verdict (`state`: progressing, waiting, blocked, completed, aborted, or stuck), a one-line `summary`, and \u2014 when stuck \u2014 a structured `cause` plus the `remediations` that would unstick it. Use this when an instance seems stalled or the user asks \"why isn't this moving?\": it distinguishes a healthy instance (waiting on a human, or will advance on its own) from a genuinely stuck one (a failed effect or task, a dead-end transition). This is a pure read \u2014 it changes nothing, and the remediations it names are advisory: none can be executed through this server. To actually advance a healthy waiting instance use fire_action; for per-task action detail use get_workflow_state.",
|
|
125
|
+
input_schema: {
|
|
126
|
+
type: "object",
|
|
127
|
+
properties: {
|
|
128
|
+
instance_id: {
|
|
129
|
+
type: "string",
|
|
130
|
+
description: "The workflow instance id."
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
required: ["instance_id"],
|
|
134
|
+
additionalProperties: !1
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
name: "fire_action",
|
|
139
|
+
description: "Advance a workflow instance by firing an action on one of its tasks. This is the only way to advance workflow state from the outside \u2014 there is no separate 'complete task' or 'transition stage' tool. To find the right (task, action) pair, call get_workflow_state first and pick from the allowed actions listed on the current stage's tasks. After firing, the engine cascades any auto-transitions that become eligible (so an 'approve' action on a review task may transition the workflow to a terminal stage in one shot). Returns the resulting state, same shape as get_workflow_state. If the action is not currently allowed (e.g. the task is already done, or a guard fails), this returns an error describing why.",
|
|
140
|
+
input_schema: {
|
|
141
|
+
type: "object",
|
|
142
|
+
properties: {
|
|
143
|
+
instance_id: {
|
|
144
|
+
type: "string",
|
|
145
|
+
description: "The workflow instance id."
|
|
146
|
+
},
|
|
147
|
+
task: {
|
|
148
|
+
type: "string",
|
|
149
|
+
description: "The id of the task on the current stage. Must be one of the tasks returned by get_workflow_state."
|
|
150
|
+
},
|
|
151
|
+
action: {
|
|
152
|
+
type: "string",
|
|
153
|
+
description: "The id of the action on that task. Must be one of the actions listed as allowed=true on the task."
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
required: ["instance_id", "task", "action"],
|
|
157
|
+
additionalProperties: !1
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
{
|
|
161
|
+
name: "get_workflow_authoring_guide",
|
|
162
|
+
description: "Get the guide for authoring a workflow definition: the DSL shape, the GROQ condition built-ins, the sugars, the rules the validator enforces, and two worked JSON examples. Call this BEFORE writing a definition from a description, then generate the JSON and check it with validate_workflow_definition. Pure read; takes no arguments.",
|
|
163
|
+
input_schema: {
|
|
164
|
+
type: "object",
|
|
165
|
+
properties: {},
|
|
166
|
+
additionalProperties: !1
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
{
|
|
170
|
+
name: "validate_workflow_definition",
|
|
171
|
+
description: "Validate a workflow definition you have authored. Runs the same checks as deploy \u2014 structural shape, cross-field invariants (e.g. every transition target is a declared stage), and GROQ syntax \u2014 without writing anything. Returns `{valid:true, definition}` where `definition` is the desugared form that would deploy, or `{valid:false, error}` with every problem listed and path-prefixed. This does NOT deploy \u2014 a human deploys the validated definition via the CLI. Call get_workflow_authoring_guide first for the shape; on `valid:false`, fix the reported problems and validate again.",
|
|
172
|
+
input_schema: {
|
|
173
|
+
type: "object",
|
|
174
|
+
properties: {
|
|
175
|
+
definition: {
|
|
176
|
+
type: "object",
|
|
177
|
+
description: "The workflow definition to validate, as a JSON object in authoring shape. See get_workflow_authoring_guide for the shape and examples."
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
required: ["definition"],
|
|
181
|
+
additionalProperties: !1
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
], SUBJECT_ENTRY_NAME = "subject";
|
|
185
|
+
function getSubjectGdr(instance) {
|
|
186
|
+
const entry = instance.fields.find((s) => s._type === "doc.ref" && s.name === SUBJECT_ENTRY_NAME);
|
|
187
|
+
if (!(entry === void 0 || entry._type !== "doc.ref"))
|
|
188
|
+
return entry.value?.id;
|
|
189
|
+
}
|
|
190
|
+
async function fetchSubjectTitles(engine, instances) {
|
|
191
|
+
const docIdToGdr = /* @__PURE__ */ new Map();
|
|
192
|
+
for (const inst of instances) {
|
|
193
|
+
const gdr = getSubjectGdr(inst);
|
|
194
|
+
if (gdr !== void 0)
|
|
195
|
+
try {
|
|
196
|
+
docIdToGdr.set(extractDocumentId(gdr), gdr);
|
|
197
|
+
} catch {
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (docIdToGdr.size === 0) return /* @__PURE__ */ new Map();
|
|
201
|
+
let docs;
|
|
202
|
+
try {
|
|
203
|
+
docs = await engine.client.fetch(
|
|
204
|
+
"*[_id in $docIds]{_id, title}",
|
|
205
|
+
{ docIds: Array.from(docIdToGdr.keys()) }
|
|
206
|
+
);
|
|
207
|
+
} catch (err) {
|
|
208
|
+
return process.stderr.write(
|
|
209
|
+
`workflow-mcp: subject-title lookup failed; returning refs without titles: ${err instanceof Error ? err.message : String(err)}
|
|
210
|
+
`
|
|
211
|
+
), /* @__PURE__ */ new Map();
|
|
212
|
+
}
|
|
213
|
+
const out = /* @__PURE__ */ new Map();
|
|
214
|
+
for (const doc of docs) {
|
|
215
|
+
const gdr = docIdToGdr.get(doc._id);
|
|
216
|
+
gdr !== void 0 && typeof doc.title == "string" && doc.title !== "" && out.set(gdr, doc.title);
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
}
|
|
220
|
+
function buildSubject(instance, subjectTitles) {
|
|
221
|
+
const gdr = getSubjectGdr(instance);
|
|
222
|
+
if (gdr === void 0) return;
|
|
223
|
+
const title = subjectTitles.get(gdr);
|
|
224
|
+
return title !== void 0 ? { ref: gdr, title } : { ref: gdr };
|
|
225
|
+
}
|
|
226
|
+
function projectSummary(doc, subjectTitles) {
|
|
227
|
+
const definition = JSON.parse(doc.definitionSnapshot), stageTitle = definition.stages.find((s) => s.name === doc.currentStage)?.title, workflowTitle = definition.title, subject = buildSubject(doc, subjectTitles);
|
|
228
|
+
return {
|
|
229
|
+
instanceId: doc._id,
|
|
230
|
+
definition: doc.definition,
|
|
231
|
+
...workflowTitle !== void 0 ? { workflowTitle } : {},
|
|
232
|
+
currentStage: doc.currentStage,
|
|
233
|
+
...stageTitle !== void 0 ? { currentStageTitle: stageTitle } : {},
|
|
234
|
+
lastChangedAt: doc.lastChangedAt,
|
|
235
|
+
done: isInstanceDone(doc),
|
|
236
|
+
...subject !== void 0 ? { subject } : {}
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
function projectState(instance, evaluation, subjectTitles) {
|
|
240
|
+
const workflowTitle = JSON.parse(instance.definitionSnapshot).title, stageTitle = evaluation.currentStage.stage.title, tasks = evaluation.currentStage.tasks.map((te) => {
|
|
241
|
+
const actions = te.actions.map((ae) => {
|
|
242
|
+
const verdict = actionVerdict(te, ae);
|
|
243
|
+
return {
|
|
244
|
+
action: verdict.action,
|
|
245
|
+
...verdict.title !== void 0 ? { title: verdict.title } : {},
|
|
246
|
+
allowed: verdict.allowed,
|
|
247
|
+
...verdict.allowed === !1 && verdict.disabledReason !== void 0 ? { disabledReason: formatDisabledReason(verdict.disabledReason) } : {}
|
|
248
|
+
};
|
|
249
|
+
});
|
|
250
|
+
return {
|
|
251
|
+
task: te.task.name,
|
|
252
|
+
...te.task.title !== void 0 ? { title: te.task.title } : {},
|
|
253
|
+
...te.task.description !== void 0 ? { description: te.task.description } : {},
|
|
254
|
+
status: te.status,
|
|
255
|
+
actions
|
|
256
|
+
};
|
|
257
|
+
}), recentHistory = instance.history.slice(-8).toReversed().map((entry) => ({
|
|
258
|
+
at: entry.at,
|
|
259
|
+
type: entry._type,
|
|
260
|
+
summary: summariseHistoryEntry(entry)
|
|
261
|
+
})), subject = buildSubject(instance, subjectTitles);
|
|
262
|
+
return {
|
|
263
|
+
instanceId: instance._id,
|
|
264
|
+
definition: instance.definition,
|
|
265
|
+
...workflowTitle !== void 0 ? { workflowTitle } : {},
|
|
266
|
+
currentStage: instance.currentStage,
|
|
267
|
+
...stageTitle !== void 0 ? { currentStageTitle: stageTitle } : {},
|
|
268
|
+
done: isInstanceDone(instance),
|
|
269
|
+
...subject !== void 0 ? { subject } : {},
|
|
270
|
+
tasks,
|
|
271
|
+
recentHistory
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
function isInstanceDone(instance) {
|
|
275
|
+
if (instance.completedAt !== void 0) return !0;
|
|
276
|
+
try {
|
|
277
|
+
const stage = JSON.parse(instance.definitionSnapshot).stages.find((s) => s.name === instance.currentStage);
|
|
278
|
+
return stage !== void 0 && isTerminalStage(stage);
|
|
279
|
+
} catch {
|
|
280
|
+
return !1;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
const DISABLED_REASON_TEXT = {
|
|
284
|
+
"filter-failed": "action's filter condition did not hold for this actor",
|
|
285
|
+
"task-not-active": "task is not currently active",
|
|
286
|
+
"stage-terminal": "stage is terminal \u2014 no further actions possible",
|
|
287
|
+
"instance-completed": "instance has already completed",
|
|
288
|
+
"requirements-unmet": "task's declared requirements are not yet satisfied"
|
|
289
|
+
};
|
|
290
|
+
function formatDisabledReason(reason) {
|
|
291
|
+
return DISABLED_REASON_TEXT[reason.kind] ?? reason.kind.replace(/-/g, " ");
|
|
292
|
+
}
|
|
293
|
+
function summariseHistoryEntry(entry) {
|
|
294
|
+
switch (entry._type) {
|
|
295
|
+
case "stageEntered":
|
|
296
|
+
return `entered stage "${String(entry.stage)}"`;
|
|
297
|
+
case "stageExited":
|
|
298
|
+
return `exited stage "${String(entry.stage)}" \u2192 "${String(entry.toStage)}"`;
|
|
299
|
+
case "taskActivated":
|
|
300
|
+
return `task "${String(entry.task)}" activated`;
|
|
301
|
+
case "taskStatusChanged":
|
|
302
|
+
return `task "${String(entry.task)}" status: ${String(entry.from)} \u2192 ${String(entry.to)}`;
|
|
303
|
+
case "actionFired":
|
|
304
|
+
return `action "${String(entry.action)}" fired on task "${String(entry.task)}"`;
|
|
305
|
+
case "transitionFired":
|
|
306
|
+
return `transition fired: "${String(entry.fromStage)}" \u2192 "${String(entry.toStage)}"`;
|
|
307
|
+
case "effectQueued":
|
|
308
|
+
return `effect "${String(entry.effect)}" queued`;
|
|
309
|
+
case "effectCompleted":
|
|
310
|
+
return `effect "${String(entry.effect)}" completed (${String(entry.status)})`;
|
|
311
|
+
case "spawned":
|
|
312
|
+
return `spawned child workflow from task "${String(entry.task)}"`;
|
|
313
|
+
default:
|
|
314
|
+
return entry._type;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
function diagnosisSummary(diagnosis) {
|
|
318
|
+
switch (diagnosis.state) {
|
|
319
|
+
case "progressing":
|
|
320
|
+
return "This instance will advance on its own.";
|
|
321
|
+
case "waiting":
|
|
322
|
+
return `Waiting for action on task "${diagnosis.task}": ${diagnosis.actions.join(" or ")}. This is the normal in-flight state \u2014 it advances when someone acts.`;
|
|
323
|
+
case "blocked":
|
|
324
|
+
return `Task "${diagnosis.task}" is visible but not yet executable \u2014 unmet requirement(s): ${diagnosis.requirements.join(", ")}. It will not advance until those are satisfied.`;
|
|
325
|
+
case "completed":
|
|
326
|
+
return `Completed at ${diagnosis.at}.`;
|
|
327
|
+
case "aborted":
|
|
328
|
+
return diagnosis.reason !== void 0 ? `Aborted at ${diagnosis.at}: ${diagnosis.reason}.` : `Aborted at ${diagnosis.at}.`;
|
|
329
|
+
case "stuck":
|
|
330
|
+
return stuckSummary(diagnosis.cause);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
function stuckSummary(cause) {
|
|
334
|
+
switch (cause.kind) {
|
|
335
|
+
case "failed-effect":
|
|
336
|
+
return `Stuck: a failed effect "${cause.effect.name}" is blocking task "${cause.effect.origin.name}", which can't complete until the effect succeeds.`;
|
|
337
|
+
case "hung-effect":
|
|
338
|
+
return `Stuck: effect "${cause.effect.name}" was claimed but never completed \u2014 the drainer likely died mid-dispatch, so it won't drain on its own.`;
|
|
339
|
+
case "failed-task":
|
|
340
|
+
return `Stuck: task "${cause.task}" is in a terminal failed state, so any exit transition gated on it can never fire.`;
|
|
341
|
+
case "no-transition-fires":
|
|
342
|
+
return "Stuck: every task is resolved but no exit transition's filter is satisfied \u2014 likely a routing state value a filter reads was never written.";
|
|
343
|
+
case "transition-unevaluable":
|
|
344
|
+
return `Stuck (recoverable): exit transition(s) ${cause.transitions.join(", ")} read an operand that is missing or unreadable (GROQ null). It advances on its own once that data becomes readable \u2014 no manual fix needed.`;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
function buildTools(engine, options = {}) {
|
|
348
|
+
const accessOverride = options.access;
|
|
349
|
+
return { descriptors: TOOL_DESCRIPTORS, impls: {
|
|
350
|
+
list_workflow_instances: async (rawInput) => {
|
|
351
|
+
const input = parseListInput(rawInput);
|
|
352
|
+
return listInstances(engine, input);
|
|
353
|
+
},
|
|
354
|
+
get_workflow_state: async (rawInput) => {
|
|
355
|
+
const input = parseInstanceIdInput(rawInput, "get_workflow_state");
|
|
356
|
+
return getInstanceState(engine, input.instance_id, accessOverride);
|
|
357
|
+
},
|
|
358
|
+
diagnose_workflow: async (rawInput) => {
|
|
359
|
+
const input = parseInstanceIdInput(rawInput, "diagnose_workflow");
|
|
360
|
+
return getInstanceDiagnosis(engine, input.instance_id, accessOverride);
|
|
361
|
+
},
|
|
362
|
+
fire_action: async (rawInput) => {
|
|
363
|
+
const input = parseFireActionInput(rawInput);
|
|
364
|
+
return await engine.fireAction({
|
|
365
|
+
instanceId: input.instance_id,
|
|
366
|
+
task: input.task,
|
|
367
|
+
action: input.action,
|
|
368
|
+
...accessOverride !== void 0 ? { access: accessOverride } : {}
|
|
369
|
+
}), getInstanceState(engine, input.instance_id, accessOverride);
|
|
370
|
+
},
|
|
371
|
+
// Authoring tools — engine-independent: they teach and check the DSL, they
|
|
372
|
+
// don't touch the lake or an instance.
|
|
373
|
+
get_workflow_authoring_guide: async () => AUTHORING_GUIDE,
|
|
374
|
+
validate_workflow_definition: async (rawInput) => {
|
|
375
|
+
const { definition } = parseValidateInput(rawInput);
|
|
376
|
+
try {
|
|
377
|
+
const stored = defineWorkflow(definition);
|
|
378
|
+
return validateDefinition(stored), { valid: !0, definition: stored };
|
|
379
|
+
} catch (err) {
|
|
380
|
+
return { valid: !1, error: err instanceof Error ? err.message : String(err) };
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
} };
|
|
384
|
+
}
|
|
385
|
+
function parseListInput(raw) {
|
|
386
|
+
if (raw === null || typeof raw != "object")
|
|
387
|
+
return { status: "in_flight" };
|
|
388
|
+
const obj = raw, status = obj.status === "done" || obj.status === "any" ? obj.status : "in_flight", definition = typeof obj.definition == "string" ? obj.definition : void 0;
|
|
389
|
+
return definition !== void 0 ? { definition, status } : { status };
|
|
390
|
+
}
|
|
391
|
+
function parseValidateInput(raw) {
|
|
392
|
+
if (raw === null || typeof raw != "object")
|
|
393
|
+
throw new Error("validate_workflow_definition: input must be an object");
|
|
394
|
+
const obj = raw;
|
|
395
|
+
if (obj.definition === null || typeof obj.definition != "object")
|
|
396
|
+
throw new Error("validate_workflow_definition: `definition` is required and must be an object");
|
|
397
|
+
return { definition: obj.definition };
|
|
398
|
+
}
|
|
399
|
+
function parseInstanceIdInput(raw, tool) {
|
|
400
|
+
if (raw === null || typeof raw != "object")
|
|
401
|
+
throw new Error(`${tool}: input must be an object`);
|
|
402
|
+
const obj = raw;
|
|
403
|
+
if (typeof obj.instance_id != "string" || obj.instance_id === "")
|
|
404
|
+
throw new Error(`${tool}: instance_id is required`);
|
|
405
|
+
return { instance_id: obj.instance_id };
|
|
406
|
+
}
|
|
407
|
+
function parseFireActionInput(raw) {
|
|
408
|
+
if (raw === null || typeof raw != "object")
|
|
409
|
+
throw new Error("fire_action: input must be an object");
|
|
410
|
+
const obj = raw;
|
|
411
|
+
for (const key of ["instance_id", "task", "action"])
|
|
412
|
+
if (typeof obj[key] != "string" || obj[key] === "")
|
|
413
|
+
throw new Error(`fire_action: ${key} is required`);
|
|
414
|
+
return {
|
|
415
|
+
instance_id: obj.instance_id,
|
|
416
|
+
task: obj.task,
|
|
417
|
+
action: obj.action
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
async function listInstances(engine, input) {
|
|
421
|
+
const groqParts = [`_type == "${WORKFLOW_INSTANCE_TYPE}"`];
|
|
422
|
+
input.definition !== void 0 && groqParts.push("definition == $definition");
|
|
423
|
+
const groq = `*[${groqParts.join(" && ")} && ${tagScopeFilter()}] | order(lastChangedAt desc)[0...${LIST_CAP}]`, params = {};
|
|
424
|
+
input.definition !== void 0 && (params.definition = input.definition);
|
|
425
|
+
const filtered = (await engine.query({ groq, params })).filter((doc) => {
|
|
426
|
+
const done = isInstanceDone(doc);
|
|
427
|
+
return input.status === "done" ? done : input.status === "in_flight" ? !done : !0;
|
|
428
|
+
}), subjectTitles = await fetchSubjectTitles(engine, filtered);
|
|
429
|
+
return {
|
|
430
|
+
instances: filtered.map((doc) => projectSummary(doc, subjectTitles))
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
async function getInstanceState(engine, instanceId, accessOverride) {
|
|
434
|
+
const evaluation = await engine.evaluateInstance({
|
|
435
|
+
instanceId,
|
|
436
|
+
...accessOverride !== void 0 ? { access: accessOverride } : {}
|
|
437
|
+
}), instance = await engine.getInstance({ instanceId }), subjectTitles = await fetchSubjectTitles(engine, [instance]);
|
|
438
|
+
return projectState(instance, evaluation, subjectTitles);
|
|
439
|
+
}
|
|
440
|
+
async function getInstanceDiagnosis(engine, instanceId, accessOverride) {
|
|
441
|
+
const { diagnosis, remediations } = await engine.diagnose({
|
|
442
|
+
instanceId,
|
|
443
|
+
...accessOverride !== void 0 ? { access: accessOverride } : {}
|
|
444
|
+
});
|
|
445
|
+
return {
|
|
446
|
+
instanceId,
|
|
447
|
+
state: diagnosis.state,
|
|
448
|
+
summary: diagnosisSummary(diagnosis),
|
|
449
|
+
...diagnosis.state === "stuck" ? { cause: diagnosis.cause.kind } : {},
|
|
450
|
+
remediations
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
export {
|
|
454
|
+
buildTools
|
|
455
|
+
};
|
|
456
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/authoring-guide.ts","../src/descriptors.ts","../src/projection.ts","../src/tools.ts"],"sourcesContent":["/**\n * Content for the `get_workflow_authoring_guide` tool.\n *\n * The agent calling the MCP server generates the workflow definition; this\n * guide is what teaches it the DSL well enough to do that on the first pass.\n * It is the orientation the examples can't convey on their own (the GROQ\n * built-ins, the sugars, the hard rules) plus two worked examples.\n *\n * The examples are kept inline (rather than imported from\n * `@sanity/workflow-examples`) on purpose: that package exports the *desugared*\n * `WorkflowDefinition` (the post-`defineWorkflow` shape), but an agent should emit\n * the *authoring* (sugar) shape — JSON, exactly what `validate_workflow_definition`\n * accepts — so importing the examples would show the wrong shape. Keeping them\n * inline also avoids promoting `@sanity/workflow-examples` to a runtime dependency\n * of a package headed for host embedding. The companion test runs every example\n * through the real validators, so a stale snippet fails CI rather than misleading\n * an agent.\n */\n\nimport type {AuthoringWorkflow} from '@sanity/workflow-engine'\n\nconst minimalExample = {\n name: 'quick-approval',\n version: 1,\n title: 'Quick approval',\n description: 'One review stage with a single approve action, then a terminal stage.',\n initialStage: 'review',\n fields: [{type: 'doc.ref', name: 'subject', title: 'Document', source: {type: 'init'}}],\n stages: [\n {\n name: 'review',\n title: 'Review',\n tasks: [\n {\n name: 'decide',\n title: 'Decide',\n activation: 'auto',\n actions: [{name: 'approve', title: 'Approve', status: 'done'}],\n },\n ],\n transitions: [{name: 'to-approved', title: 'Approve and finish', to: 'approved'}],\n },\n {name: 'approved', title: 'Approved', description: 'Terminal — no transitions out.'},\n ],\n} satisfies AuthoringWorkflow\n\nconst reviewLoopExample = {\n name: 'doc-review',\n version: 1,\n title: 'Document review',\n description: 'Draft, then editorial review that approves or rejects back to drafting.',\n initialStage: 'drafting',\n fields: [{type: 'doc.ref', name: 'subject', title: 'Document', source: {type: 'init'}}],\n stages: [\n {\n name: 'drafting',\n title: 'Drafting',\n tasks: [\n {\n name: 'write',\n title: 'Write the draft',\n activation: 'auto',\n actions: [{name: 'submit', title: 'Submit for review', status: 'done'}],\n },\n ],\n transitions: [{name: 'to-review', title: 'Send to review', to: 'review'}],\n },\n {\n name: 'review',\n title: 'Editorial review',\n tasks: [\n {\n name: 'review',\n title: 'Review the draft',\n activation: 'auto',\n actions: [\n {name: 'approve', title: 'Approve', status: 'done'},\n {name: 'reject', title: 'Reject', status: 'failed'},\n ],\n },\n ],\n transitions: [\n {name: 'to-approved', title: 'Approve and finish', to: 'approved'},\n // Reject flips the task to `failed`; this routes the instance back.\n {\n name: 'to-drafting',\n title: 'Send back to drafting',\n to: 'drafting',\n filter: '$anyTaskFailed',\n },\n ],\n },\n {name: 'approved', title: 'Approved', description: 'Terminal — no transitions out.'},\n ],\n} satisfies AuthoringWorkflow\n\n/**\n * Worked examples included verbatim in {@link AUTHORING_GUIDE}, and exercised by\n * the drift-guard test. Authoring (sugar) shape — what an agent passes to\n * `validate_workflow_definition`.\n */\nexport const GUIDE_EXAMPLES: AuthoringWorkflow[] = [minimalExample, reviewLoopExample]\n\nconst ORIENTATION = `# Authoring a workflow definition\n\nA workflow definition is a plain JSON object. There is no code in it — every\ncondition (filters, predicates, guards) is a GROQ *string*. Generate the JSON,\nthen call \\`validate_workflow_definition\\` to check it; fix the reported errors\nand re-validate until it returns \\`valid: true\\`. The validator returns the\n*desugared* definition under \\`definition\\` — that is exactly what would deploy.\n\n## Shape\n\n- **Workflow**: \\`{ name, version (positive int), title, description?, initialStage, fields?, stages[], predicates? }\\`.\n \\`initialStage\\` must be the \\`name\\` of a declared stage.\n- **Stage**: \\`{ name, title?, description?, tasks?, transitions? }\\`. A stage with\n no transitions is terminal. Reaching a terminal stage ends the workflow.\n- **Task**: \\`{ name, title?, activation?, actions? }\\`. \\`activation\\` is \\`'auto'\\`\n (starts when the stage is entered) or \\`'manual'\\` (default — a human starts it).\n- **Action**: \\`{ name, title?, status?, params?, ops? }\\`.\n \\`status: 'done' | 'skipped' | 'failed'\\` is sugar that flips the *firing task* to\n that status when the action fires. \\`ops\\` are mutations applied when the action\n fires (e.g. \\`{type:'field.set', target:{field:'x'}, value:{type:'param', param:'p'}}\\`).\n \\`params\\` are values the action collects from the caller (referenced by\n \\`{type:'param', param:'<name>'}\\` sources).\n- **Transition**: \\`{ name, title?, to, filter? }\\`. \\`to\\` must name a declared\n stage. \\`filter\\` is a GROQ condition gating the exit; omit it and it defaults\n to \\`$allTasksDone\\`.\n- **Field** (workflow- or stage-scoped persistent state): \\`{ type, name, title?, source }\\`.\n Common \\`type\\`s: \\`doc.ref\\`, \\`doc.refs\\`, \\`value.string\\`, \\`value.url\\`,\n \\`value.number\\`, \\`value.boolean\\`. \\`source\\` is where the value comes from:\n \\`{type:'init'}\\` (supplied when the instance starts), \\`{type:'write'}\\` (a user\n edits it), \\`{type:'param', param:'<actionParamName>'}\\`, \\`{type:'now'}\\`, \\`{type:'actor'}\\`.\n By convention a workflow has an \\`init\\`-sourced \\`doc.ref\\` named \\`subject\\` — the\n headline document it is about.\n\n## GROQ in conditions\n\nBuilt-in variables available in filters/predicates: \\`$allTasksDone\\`,\n\\`$anyTaskFailed\\` (booleans over the current stage's tasks), \\`$tasks\\` (the task\nlist), \\`$fields\\` (field values), \\`$now\\`, and the caller-scoped vars \\`$actor\\`\n(the acting user), \\`$assigned\\` (whether the caller is the task's assignee — the\nidiomatic permission gate, used as \\`filter: '$assigned'\\`), and \\`$can\\`. Define\nreusable named conditions under top-level \\`predicates: { name: '<groq>' }\\` and\nreference them as \\`$name\\` (e.g.\n\\`predicates: { ready: \"count($tasks[status != 'done']) == 0\" }\\` → \\`$ready\\`).\n\nConditions evaluate against an in-memory snapshot (the instance + its subject +\nfield-declared docs) — **never** scan by \\`_type\\` (e.g. \\`*[_type==\"article\"]\\`);\nthat is a discovery query and the validator rejects it. To bring a document into\nscope, declare a \\`doc.ref\\` field for it.\n\n## Sugars worth knowing\n\n- Action \\`status: 'done' | 'skipped' | 'failed'\\` — flips the firing task (shown above).\n- Omitted transition \\`filter\\` — defaults to \\`$allTasksDone\\`.\n- Omitted task \\`activation\\` — defaults to \\`'manual'\\`.\n\n## Modeling defaults\n\nValid is not the same as good. Prefer these unless the request says otherwise:\n\n- **A decline/reject loops back.** Route a rejected / changes-requested\n transition to an *earlier* stage for revision (e.g. \\`review → drafting\\` gated\n on \\`$anyTaskFailed\\`), not to a terminal stage. Reserve terminal stages for\n completion and for explicit cancellation/abandonment — a workflow should not\n dead-end just because something was declined.\n- **Prefer draft → review.** Model an author working in a drafting stage who\n submits, then a review stage that gates. Don't add more review stages unless\n the request asks for multiple approvers or rounds.\n- **When the shape is ambiguous, pick the conventional one and confirm** with the\n user rather than inventing extra stages.\n\n## Rules the validator enforces\n\n- Stage names, task names (per stage) and transition names are unique.\n- Every transition \\`to\\` and \\`initialStage\\` names a declared stage.\n- Custom \\`predicates\\` must not shadow a built-in (e.g. \\`allTasksDone\\`).\n- Every GROQ string must parse and must not be a \\`_type\\` discovery scan.`\n\n/**\n * The full text returned by `get_workflow_authoring_guide`: orientation plus the\n * two worked examples rendered as JSON.\n */\nexport const AUTHORING_GUIDE = `${ORIENTATION}\n\n## Examples\n\n### Example 1 — ${minimalExample.title} (minimal: one stage, one action)\n\\`\\`\\`json\n${JSON.stringify(minimalExample, null, 2)}\n\\`\\`\\`\n\n### Example 2 — ${reviewLoopExample.title} (review loop: reject routes back)\n\\`\\`\\`json\n${JSON.stringify(reviewLoopExample, null, 2)}\n\\`\\`\\`\n`\n","/**\n * The MCP tool surface for workflow operations — the static descriptors an\n * agent reads to decide what to call. The implementations live in `tools.ts`;\n * these are pure data (descriptions + JSON schemas) and safe to cache.\n *\n * Two jobs: operate running instances, and author new definitions.\n *\n * Operate an instance:\n *\n * - `list_workflow_instances` is the only way to *discover* what's\n * running without already knowing an id. Filterable, capped.\n * - `get_workflow_state` is the \"tell me everything actionable about\n * one instance\" call. It composes the engine's `evaluate` projection\n * into a flat shape an LLM can reason over without piecing together\n * raw `WorkflowInstance` documents.\n * - `diagnose_workflow` answers \"*why* isn't this moving?\" — it\n * classifies an instance as healthy (waiting/progressing) or genuinely\n * stuck (a failed effect/task, a dead-end transition) and names the\n * remediations that would unstick it. A pure read; the remediations are\n * advisory (none execute through this server).\n * - `fire_action` is the only write. Mirrors the engine's universal\n * \"something happened\" entry point — everything other than admin\n * override flows through it.\n *\n * Author a definition (both pure, engine-independent, neither deploys):\n *\n * - `get_workflow_authoring_guide` returns the DSL guide an agent reads\n * before writing a definition — shape, GROQ built-ins, sugars, examples.\n * - `validate_workflow_definition` runs the deploy-time checks (structure +\n * invariants + GROQ) and returns the desugared definition or a\n * path-prefixed error list. A human deploys it via the CLI.\n *\n * Surface choices that matter for an LLM consumer:\n *\n * - Descriptions are written for an agent, not a human reader.\n * Each one says (a) what the tool does, (b) when to use it,\n * (c) what *not* to use it for.\n * - Parameter names use snake_case, matching MCP convention.\n * - The write tool's description spells out that this is the way\n * to advance workflow state — not a side door. Without that line,\n * an LLM tends to look for a `complete_task` or `set_stage` tool.\n * - Read tools cap their output. A 50-page `recent_history` would\n * burn context and is rarely informative; 8 is enough to spot\n * loops or stuck-in-stage patterns.\n */\n\n/**\n * The descriptor shape the Anthropic Messages API + the MCP SDK both\n * accept. Kept here as a small, transport-neutral interface so we can\n * feed the same descriptors to either consumer.\n */\nexport interface ToolDescriptor {\n name: string\n description: string\n /** JSON Schema describing the tool's parameters. */\n input_schema: {\n type: 'object'\n properties: Record<string, unknown>\n required?: string[]\n additionalProperties?: boolean\n }\n}\n\n/** Maximum instances returned by list_workflow_instances. */\nexport const LIST_CAP = 25\n\n/**\n * The static tool descriptors. Independent of any engine — the bound\n * implementations that close over an engine live in {@link buildTools}.\n */\nexport const TOOL_DESCRIPTORS: ToolDescriptor[] = [\n {\n name: 'list_workflow_instances',\n description:\n 'List workflow instances in the configured workspace. Use this when you need ' +\n \"to find a workflow but don't already know its instance id, or to survey \" +\n \"what's in flight. Returns a compact summary — id, workflow type id and \" +\n 'human-readable `workflowTitle`, current stage, whether the instance is done, ' +\n 'and (when the workflow has a conventional subject document) a `subject` ' +\n \"field with the subject doc's ref and title. Use `workflowTitle` when the \" +\n 'user names the workflow by type (e.g. \"article reviews\") and `subject.title` ' +\n \"when they name a specific in-flight instance by what it's about (e.g. \" +\n '\"the article-review about pricing\"). ' +\n 'Capped at ' +\n String(LIST_CAP) +\n ' results. ' +\n 'Do NOT use this to inspect a single known instance — use get_workflow_state ' +\n 'for that, the response will be richer.',\n input_schema: {\n type: 'object',\n properties: {\n definition: {\n type: 'string',\n description:\n \"Optional. Restrict to instances of this workflow definition (e.g. 'article-review').\",\n },\n status: {\n type: 'string',\n enum: ['in_flight', 'done', 'any'],\n description:\n \"Optional. 'in_flight' returns instances not in a terminal stage; \" +\n \"'done' returns completed/aborted; 'any' returns both. Defaults to 'in_flight'.\",\n },\n },\n additionalProperties: false,\n },\n },\n {\n name: 'get_workflow_state',\n description:\n 'Get the current state of a single workflow instance, projected for action. ' +\n \"Returns the workflow's id and human-readable `workflowTitle`, the current \" +\n 'stage, the subject document the workflow is about (when the workflow has a ' +\n 'conventional subject — its ref and title), every task on the current stage ' +\n 'with its available actions (and whether each action is currently allowed), ' +\n 'and the most recent history entries. Use this whenever you need to understand ' +\n \"what's possible on an instance before deciding to act. \" +\n 'This is a pure read — it does not change anything. ' +\n 'If you only need to discover what instances exist, use list_workflow_instances ' +\n 'instead; this tool requires you to know the instance id. ' +\n 'list_workflow_instances also returns the same `workflowTitle` and `subject` ' +\n 'fields, so prefer it for fan-out discovery rather than polling ' +\n 'get_workflow_state per instance.',\n input_schema: {\n type: 'object',\n properties: {\n instance_id: {\n type: 'string',\n description: 'The workflow instance id.',\n },\n },\n required: ['instance_id'],\n additionalProperties: false,\n },\n },\n {\n name: 'diagnose_workflow',\n description:\n \"Explain why a single workflow instance is or isn't progressing. Returns a \" +\n 'verdict (`state`: progressing, waiting, blocked, completed, aborted, or ' +\n 'stuck), a one-line `summary`, and — when stuck — a structured `cause` plus ' +\n 'the `remediations` that would unstick it. Use this when an instance seems ' +\n 'stalled or the user asks \"why isn\\'t this moving?\": it distinguishes a healthy ' +\n 'instance (waiting on a human, or will advance on its own) from a genuinely ' +\n 'stuck one (a failed effect or task, a dead-end transition). ' +\n 'This is a pure read — it changes nothing, and the remediations it names are ' +\n 'advisory: none can be executed through this server. To actually advance a ' +\n 'healthy waiting instance use fire_action; for per-task action detail use ' +\n 'get_workflow_state.',\n input_schema: {\n type: 'object',\n properties: {\n instance_id: {\n type: 'string',\n description: 'The workflow instance id.',\n },\n },\n required: ['instance_id'],\n additionalProperties: false,\n },\n },\n {\n name: 'fire_action',\n description:\n 'Advance a workflow instance by firing an action on one of its tasks. ' +\n 'This is the only way to advance workflow state from the outside — there is no ' +\n \"separate 'complete task' or 'transition stage' tool. To find the right \" +\n '(task, action) pair, call get_workflow_state first and pick from the ' +\n \"allowed actions listed on the current stage's tasks. \" +\n 'After firing, the engine cascades any auto-transitions that become eligible ' +\n \"(so an 'approve' action on a review task may transition the workflow to a \" +\n 'terminal stage in one shot). Returns the resulting state, same shape as ' +\n 'get_workflow_state. ' +\n 'If the action is not currently allowed (e.g. the task is already done, or a ' +\n 'guard fails), this returns an error describing why.',\n input_schema: {\n type: 'object',\n properties: {\n instance_id: {\n type: 'string',\n description: 'The workflow instance id.',\n },\n task: {\n type: 'string',\n description:\n 'The id of the task on the current stage. Must be one of the tasks ' +\n 'returned by get_workflow_state.',\n },\n action: {\n type: 'string',\n description:\n 'The id of the action on that task. Must be one of the actions listed ' +\n 'as allowed=true on the task.',\n },\n },\n required: ['instance_id', 'task', 'action'],\n additionalProperties: false,\n },\n },\n {\n name: 'get_workflow_authoring_guide',\n description:\n 'Get the guide for authoring a workflow definition: the DSL shape, the ' +\n 'GROQ condition built-ins, the sugars, the rules the validator enforces, ' +\n 'and two worked JSON examples. Call this BEFORE writing a definition from ' +\n 'a description, then generate the JSON and check it with ' +\n 'validate_workflow_definition. Pure read; takes no arguments.',\n input_schema: {\n type: 'object',\n properties: {},\n additionalProperties: false,\n },\n },\n {\n name: 'validate_workflow_definition',\n description:\n 'Validate a workflow definition you have authored. Runs the same checks as ' +\n 'deploy — structural shape, cross-field invariants (e.g. every transition ' +\n 'target is a declared stage), and GROQ syntax — without writing anything. ' +\n 'Returns `{valid:true, definition}` where `definition` is the desugared form ' +\n 'that would deploy, or `{valid:false, error}` with every problem listed and ' +\n 'path-prefixed. This does NOT deploy — a human deploys the validated ' +\n 'definition via the CLI. Call get_workflow_authoring_guide first for the ' +\n 'shape; on `valid:false`, fix the reported problems and validate again.',\n input_schema: {\n type: 'object',\n properties: {\n definition: {\n type: 'object',\n description:\n 'The workflow definition to validate, as a JSON object in authoring ' +\n 'shape. See get_workflow_authoring_guide for the shape and examples.',\n },\n },\n required: ['definition'],\n additionalProperties: false,\n },\n },\n]\n","/**\n * Projection helpers — engine output shaped for an LLM consumer.\n *\n * Why a hand-written projection rather than returning the engine's\n * `WorkflowEvaluation` raw: the LLM only needs (a) which tasks exist,\n * (b) which actions are allowed on each, (c) why an action is denied\n * when it is. The evaluation includes per-stage field-entry resolution\n * and snapshot bookkeeping that bloats the payload without helping\n * the model pick the right next move.\n *\n * The engine reads that feed these live in `tools.ts`; this module is\n * pure shaping plus the one batched subject-title lookup they all share.\n */\n\nimport {\n actionVerdict,\n extractDocumentId,\n isTerminalStage,\n type Diagnosis,\n type Engine,\n type StuckCause,\n type WorkflowDefinition,\n type WorkflowEvaluation,\n type WorkflowInstance,\n} from '@sanity/workflow-engine'\n\nimport type {\n ProjectedActionVerdict,\n ProjectedHistoryEntry,\n ProjectedInstanceState,\n ProjectedInstanceSummary,\n ProjectedSubject,\n ProjectedTask,\n} from './types.ts'\n\n/**\n * The field-entry name we treat as the workflow's \"subject\" — the headline\n * doc the workflow is about. Convention-only (see ProjectedSubject docs);\n * a workflow without an entry with this name won't have `subject` populated\n * on the projection.\n */\nconst SUBJECT_ENTRY_NAME = 'subject'\n\n/** Maximum history entries returned in get_workflow_state. */\nconst HISTORY_CAP = 8\n\n// Subject doc resolution\n//\n// The conventional \"subject\" entry holds a doc.ref to the thing the\n// workflow is about. The entry value is a GDR URI (e.g.\n// `dataset:proj:ds:article-1`) — what `_id` in the store actually\n// uses is the bare `article-1` part. Extract, batch-fetch by id list,\n// build a Map keyed by GDR URI.\n//\n// Known gap: cross-resource subject docs. If the subject lives in a\n// different Sanity resource than the engine's own workflowResource,\n// this lookup misses — the engine's `query` runs against the workflow\n// resource's client. Production-shape fix is to thread the engine's\n// `resourceClients` resolver through here; out of scope for v0.1.\n\n/**\n * Look up the conventional subject entry on a workflow instance's\n * workflow-scope fields. Returns the GDR URI when present, undefined\n * when the workflow has no subject entry or the entry is null.\n */\nfunction getSubjectGdr(instance: WorkflowInstance): string | undefined {\n const entry = instance.fields.find((s) => s._type === 'doc.ref' && s.name === SUBJECT_ENTRY_NAME)\n if (entry === undefined || entry._type !== 'doc.ref') return undefined\n return entry.value?.id\n}\n\n/**\n * Batch-fetch the `title` field for every subject doc referenced by\n * the supplied instances. Returns a `Map<gdrUri, title>` — missing\n * keys mean the doc had no title (or didn't exist / was unreadable).\n * The caller projects `ref` from the GDR either way; this map only\n * controls whether `title` is populated.\n *\n * Single GROQ call regardless of how many instances are supplied. At\n * `LIST_CAP=25` this is cheap; per-instance lookups would be N+1.\n */\nexport async function fetchSubjectTitles(\n engine: Engine,\n instances: WorkflowInstance[],\n): Promise<Map<string, string>> {\n // Build docId → gdrUri so we can attribute results back. Skip any\n // malformed GDRs silently — the projection still surfaces `ref`,\n // the LLM falls back to that as an identifier.\n const docIdToGdr = new Map<string, string>()\n for (const inst of instances) {\n const gdr = getSubjectGdr(inst)\n if (gdr === undefined) continue\n try {\n docIdToGdr.set(extractDocumentId(gdr), gdr)\n } catch {\n // Malformed GDR — leave it out of the title lookup.\n }\n }\n if (docIdToGdr.size === 0) return new Map()\n\n // Subject docs are ordinary content, not workflow docs — they carry no\n // engine tag, so we read them straight off the engine's client rather\n // than through the tag-scoped `engine.query` (which mandates a\n // `$tag` filter). Access is the client credential's concern: a\n // doc the caller can't read simply comes back absent.\n let docs: {_id: string; title?: string}[]\n try {\n docs = await engine.client.fetch<{_id: string; title?: string}[]>(\n '*[_id in $docIds]{_id, title}',\n {docIds: Array.from(docIdToGdr.keys())},\n )\n } catch (err) {\n // Titles are optional enrichment — degrade to bare refs rather than\n // failing the whole tool call when the lookup can't be served.\n process.stderr.write(\n `workflow-mcp: subject-title lookup failed; returning refs without titles: ${\n err instanceof Error ? err.message : String(err)\n }\\n`,\n )\n return new Map()\n }\n\n const out = new Map<string, string>()\n for (const doc of docs) {\n const gdr = docIdToGdr.get(doc._id)\n if (gdr !== undefined && typeof doc.title === 'string' && doc.title !== '') {\n out.set(gdr, doc.title)\n }\n }\n return out\n}\n\n/**\n * Build a `ProjectedSubject` for one instance, given the title map\n * produced by `fetchSubjectTitles`. Returns undefined when the\n * workflow has no subject entry; returns `{ ref }` without `title`\n * when the entry is present but the doc has no title field.\n */\nfunction buildSubject(\n instance: WorkflowInstance,\n subjectTitles: Map<string, string>,\n): ProjectedSubject | undefined {\n const gdr = getSubjectGdr(instance)\n if (gdr === undefined) return undefined\n const title = subjectTitles.get(gdr)\n return title !== undefined ? {ref: gdr, title} : {ref: gdr}\n}\n\nexport function projectSummary(\n doc: WorkflowInstance,\n subjectTitles: Map<string, string>,\n): ProjectedInstanceSummary {\n const definition = JSON.parse(doc.definitionSnapshot) as WorkflowDefinition\n const stage = definition.stages.find((s) => s.name === doc.currentStage)\n const stageTitle = stage?.title\n const workflowTitle = definition.title\n const subject = buildSubject(doc, subjectTitles)\n return {\n instanceId: doc._id,\n definition: doc.definition,\n ...(workflowTitle !== undefined ? {workflowTitle} : {}),\n currentStage: doc.currentStage,\n ...(stageTitle !== undefined ? {currentStageTitle: stageTitle} : {}),\n lastChangedAt: doc.lastChangedAt,\n done: isInstanceDone(doc),\n ...(subject !== undefined ? {subject} : {}),\n }\n}\n\nexport function projectState(\n instance: WorkflowInstance,\n evaluation: WorkflowEvaluation,\n subjectTitles: Map<string, string>,\n): ProjectedInstanceState {\n // The evaluation already exposes the current stage's title from the\n // snapshot, but not the workflow's own title — parse the snapshot\n // once here to read it.\n const definition = JSON.parse(instance.definitionSnapshot) as WorkflowDefinition\n const workflowTitle = definition.title\n const stageTitle = evaluation.currentStage.stage.title\n\n const tasks: ProjectedTask[] = evaluation.currentStage.tasks.map((te) => {\n // Each action's verdict comes from the engine's shared `actionVerdict` —\n // the same \"is this firable, and why not\" the CLI reads — so the verdict\n // shape has one source; we keep the LLM-shaped per-task nesting.\n const actions: ProjectedActionVerdict[] = te.actions.map((ae) => {\n const verdict = actionVerdict(te, ae)\n return {\n action: verdict.action,\n ...(verdict.title !== undefined ? {title: verdict.title} : {}),\n allowed: verdict.allowed,\n ...(verdict.allowed === false && verdict.disabledReason !== undefined\n ? {disabledReason: formatDisabledReason(verdict.disabledReason)}\n : {}),\n }\n })\n\n return {\n task: te.task.name,\n ...(te.task.title !== undefined ? {title: te.task.title} : {}),\n ...(te.task.description !== undefined ? {description: te.task.description} : {}),\n status: te.status,\n actions,\n }\n })\n\n const recentHistory: ProjectedHistoryEntry[] = instance.history\n .slice(-HISTORY_CAP)\n .toReversed()\n .map((entry) => ({\n at: entry.at,\n type: entry._type,\n summary: summariseHistoryEntry(entry),\n }))\n\n const subject = buildSubject(instance, subjectTitles)\n return {\n instanceId: instance._id,\n definition: instance.definition,\n ...(workflowTitle !== undefined ? {workflowTitle} : {}),\n currentStage: instance.currentStage,\n ...(stageTitle !== undefined ? {currentStageTitle: stageTitle} : {}),\n done: isInstanceDone(instance),\n ...(subject !== undefined ? {subject} : {}),\n tasks,\n recentHistory,\n }\n}\n\nexport function isInstanceDone(instance: WorkflowInstance): boolean {\n // The engine sets `completedAt` when an instance enters a terminal\n // stage; falling back to the structural check covers any edge case\n // where the definition snapshot is the source of truth.\n if (instance.completedAt !== undefined) return true\n try {\n const definition = JSON.parse(instance.definitionSnapshot) as WorkflowDefinition\n const stage = definition.stages.find((s) => s.name === instance.currentStage)\n return stage !== undefined && isTerminalStage(stage)\n } catch {\n return false\n }\n}\n\n/**\n * Engine `disabledReason` is a structured tagged union (see\n * `DisabledReason` in @sanity/workflow-engine). For an LLM\n * we want a short English phrase rather than the tagged shape — the\n * tagged shape is still available on the raw evaluation if a richer\n * consumer wants it.\n */\nconst DISABLED_REASON_TEXT: Record<string, string> = {\n 'filter-failed': \"action's filter condition did not hold for this actor\",\n 'task-not-active': 'task is not currently active',\n 'stage-terminal': 'stage is terminal — no further actions possible',\n 'instance-completed': 'instance has already completed',\n 'requirements-unmet': \"task's declared requirements are not yet satisfied\",\n}\n\nfunction formatDisabledReason(reason: {kind: string}): string {\n // Fall back to a humanised form of the kind for reasons we don't have\n // bespoke copy for, so a new engine reason never renders as a raw enum.\n return DISABLED_REASON_TEXT[reason.kind] ?? reason.kind.replace(/-/g, ' ')\n}\n\nfunction summariseHistoryEntry(entry: {_type: string} & Record<string, unknown>): string {\n switch (entry._type) {\n case 'stageEntered':\n return `entered stage \"${String(entry.stage)}\"`\n case 'stageExited':\n return `exited stage \"${String(entry.stage)}\" → \"${String(entry.toStage)}\"`\n case 'taskActivated':\n return `task \"${String(entry.task)}\" activated`\n case 'taskStatusChanged':\n return `task \"${String(entry.task)}\" status: ${String(entry.from)} → ${String(entry.to)}`\n case 'actionFired':\n return `action \"${String(entry.action)}\" fired on task \"${String(entry.task)}\"`\n case 'transitionFired':\n return `transition fired: \"${String(entry.fromStage)}\" → \"${String(entry.toStage)}\"`\n case 'effectQueued':\n return `effect \"${String(entry.effect)}\" queued`\n case 'effectCompleted':\n return `effect \"${String(entry.effect)}\" completed (${String(entry.status)})`\n case 'spawned':\n return `spawned child workflow from task \"${String(entry.task)}\"`\n default:\n return entry._type\n }\n}\n\n// Diagnosis summary — a plain-English one-liner per verdict, the LLM-facing\n// counterpart to the CLI's terminal-decorated rendering. The engine's\n// `diagnostics` module deliberately does no rendering, so each consumer writes\n// its own; this one folds the key identifiers (the stuck effect/task, the\n// waiting actions) into one undecorated line.\n\n/** Exported for unit coverage of every verdict branch — see `tools.test.ts`.\n * Used internally by the diagnose_workflow read in `tools.ts`. */\nexport function diagnosisSummary(diagnosis: Diagnosis): string {\n switch (diagnosis.state) {\n case 'progressing':\n return 'This instance will advance on its own.'\n case 'waiting':\n return `Waiting for action on task \"${diagnosis.task}\": ${diagnosis.actions.join(' or ')}. This is the normal in-flight state — it advances when someone acts.`\n case 'blocked':\n return `Task \"${diagnosis.task}\" is visible but not yet executable — unmet requirement(s): ${diagnosis.requirements.join(', ')}. It will not advance until those are satisfied.`\n case 'completed':\n return `Completed at ${diagnosis.at}.`\n case 'aborted':\n return diagnosis.reason !== undefined\n ? `Aborted at ${diagnosis.at}: ${diagnosis.reason}.`\n : `Aborted at ${diagnosis.at}.`\n case 'stuck':\n return stuckSummary(diagnosis.cause)\n }\n}\n\nfunction stuckSummary(cause: StuckCause): string {\n switch (cause.kind) {\n case 'failed-effect':\n return `Stuck: a failed effect \"${cause.effect.name}\" is blocking task \"${cause.effect.origin.name}\", which can't complete until the effect succeeds.`\n case 'hung-effect':\n return `Stuck: effect \"${cause.effect.name}\" was claimed but never completed — the drainer likely died mid-dispatch, so it won't drain on its own.`\n case 'failed-task':\n return `Stuck: task \"${cause.task}\" is in a terminal failed state, so any exit transition gated on it can never fire.`\n case 'no-transition-fires':\n return `Stuck: every task is resolved but no exit transition's filter is satisfied — likely a routing state value a filter reads was never written.`\n case 'transition-unevaluable':\n return `Stuck (recoverable): exit transition(s) ${cause.transitions.join(', ')} read an operand that is missing or unreadable (GROQ null). It advances on its own once that data becomes readable — no manual fix needed.`\n }\n}\n","/**\n * Builds the MCP tool surface: binds the static descriptors (`descriptors.ts`)\n * to implementations that close over a single engine, parses tool input, and\n * runs the engine reads that the projection helpers (`projection.ts`) shape.\n */\n\nimport {\n validateDefinition,\n WORKFLOW_INSTANCE_TYPE,\n tagScopeFilter,\n type AuthoringWorkflow,\n type Engine,\n type WorkflowAccessOverride,\n type WorkflowInstance,\n} from '@sanity/workflow-engine'\nimport {defineWorkflow} from '@sanity/workflow-engine/define'\n\nimport {AUTHORING_GUIDE} from './authoring-guide.ts'\nimport {LIST_CAP, TOOL_DESCRIPTORS, type ToolDescriptor} from './descriptors.ts'\nimport {\n diagnosisSummary,\n fetchSubjectTitles,\n isInstanceDone,\n projectState,\n projectSummary,\n} from './projection.ts'\nimport type {\n ProjectedDiagnosis,\n ProjectedInstanceState,\n ProjectedInstanceSummary,\n ValidateDefinitionResult,\n} from './types.ts'\n\n/**\n * A tool implementation is a function from validated input → JSON-able\n * output. The runner is responsible for serialising the output and for\n * surfacing thrown errors as `is_error` tool results.\n */\nexport type ToolImpl = (input: unknown) => Promise<unknown>\n\nexport interface BuiltTools {\n descriptors: ToolDescriptor[]\n impls: Record<string, ToolImpl>\n}\n\n/**\n * Optional knobs for `buildTools`.\n *\n * `access` — override the engine's actor + grants resolution for every\n * call the tools make. In production, leave this unset: the engine\n * resolves the actor from the supplied client's token via `/users/me`.\n * In tests, pass `ALL_ACCESS` (from `@sanity/workflow-engine-test`)\n * because the TestClient has no token and would otherwise throw on\n * the resolution path.\n */\nexport interface BuildToolsOptions {\n access?: WorkflowAccessOverride\n}\n\n/**\n * Build the MCP tool descriptors and bound implementations against a\n * single engine. Pass the engine the tools should operate on; the\n * returned descriptors are static (safe to cache), the implementations\n * close over the engine.\n *\n * In production this is called once at server boot. In tests it's\n * called per-bench so each eval case has an isolated engine.\n */\nexport function buildTools(engine: Engine, options: BuildToolsOptions = {}): BuiltTools {\n const accessOverride = options.access\n\n const impls: Record<string, ToolImpl> = {\n list_workflow_instances: async (rawInput) => {\n const input = parseListInput(rawInput)\n return listInstances(engine, input)\n },\n get_workflow_state: async (rawInput) => {\n const input = parseInstanceIdInput(rawInput, 'get_workflow_state')\n return getInstanceState(engine, input.instance_id, accessOverride)\n },\n diagnose_workflow: async (rawInput) => {\n const input = parseInstanceIdInput(rawInput, 'diagnose_workflow')\n return getInstanceDiagnosis(engine, input.instance_id, accessOverride)\n },\n fire_action: async (rawInput) => {\n const input = parseFireActionInput(rawInput)\n await engine.fireAction({\n instanceId: input.instance_id,\n task: input.task,\n action: input.action,\n ...(accessOverride !== undefined ? {access: accessOverride} : {}),\n })\n // Re-use the same projection so the LLM sees consistent shapes\n // between get_workflow_state and fire_action responses.\n return getInstanceState(engine, input.instance_id, accessOverride)\n },\n // Authoring tools — engine-independent: they teach and check the DSL, they\n // don't touch the lake or an instance.\n get_workflow_authoring_guide: async () => AUTHORING_GUIDE,\n validate_workflow_definition: async (rawInput): Promise<ValidateDefinitionResult> => {\n const {definition} = parseValidateInput(rawInput)\n try {\n // `defineWorkflow` is the gate (valibot structural parse + desugar +\n // cross-field invariants); `validateDefinition` adds GROQ syntax checks.\n // The cast only satisfies the compiler — `defineWorkflow` validates the\n // value at runtime and throws an aggregated, path-prefixed error.\n const stored = defineWorkflow(definition as AuthoringWorkflow)\n validateDefinition(stored)\n return {valid: true, definition: stored}\n } catch (err) {\n return {valid: false, error: err instanceof Error ? err.message : String(err)}\n }\n },\n }\n\n return {descriptors: TOOL_DESCRIPTORS, impls}\n}\n\n// Input parsers — lightweight, no zod dependency\n//\n// Reasoning: pulling in zod would inflate the package for this handful of tools.\n// The MCP server and the eval harness already constrain the shape via\n// the JSON schema in the descriptor; these parsers exist for runtime\n// type-narrowing in TypeScript, not for deep validation.\n\ninterface ListInput {\n definition?: string\n status: 'in_flight' | 'done' | 'any'\n}\n\nfunction parseListInput(raw: unknown): ListInput {\n if (raw === null || typeof raw !== 'object') {\n return {status: 'in_flight'}\n }\n const obj = raw as Record<string, unknown>\n const status = obj.status === 'done' || obj.status === 'any' ? obj.status : ('in_flight' as const)\n const definition = typeof obj.definition === 'string' ? obj.definition : undefined\n return definition !== undefined ? {definition, status} : {status}\n}\n\n/** Narrow the validate input to `{definition: object}`. The deep validation\n * is `defineWorkflow`'s job — this only guards the envelope. */\nfunction parseValidateInput(raw: unknown): {definition: object} {\n if (raw === null || typeof raw !== 'object') {\n throw new Error('validate_workflow_definition: input must be an object')\n }\n const obj = raw as Record<string, unknown>\n if (obj.definition === null || typeof obj.definition !== 'object') {\n throw new Error('validate_workflow_definition: `definition` is required and must be an object')\n }\n return {definition: obj.definition}\n}\n\n/** Shared by every single-instance tool — `tool` names the caller so the\n * thrown error points at the right tool. */\nfunction parseInstanceIdInput(raw: unknown, tool: string): {instance_id: string} {\n if (raw === null || typeof raw !== 'object') {\n throw new Error(`${tool}: input must be an object`)\n }\n const obj = raw as Record<string, unknown>\n if (typeof obj.instance_id !== 'string' || obj.instance_id === '') {\n throw new Error(`${tool}: instance_id is required`)\n }\n return {instance_id: obj.instance_id}\n}\n\nfunction parseFireActionInput(raw: unknown): {\n instance_id: string\n task: string\n action: string\n} {\n if (raw === null || typeof raw !== 'object') {\n throw new Error('fire_action: input must be an object')\n }\n const obj = raw as Record<string, unknown>\n for (const key of ['instance_id', 'task', 'action'] as const) {\n if (typeof obj[key] !== 'string' || obj[key] === '') {\n throw new Error(`fire_action: ${key} is required`)\n }\n }\n return {\n instance_id: obj.instance_id as string,\n task: obj.task as string,\n action: obj.action as string,\n }\n}\n\n// Engine reads, projected for an LLM\n\nasync function listInstances(\n engine: Engine,\n input: ListInput,\n): Promise<{instances: ProjectedInstanceSummary[]}> {\n // Tag-scoped via the engine's own query helper — every instance\n // returned is one this engine is allowed to see.\n const groqParts = [`_type == \"${WORKFLOW_INSTANCE_TYPE}\"`]\n if (input.definition !== undefined) {\n groqParts.push('definition == $definition')\n }\n const groq =\n `*[${groqParts.join(' && ')} && ${tagScopeFilter()}] ` +\n `| order(lastChangedAt desc)[0...${LIST_CAP}]`\n\n const params: Record<string, unknown> = {}\n if (input.definition !== undefined) params.definition = input.definition\n\n const docs = await engine.query<WorkflowInstance[]>({groq, params})\n const filtered = docs.filter((doc) => {\n const done = isInstanceDone(doc)\n if (input.status === 'done') return done\n if (input.status === 'in_flight') return !done\n return true // \"any\"\n })\n const subjectTitles = await fetchSubjectTitles(engine, filtered)\n return {\n instances: filtered.map((doc) => projectSummary(doc, subjectTitles)),\n }\n}\n\nasync function getInstanceState(\n engine: Engine,\n instanceId: string,\n accessOverride: WorkflowAccessOverride | undefined,\n): Promise<ProjectedInstanceState> {\n const evaluation = await engine.evaluateInstance({\n instanceId,\n ...(accessOverride !== undefined ? {access: accessOverride} : {}),\n })\n const instance = await engine.getInstance({instanceId})\n const subjectTitles = await fetchSubjectTitles(engine, [instance])\n return projectState(instance, evaluation, subjectTitles)\n}\n\nasync function getInstanceDiagnosis(\n engine: Engine,\n instanceId: string,\n accessOverride: WorkflowAccessOverride | undefined,\n): Promise<ProjectedDiagnosis> {\n const {diagnosis, remediations} = await engine.diagnose({\n instanceId,\n ...(accessOverride !== undefined ? {access: accessOverride} : {}),\n })\n return {\n instanceId,\n state: diagnosis.state,\n summary: diagnosisSummary(diagnosis),\n ...(diagnosis.state === 'stuck' ? {cause: diagnosis.cause.kind} : {}),\n remediations,\n }\n}\n"],"names":[],"mappings":";;AAqBA,MAAM,iBAAiB;AAAA,EACrB,MAAM;AAAA,EACN,SAAS;AAAA,EACT,OAAO;AAAA,EACP,aAAa;AAAA,EACb,cAAc;AAAA,EACd,QAAQ,CAAC,EAAC,MAAM,WAAW,MAAM,WAAW,OAAO,YAAY,QAAQ,EAAC,MAAM,OAAA,GAAQ;AAAA,EACtF,QAAQ;AAAA,IACN;AAAA,MACE,MAAM;AAAA,MACN,OAAO;AAAA,MACP,OAAO;AAAA,QACL;AAAA,UACE,MAAM;AAAA,UACN,OAAO;AAAA,UACP,YAAY;AAAA,UACZ,SAAS,CAAC,EAAC,MAAM,WAAW,OAAO,WAAW,QAAQ,OAAA,CAAO;AAAA,QAAA;AAAA,MAC/D;AAAA,MAEF,aAAa,CAAC,EAAC,MAAM,eAAe,OAAO,sBAAsB,IAA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W,SAAe,OAChC,MAAM,WAAW,cAAoB,CAAC,OACnC;AAAA,EACT,CAAC,GACK,gBAAgB,MAAM,mBAAmB,QAAQ,QAAQ;AAC/D,SAAO;AAAA,IACL,WAAW,SAAS,IAAI,CAAC,QAAQ,eAAe,KAAK,aAAa,CAAC;AAAA,EAAA;AAEvE;AAEA,eAAe,iBACb,QACA,YACA,gBACiC;AACjC,QAAM,aAAa,MAAM,OAAO,iBAAiB;AAAA,IAC/C;AAAA,IACA,GAAI,mBAAmB,SAAY,EAAC,QAAQ,eAAA,IAAkB,CAAA;AAAA,EAAC,CAChE,GACK,WAAW,MAAM,OAAO,YAAY,EAAC,WAAA,CAAW,GAChD,gBAAgB,MAAM,mBAAmB,QAAQ,CAAC,QAAQ,CAAC;AACjE,SAAO,aAAa,UAAU,YAAY,aAAa;AACzD;AAEA,eAAe,qBACb,QACA,YACA,gBAC6B;AAC7B,QAAM,EAAC,WAAW,aAAA,IAAgB,MAAM,OAAO,SAAS;AAAA,IACtD;AAAA,IACA,GAAI,mBAAmB,SAAY,EAAC,QAAQ,eAAA,IAAkB,CAAA;AAAA,EAAC,CAChE;AACD,SAAO;AAAA,IACL;AAAA,IACA,OAAO,UAAU;AAAA,IACjB,SAAS,iBAAiB,SAAS;AAAA,IACnC,GAAI,UAAU,UAAU,UAAU,EAAC,OAAO,UAAU,MAAM,KAAA,IAAQ,CAAA;AAAA,IAClE;AAAA,EAAA;AAEJ;"}
|
package/dist/stdio.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* stdio MCP host — boots a {@link Server} from `@modelcontextprotocol/sdk`,
|
|
3
|
+
* binds the workflow tools to an engine built from environment variables,
|
|
4
|
+
* and listens on stdio.
|
|
5
|
+
*
|
|
6
|
+
* This is one of two thin hosts over the shared {@link buildTools} core:
|
|
7
|
+
* the stdio host (here) is the early-access self-host (one env-built
|
|
8
|
+
* engine, BYO scoped token, system-actor attribution); the production
|
|
9
|
+
* host embeds {@link buildTools} with per-request identity elsewhere.
|
|
10
|
+
*
|
|
11
|
+
* Kept as its own package entry (not inline in `bin/`) so it can be
|
|
12
|
+
* compiled to `dist/stdio.js` by pkg-utils and re-used by both the
|
|
13
|
+
* published bin (`bin/run.js`) and the dev entry (`bin/workflow-mcp.ts`)
|
|
14
|
+
* — one boot path, no duplication. Keeping it out of the `.` entry also
|
|
15
|
+
* keeps the MCP transport deps out of the library import graph.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Read the environment, build the engine, register the tools, and serve
|
|
19
|
+
* on stdio. Resolves when the transport is connected (the process then
|
|
20
|
+
* stays alive on the open stdio streams).
|
|
21
|
+
*/
|
|
22
|
+
export declare function runStdioServer(): Promise<void>;
|
|
23
|
+
|
|
24
|
+
export {};
|