@sanity/workflow-mcp 0.5.1 → 0.6.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/dist/index.js CHANGED
@@ -1,520 +1,3 @@
1
- import { extractDocumentId, actionVerdict, isTerminalStage, deniedGuardLabels, 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
- title: "Quick approval",
6
- description: "One review stage with a single approve action, then a terminal stage.",
7
- initialStage: "review",
8
- fields: [{ type: "doc.ref", name: "subject", title: "Document", initialValue: { type: "input" } }],
9
- stages: [
10
- {
11
- name: "review",
12
- title: "Review",
13
- activities: [
14
- {
15
- name: "decide",
16
- title: "Decide",
17
- activation: "auto",
18
- actions: [{ name: "approve", title: "Approve", status: "done" }]
19
- }
20
- ],
21
- transitions: [{ name: "to-approved", title: "Approve and finish", to: "approved" }]
22
- },
23
- { name: "approved", title: "Approved", description: "Terminal \u2014 no transitions out." }
24
- ]
25
- }, reviewLoopExample = {
26
- name: "doc-review",
27
- title: "Document review",
28
- description: "Draft, then editorial review that approves or rejects back to drafting.",
29
- initialStage: "drafting",
30
- fields: [{ type: "doc.ref", name: "subject", title: "Document", initialValue: { type: "input" } }],
31
- stages: [
32
- {
33
- name: "drafting",
34
- title: "Drafting",
35
- activities: [
36
- {
37
- name: "write",
38
- title: "Write the draft",
39
- activation: "auto",
40
- actions: [{ name: "submit", title: "Submit for review", status: "done" }]
41
- }
42
- ],
43
- transitions: [{ name: "to-review", title: "Send to review", to: "review" }]
44
- },
45
- {
46
- name: "review",
47
- title: "Editorial review",
48
- // The decision is data: each action writes it, the transition filters
49
- // read it. Stage-scoped so a later review round starts with a clean slate.
50
- fields: [{ type: "string", name: "decision", title: "Review decision" }],
51
- activities: [
52
- {
53
- name: "review",
54
- title: "Review the draft",
55
- activation: "auto",
56
- actions: [
57
- {
58
- name: "approve",
59
- title: "Approve",
60
- status: "done",
61
- ops: [
62
- {
63
- type: "field.set",
64
- target: { field: "decision" },
65
- value: { type: "literal", value: "approve" }
66
- }
67
- ]
68
- },
69
- // Rejecting is the reviewer DOING their job — a decision, not a
70
- // failure — so it resolves `done` and routes via the field.
71
- {
72
- name: "reject",
73
- title: "Reject",
74
- status: "done",
75
- ops: [
76
- {
77
- type: "field.set",
78
- target: { field: "decision" },
79
- value: { type: "literal", value: "reject" }
80
- }
81
- ]
82
- }
83
- ]
84
- }
85
- ],
86
- transitions: [
87
- {
88
- name: "to-approved",
89
- title: "Approve and finish",
90
- to: "approved",
91
- filter: "$allActivitiesDone && $fields.decision == 'approve'"
92
- },
93
- {
94
- name: "to-drafting",
95
- title: "Send back to drafting",
96
- to: "drafting",
97
- filter: "$allActivitiesDone && $fields.decision == 'reject'"
98
- }
99
- ]
100
- },
101
- { name: "approved", title: "Approved", description: "Terminal \u2014 no transitions out." }
102
- ]
103
- }, 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, title, description?, initialStage, fields?, stages[], predicates? }`.\n `initialStage` must be the `name` of a declared stage. Do NOT include a\n `version` \u2014 definitions are immutable and content-addressed; deploy assigns\n the version from the content, the author never writes one.\n- **Stage**: `{ name, title?, description?, activities?, transitions? }`. A stage with\n no transitions is terminal. Reaching a terminal stage ends the workflow.\n- **Activity**: `{ 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 activity* to\n that status when the action fires. Status is a health axis, not a decision:\n a routine decision (reject, send back, decline, hold) resolves `'done'` and\n writes the decision into a field the transition filters read \u2014 reserve\n `'failed'` for work that genuinely could not complete (e.g. a missed\n deadline via `failWhen`). `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 `$allActivitiesDone`.\n- **Field** (workflow- or stage-scoped persistent state): `{ type, name, title?, initialValue? }`.\n Scalar `type`s mirror Sanity: `string`, `text` (multiline), `number`,\n `boolean`, `date` (YYYY-MM-DD), `datetime` (ISO), `url`. Plus references\n (`doc.ref`, `doc.refs`, `release.ref`), identities (`actor` \u2014 one concrete\n principal; `assignee` / `assignees` \u2014 one or many user-or-role assignees), and\n the compositional kinds `object` (`{ type:'object', name, fields: [...] }`) and\n `array` (`{ type:'array', name, of: [...] }`) \u2014 `fields`/`of` are themselves\n field shapes, so any structure composes. `initialValue` seeds the field once at\n materialisation and is **optional** \u2014 omit it for op-filled working memory\n (the common default). Arms: `{type:'input'}` (the caller supplies it when the\n instance starts), `{type:'query', query:'<groq>'}` (computed from the lake),\n `{type:'literal', value:<json>}`, or `{type:'fieldRead', field:'<name>'}`.\n By convention a workflow has an `input`-sourced `doc.ref` named `subject` \u2014 the\n headline document it is about.\n Two list sugars desugar to `array`: `{type:'todoList', name}` (ad-hoc\n status-tracked work \u2014 rows `{ label, status, assignee?, dueDate? }`) and\n `{type:'notes', name}` (an append-only audit/comment log \u2014 rows\n `{ body, actor, at }`; pairs with the `audit` op, which stamps `actor`/`at`).\n\n## GROQ in conditions\n\nBuilt-in variables available in filters/predicates (the engine's exported\n`CONDITION_VARS` inventory is the source of truth): `$allActivitiesDone`,\n`$anyActivityFailed` (booleans over the current stage's activities), `$activities` (the activity\nlist), `$fields` (field values), `$now`, `$self`/`$stage`/`$parent`/`$ancestors`\n(instance identity + position), `$effectStatus` (effect name \u2192 `'done'`/`'failed'`\nof the run queued during the CURRENT stage entry \u2014 the re-entry-safe way to gate\non an effect having drained, e.g.\n`completeWhen: \"defined($effectStatus['my.effect'])\"`), and the caller-scoped\nvars `$actor` (the acting user), `$assigned` (whether the caller is the\nactivity's assignee \u2014 the idiomatic permission gate, used as\n`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($activities[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 activity (shown above).\n- Omitted transition `filter` \u2014 defaults to `$allActivitiesDone`.\n- Omitted activity `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 a `decision` field the reject action wrote), not to a terminal stage.\n Reserve terminal stages for completion and for explicit\n cancellation/abandonment \u2014 a workflow should not dead-end just because\n something was declined.\n- **Decisions are fields, not failures.** When a stage branches on a human\n decision, declare a stage-scoped `string` field (stage scope resets on\n re-entry, so loop-backs start clean), have each deciding action `field.set`\n it, and gate every outbound transition on its value (Example 2). Do not\n encode a decision as `status: 'failed'` + `$anyActivityFailed` \u2014 reporting\n would count healthy loops as failures.\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, activity 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. `allActivitiesDone`).\n- Every GROQ string must parse and must not be a `_type` discovery scan.", AUTHORING_GUIDE = `${ORIENTATION}
1
+ import { WORKFLOW_TOOLS, registerWorkflowTools, toolInputJsonSchema, workflowAddressFromInput } from "./_chunks-es/index.js";
104
2
 
105
- ## Examples
106
-
107
- ### Example 1 \u2014 ${minimalExample.title} (minimal: one stage, one action)
108
- \`\`\`json
109
- ${JSON.stringify(minimalExample, null, 2)}
110
- \`\`\`
111
-
112
- ### Example 2 \u2014 ${reviewLoopExample.title} (review loop: reject routes back)
113
- \`\`\`json
114
- ${JSON.stringify(reviewLoopExample, null, 2)}
115
- \`\`\`
116
- `, LIST_CAP = 25, TOOL_DESCRIPTORS = [
117
- {
118
- name: "list_workflow_instances",
119
- 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, `definition` (the workflow definition's `name`) 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.",
120
- input_schema: {
121
- type: "object",
122
- properties: {
123
- definition: {
124
- type: "string",
125
- description: "Optional. Restrict to instances of this workflow definition, by its `name` (e.g. 'article-review')."
126
- },
127
- status: {
128
- type: "string",
129
- enum: ["in_flight", "done", "any"],
130
- description: "Optional. 'in_flight' returns instances not in a terminal stage; 'done' returns completed/aborted; 'any' returns both. Defaults to 'in_flight'."
131
- }
132
- },
133
- additionalProperties: !1
134
- }
135
- },
136
- {
137
- name: "get_workflow_state",
138
- 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 activity 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.",
139
- input_schema: {
140
- type: "object",
141
- properties: {
142
- instance_id: {
143
- type: "string",
144
- description: "The workflow instance id."
145
- }
146
- },
147
- required: ["instance_id"],
148
- additionalProperties: !1
149
- }
150
- },
151
- {
152
- name: "diagnose_workflow",
153
- 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 activity, 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-activity action detail use get_workflow_state.",
154
- input_schema: {
155
- type: "object",
156
- properties: {
157
- instance_id: {
158
- type: "string",
159
- description: "The workflow instance id."
160
- }
161
- },
162
- required: ["instance_id"],
163
- additionalProperties: !1
164
- }
165
- },
166
- {
167
- name: "fire_action",
168
- description: "Advance a workflow instance by firing an action on one of its activities. This is the only way to advance workflow state from the outside \u2014 there is no separate 'complete activity' or 'transition stage' tool. To find the right (activity, action) pair, call get_workflow_state first and pick from the allowed actions listed on the current stage's activities. After firing, the engine cascades any auto-transitions that become eligible (so an 'approve' action on a review activity 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 activity is already done, or a guard fails), this returns an error describing why.",
169
- input_schema: {
170
- type: "object",
171
- properties: {
172
- instance_id: {
173
- type: "string",
174
- description: "The workflow instance id."
175
- },
176
- activity: {
177
- type: "string",
178
- description: "The id of the activity on the current stage. Must be one of the activities returned by get_workflow_state."
179
- },
180
- action: {
181
- type: "string",
182
- description: "The id of the action on that activity. Must be one of the actions listed as allowed=true on the activity."
183
- },
184
- params: {
185
- type: "object",
186
- description: `Optional. Values for the action's declared params, keyed by param name (e.g. {"note": "Unsupported claim in paragraph 3."}). Required when the action declares a required param \u2014 get_workflow_state lists each action's params and whether they are required. The shape is per-action, so this is a free-form object; the engine validates the supplied values against the action's declared params and rejects the call if a required one is missing.`,
187
- additionalProperties: !0
188
- }
189
- },
190
- required: ["instance_id", "activity", "action"],
191
- additionalProperties: !1
192
- }
193
- },
194
- {
195
- name: "get_workflow_authoring_guide",
196
- 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.",
197
- input_schema: {
198
- type: "object",
199
- properties: {},
200
- additionalProperties: !1
201
- }
202
- },
203
- {
204
- name: "validate_workflow_definition",
205
- 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.",
206
- input_schema: {
207
- type: "object",
208
- properties: {
209
- definition: {
210
- type: "object",
211
- description: "The workflow definition to validate, as a JSON object in authoring shape. See get_workflow_authoring_guide for the shape and examples."
212
- }
213
- },
214
- required: ["definition"],
215
- additionalProperties: !1
216
- }
217
- }
218
- ], SUBJECT_ENTRY_NAME = "subject";
219
- function getSubjectGdr(instance) {
220
- const entry = instance.fields.find((s) => s._type === "doc.ref" && s.name === SUBJECT_ENTRY_NAME);
221
- if (!(entry === void 0 || entry._type !== "doc.ref"))
222
- return entry.value?.id;
223
- }
224
- async function fetchSubjectTitles(engine, instances) {
225
- const docIdToGdr = /* @__PURE__ */ new Map();
226
- for (const inst of instances) {
227
- const gdr = getSubjectGdr(inst);
228
- if (gdr !== void 0)
229
- try {
230
- docIdToGdr.set(extractDocumentId(gdr), gdr);
231
- } catch {
232
- }
233
- }
234
- if (docIdToGdr.size === 0) return /* @__PURE__ */ new Map();
235
- let docs;
236
- try {
237
- docs = await engine.client.fetch(
238
- "*[_id in $docIds]{_id, title}",
239
- { docIds: Array.from(docIdToGdr.keys()) }
240
- );
241
- } catch (err) {
242
- return process.stderr.write(
243
- `workflow-mcp: subject-title lookup failed; returning refs without titles: ${err instanceof Error ? err.message : String(err)}
244
- `
245
- ), /* @__PURE__ */ new Map();
246
- }
247
- const out = /* @__PURE__ */ new Map();
248
- for (const doc of docs) {
249
- const gdr = docIdToGdr.get(doc._id);
250
- gdr !== void 0 && typeof doc.title == "string" && doc.title !== "" && out.set(gdr, doc.title);
251
- }
252
- return out;
253
- }
254
- function buildSubject(instance, subjectTitles) {
255
- const gdr = getSubjectGdr(instance);
256
- if (gdr === void 0) return;
257
- const title = subjectTitles.get(gdr);
258
- return title !== void 0 ? { ref: gdr, title } : { ref: gdr };
259
- }
260
- function projectSummary(doc, subjectTitles) {
261
- const definition = JSON.parse(doc.definitionSnapshot), stageTitle = definition.stages.find((s) => s.name === doc.currentStage)?.title, workflowTitle = definition.title, subject = buildSubject(doc, subjectTitles);
262
- return {
263
- instanceId: doc._id,
264
- definition: doc.definition,
265
- ...workflowTitle !== void 0 ? { workflowTitle } : {},
266
- currentStage: doc.currentStage,
267
- ...stageTitle !== void 0 ? { currentStageTitle: stageTitle } : {},
268
- lastChangedAt: doc.lastChangedAt,
269
- done: isInstanceDone(doc),
270
- ...subject !== void 0 ? { subject } : {}
271
- };
272
- }
273
- function projectState({
274
- instance,
275
- evaluation,
276
- subjectTitles
277
- }) {
278
- const workflowTitle = JSON.parse(instance.definitionSnapshot).title, stageTitle = evaluation.currentStage.stage.title, activities = evaluation.currentStage.activities.map((te) => {
279
- const actions = te.actions.map((ae) => {
280
- const verdict = actionVerdict(te, ae);
281
- return {
282
- action: verdict.action,
283
- ...verdict.title !== void 0 ? { title: verdict.title } : {},
284
- allowed: verdict.allowed,
285
- ...verdict.allowed === !1 && verdict.disabledReason !== void 0 ? { disabledReason: formatDisabledReason(verdict.disabledReason) } : {}
286
- };
287
- });
288
- return {
289
- activity: te.activity.name,
290
- ...te.activity.title !== void 0 ? { title: te.activity.title } : {},
291
- ...te.activity.description !== void 0 ? { description: te.activity.description } : {},
292
- status: te.status,
293
- actions
294
- };
295
- }), recentHistory = instance.history.slice(-8).toReversed().map((entry) => ({
296
- at: entry.at,
297
- type: entry._type,
298
- summary: summariseHistoryEntry(entry)
299
- })), subject = buildSubject(instance, subjectTitles);
300
- return {
301
- instanceId: instance._id,
302
- definition: instance.definition,
303
- ...workflowTitle !== void 0 ? { workflowTitle } : {},
304
- currentStage: instance.currentStage,
305
- ...stageTitle !== void 0 ? { currentStageTitle: stageTitle } : {},
306
- done: isInstanceDone(instance),
307
- ...subject !== void 0 ? { subject } : {},
308
- activities,
309
- recentHistory
310
- };
311
- }
312
- function isInstanceDone(instance) {
313
- if (instance.completedAt !== void 0) return !0;
314
- try {
315
- const stage = JSON.parse(instance.definitionSnapshot).stages.find((s) => s.name === instance.currentStage);
316
- return stage !== void 0 && isTerminalStage(stage);
317
- } catch {
318
- return !1;
319
- }
320
- }
321
- function formatDisabledReason(reason) {
322
- switch (reason.kind) {
323
- case "filter-failed":
324
- return "action's filter condition did not hold for this actor";
325
- case "activity-not-active":
326
- return "activity is not currently active";
327
- case "stage-terminal":
328
- return "stage is terminal \u2014 no further actions possible";
329
- case "mutation-guard-denied":
330
- return `blocked by mutation guard(s): ${deniedGuardLabels(reason.denied).join(", ")}`;
331
- case "instance-completed":
332
- return "instance has already completed";
333
- case "requirements-unmet":
334
- return "activity's declared requirements are not yet satisfied";
335
- }
336
- }
337
- function summariseHistoryEntry(entry) {
338
- switch (entry._type) {
339
- case "stageEntered":
340
- return `entered stage "${String(entry.stage)}"`;
341
- case "stageExited":
342
- return `exited stage "${String(entry.stage)}" \u2192 "${String(entry.toStage)}"`;
343
- case "activityActivated":
344
- return `activity "${String(entry.activity)}" activated`;
345
- case "activityStatusChanged":
346
- return `activity "${String(entry.activity)}" status: ${String(entry.from)} \u2192 ${String(entry.to)}`;
347
- case "actionFired":
348
- return `action "${String(entry.action)}" fired on activity "${String(entry.activity)}"`;
349
- case "transitionFired":
350
- return `transition fired: "${String(entry.fromStage)}" \u2192 "${String(entry.toStage)}"`;
351
- case "effectQueued":
352
- return `effect "${String(entry.effect)}" queued`;
353
- case "effectCompleted":
354
- return `effect "${String(entry.effect)}" completed (${String(entry.status)})`;
355
- case "spawned":
356
- return `spawned child workflow from activity "${String(entry.activity)}"`;
357
- default:
358
- return entry._type;
359
- }
360
- }
361
- function diagnosisSummary(diagnosis) {
362
- switch (diagnosis.state) {
363
- case "progressing":
364
- return "This instance will advance on its own.";
365
- case "waiting":
366
- return `Waiting for action on activity "${diagnosis.activity}": ${diagnosis.actions.join(" or ")}. This is the normal in-flight state \u2014 it advances when someone acts.`;
367
- case "blocked":
368
- return `Activity "${diagnosis.activity}" is visible but not yet executable \u2014 unmet requirement(s): ${diagnosis.requirements.join(", ")}. It will not advance until those are satisfied.`;
369
- case "completed":
370
- return `Completed at ${diagnosis.at}.`;
371
- case "aborted":
372
- return diagnosis.reason !== void 0 ? `Aborted at ${diagnosis.at}: ${diagnosis.reason}.` : `Aborted at ${diagnosis.at}.`;
373
- case "stuck":
374
- return stuckSummary(diagnosis.cause);
375
- }
376
- }
377
- function stuckSummary(cause) {
378
- switch (cause.kind) {
379
- case "failed-effect":
380
- return `Stuck: a failed effect "${cause.effect.name}" is blocking activity "${cause.effect.origin.name}", which can't complete until the effect succeeds.`;
381
- case "hung-effect":
382
- 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.`;
383
- case "failed-activity":
384
- return `Stuck: activity "${cause.activity}" is in a terminal failed state, so any exit transition gated on it can never fire.`;
385
- case "no-transition-fires":
386
- return "Stuck: every activity is resolved but no exit transition's filter is satisfied \u2014 likely a routing state value a filter reads was never written.";
387
- case "transition-unevaluable":
388
- 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.`;
389
- }
390
- }
391
- function buildTools(engine, options = {}) {
392
- const accessOverride = options.access;
393
- return { descriptors: TOOL_DESCRIPTORS, impls: {
394
- list_workflow_instances: async (rawInput) => {
395
- const input = parseListInput(rawInput);
396
- return listInstances(engine, input);
397
- },
398
- get_workflow_state: async (rawInput) => {
399
- const input = parseInstanceIdInput(rawInput, "get_workflow_state");
400
- return getInstanceState({ engine, instanceId: input.instance_id, accessOverride });
401
- },
402
- diagnose_workflow: async (rawInput) => {
403
- const input = parseInstanceIdInput(rawInput, "diagnose_workflow");
404
- return getInstanceDiagnosis({ engine, instanceId: input.instance_id, accessOverride });
405
- },
406
- fire_action: async (rawInput) => {
407
- const input = parseFireActionInput(rawInput);
408
- return await engine.fireAction({
409
- instanceId: input.instance_id,
410
- activity: input.activity,
411
- action: input.action,
412
- ...input.params !== void 0 ? { params: input.params } : {},
413
- ...accessOverride !== void 0 ? { access: accessOverride } : {}
414
- }), getInstanceState({ engine, instanceId: input.instance_id, accessOverride });
415
- },
416
- // Authoring tools — engine-independent: they teach and check the DSL, they
417
- // don't touch the lake or an instance.
418
- get_workflow_authoring_guide: async () => AUTHORING_GUIDE,
419
- validate_workflow_definition: async (rawInput) => {
420
- const { definition } = parseValidateInput(rawInput);
421
- try {
422
- const stored = defineWorkflow(definition);
423
- return validateDefinition(stored), { valid: !0, definition: stored };
424
- } catch (err) {
425
- return { valid: !1, error: err instanceof Error ? err.message : String(err) };
426
- }
427
- }
428
- } };
429
- }
430
- function parseListInput(raw) {
431
- if (raw === null || typeof raw != "object")
432
- return { status: "in_flight" };
433
- const obj = raw, status = obj.status === "done" || obj.status === "any" ? obj.status : "in_flight", definition = typeof obj.definition == "string" ? obj.definition : void 0;
434
- return definition !== void 0 ? { definition, status } : { status };
435
- }
436
- function asObject(raw, tool) {
437
- if (raw === null || typeof raw != "object")
438
- throw new Error(`${tool}: input must be an object`);
439
- return raw;
440
- }
441
- function requireString({
442
- obj,
443
- key,
444
- tool
445
- }) {
446
- const value = obj[key];
447
- if (typeof value != "string" || value === "")
448
- throw new Error(`${tool}: ${key} is required`);
449
- return value;
450
- }
451
- function parseValidateInput(raw) {
452
- const obj = asObject(raw, "validate_workflow_definition");
453
- if (obj.definition === null || typeof obj.definition != "object")
454
- throw new Error("validate_workflow_definition: `definition` is required and must be an object");
455
- return { definition: obj.definition };
456
- }
457
- function parseInstanceIdInput(raw, tool) {
458
- const obj = asObject(raw, tool);
459
- return { instance_id: requireString({ obj, key: "instance_id", tool }) };
460
- }
461
- function parseFireActionInput(raw) {
462
- const obj = asObject(raw, "fire_action");
463
- let params;
464
- if (obj.params !== void 0) {
465
- if (obj.params === null || typeof obj.params != "object" || Array.isArray(obj.params))
466
- throw new Error("fire_action: params must be an object");
467
- params = obj.params;
468
- }
469
- return {
470
- instance_id: requireString({ obj, key: "instance_id", tool: "fire_action" }),
471
- activity: requireString({ obj, key: "activity", tool: "fire_action" }),
472
- action: requireString({ obj, key: "action", tool: "fire_action" }),
473
- ...params !== void 0 ? { params } : {}
474
- };
475
- }
476
- async function listInstances(engine, input) {
477
- const groqParts = [`_type == "${WORKFLOW_INSTANCE_TYPE}"`];
478
- input.definition !== void 0 && groqParts.push("definition == $definition");
479
- const groq = `*[${groqParts.join(" && ")} && ${tagScopeFilter()}] | order(lastChangedAt desc)[0...${LIST_CAP}]`, params = {};
480
- input.definition !== void 0 && (params.definition = input.definition);
481
- const filtered = (await engine.query({ groq, params })).filter((doc) => {
482
- const done = isInstanceDone(doc);
483
- return input.status === "done" ? done : input.status === "in_flight" ? !done : !0;
484
- }), subjectTitles = await fetchSubjectTitles(engine, filtered);
485
- return {
486
- instances: filtered.map((doc) => projectSummary(doc, subjectTitles))
487
- };
488
- }
489
- async function getInstanceState({
490
- engine,
491
- instanceId,
492
- accessOverride
493
- }) {
494
- const evaluation = await engine.evaluate({
495
- instanceId,
496
- ...accessOverride !== void 0 ? { access: accessOverride } : {}
497
- }), instance = await engine.getInstance({ instanceId }), subjectTitles = await fetchSubjectTitles(engine, [instance]);
498
- return projectState({ instance, evaluation, subjectTitles });
499
- }
500
- async function getInstanceDiagnosis({
501
- engine,
502
- instanceId,
503
- accessOverride
504
- }) {
505
- const { diagnosis, remediations } = await engine.diagnose({
506
- instanceId,
507
- ...accessOverride !== void 0 ? { access: accessOverride } : {}
508
- });
509
- return {
510
- instanceId,
511
- state: diagnosis.state,
512
- summary: diagnosisSummary(diagnosis),
513
- ...diagnosis.state === "stuck" ? { cause: diagnosis.cause.kind } : {},
514
- remediations
515
- };
516
- }
517
- export {
518
- buildTools
519
- };
520
- //# sourceMappingURL=index.js.map
3
+ export { WORKFLOW_TOOLS, registerWorkflowTools, toolInputJsonSchema, workflowAddressFromInput };
package/dist/stdio.d.ts CHANGED
@@ -1,12 +1,16 @@
1
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.
2
+ * stdio MCP host — boots an {@link McpServer} from
3
+ * `@modelcontextprotocol/sdk`, binds the workflow tools, and listens on
4
+ * stdio.
5
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.
6
+ * The server is org-authed: boot config is the org-level
7
+ * `SANITY_AUTH_TOKEN` (plus an optional `SANITY_API_HOST`) and nothing
8
+ * else no project, dataset, resource, or tag. Every instance-operating
9
+ * tool call names its own workflow environment (`workflow_resource` +
10
+ * `tag`, see `./address.ts`), and the host builds one engine per
11
+ * distinct environment, cached for the life of the process (see
12
+ * `./engine-cache.ts`). Same model as the Sanity MCP: auth says who may
13
+ * act, the call says where.
10
14
  *
11
15
  * Kept as its own package entry (not inline in `bin/`) so it can be
12
16
  * compiled to `dist/stdio.js` by pkg-utils and re-used by both the
@@ -15,9 +19,9 @@
15
19
  * keeps the MCP transport deps out of the library import graph.
16
20
  */
17
21
  /**
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).
22
+ * Read the org token, register the tools, and serve on stdio. Resolves
23
+ * when the transport is connected (the process then stays alive on the
24
+ * open stdio streams).
21
25
  */
22
26
  export declare function runStdioServer(): Promise<void>;
23
27