1
---
2
name: flowstudio-power-automate-debug
3
description: >-
4
Debug failing Power Automate cloud flows using the FlowStudio MCP server.
5
The Graph API only shows top-level status codes. This skill gives your agent
6
action-level inputs and outputs to find the actual root cause.
7
Load this skill when asked to: debug a flow, investigate a failed run, why is
8
this flow failing, inspect action outputs, find the root cause of a flow error,
9
fix a broken Power Automate flow, diagnose a timeout, trace a DynamicOperationRequestFailure,
10
check connector auth errors, read error details from a run, or troubleshoot
11
expression failures. Requires a FlowStudio MCP subscription — see https://mcp.flowstudio.app
12
---
13
14
# Power Automate Debugging with FlowStudio MCP
15
16
A step-by-step diagnostic process for investigating failing Power Automate
17
cloud flows through the FlowStudio MCP server.
18
19
> **Real debugging examples**: [Expression error in child flow](https://github.com/ninihen1/power-automate-mcp-skills/blob/main/examples/fix-expression-error.md) |
20
> [Data entry, not a flow bug](https://github.com/ninihen1/power-automate-mcp-skills/blob/main/examples/data-not-flow.md) |
21
> [Null value crashes child flow](https://github.com/ninihen1/power-automate-mcp-skills/blob/main/examples/null-child-flow.md)
22
23
**Prerequisite**: A FlowStudio MCP server must be reachable with a valid API key or sign-in.
24
See the `flowstudio-power-automate-mcp` skill for connection setup.
25
Subscribe at https://mcp.flowstudio.app
26
27
---
28
29
## Source of Truth
30
31
> **Always call `tool_search` first** (`skill:debug-flow`, then `select:` each
32
> other tool used below; most sit in other bundles) to confirm tool names and
33
> parameter schemas.
34
> This skill covers response shapes, behavioral notes, and diagnostic patterns —
35
> things tool schemas cannot tell you. If this document disagrees with
36
> `tool_search` or a real API response, the API wins.
37
38
---
39
40
## Python Helper
41
42
```python
43
import json, time, urllib.request
44
45
MCP_URL = "https://mcp.flowstudio.app/mcp"
46
MCP_TOKEN = "<YOUR_API_KEY>"
47
48
def mcp(tool, **kwargs):
49
payload = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call",
50
"params": {"name": tool, "arguments": kwargs}}).encode()
51
req = urllib.request.Request(MCP_URL, data=payload,
52
headers={"x-api-key": MCP_TOKEN, "Content-Type": "application/json",
53
"User-Agent": "FlowStudio-MCP/1.0"})
54
try:
55
resp = urllib.request.urlopen(req, timeout=120)
56
except urllib.error.HTTPError as e:
57
body = e.read().decode("utf-8", errors="replace")
58
raise RuntimeError(f"MCP HTTP {e.code}: {body[:200]}") from e
59
raw = json.loads(resp.read())
60
if "error" in raw:
61
raise RuntimeError(f"MCP error: {json.dumps(raw['error'])}")
62
res = raw["result"]
63
if res.get("isError"): # refusals and failed calls: may not be JSON
64
raise RuntimeError(res["content"][0]["text"][:500])
65
return json.loads(res["content"][0]["text"])
66
67
ENV = "<environment-id>" # e.g. Default-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
68
```
69
70
---
71
72
## Step 1 — Locate the Flow
73
74
```python
75
result = mcp("list_live_flows", environmentName=ENV, search="My Flow Name")
76
# Returns a wrapper object: {mode, flows, totalCount, error}
77
target = result["flows"][0]
78
FLOW_ID = target["id"] # plain UUID — use directly as flowName
79
print(FLOW_ID)
80
```
81
82
---
83
84
## Step 2 — Find the Failing Run
85
86
```python
87
res = mcp("get_live_flow_runs", environmentName=ENV, flowName=FLOW_ID,
88
status="Failed", top=5) # also startedAfter / startedBefore (date-times)
89
runs = res["runs"] # newest first, filtered by Power Automate across pages
90
# res: {"runs": [{"name": "08584296...CU15", "status": "Failed",
91
# "startTime": "...", "endTime": "...", "triggerName": "manual",
92
# "error": {"code": "ActionFailed", ...}}, ...],
93
# "runCount": 5, "runFilter": "status eq 'Failed'", "triggerChecks": null}
94
# NO RUNS != healthy. With no status or date filter, zero runs fills
95
# res["triggerChecks"]. byStatus: Skipped = polled, nothing new (not
96
# an error); Failed = trigger error: pass its checkId to outputs tool.
97
98
RUN_ID = runs[0]["name"] # runName="latest" also picks the newest run
99
```
100
101
---
102
103
## Step 3 — Get the Top-Level Error
104
105
> **CRITICAL**: `get_live_flow_run_error` tells you **which** action failed.
106
> `get_live_flow_run_action_outputs` tells you **why**. You must call BOTH.
107
> Never stop at the error alone — error codes like `ActionFailed`,
108
> `NotSpecified`, and `InternalServerError` are generic wrappers. The actual
109
> root cause (wrong field, null value, HTTP 500 body, stack trace) is only
110
> visible in the action's inputs and outputs.
111
112
```python
113
err = mcp("get_live_flow_run_error",
114
environmentName=ENV, flowName=FLOW_ID, runName=RUN_ID)
115
# Returns:
116
# {
117
# "runName": "08584296068667933411438594643CU15",
118
# "failedActions": [
119
# {"actionName": "Apply_to_each_prepare_workers", "status": "Failed",
120
# "code": "ActionFailed", "error": {"code": "ActionFailed", ...},
121
# "startTime": "...", "endTime": "..."},
122
# {"actionName": "HTTP_find_AD_User_by_Name", "status": "Failed",
123
# "code": "NotSpecified", "startTime": "...", "endTime": "..."}
124
# ],
125
# "allActions": [
126
# {"actionName": "Apply_to_each", "status": "Skipped"},
127
# {"actionName": "Compose_WeekEnd", "status": "Succeeded"},
128
# ...
129
# ]
130
# }
131
132
# failedActions is in name order, not run order. Containers (Foreach, Scope,
133
# Condition) fail with ActionFailed; the ROOT is the entry that does not:
134
fa = err["failedActions"]
135
root = next((a for a in fa if a.get("code") != "ActionFailed"), fa[-1])
136
print(f"Root action: {root['actionName']} → code: {root.get('code')}")
137
138
# allActions shows every action's status — useful for spotting what was Skipped
139
# See common-errors.md to decode the error code.
140
```
141
142
---
143
144
## Step 4 — Inspect the Failing Action's Inputs and Outputs
145
146
> **This is the most important step.** The real error detail — HTTP status,
147
> response body, stack trace, null value — lives in the action's inputs and outputs.
148
149
```python
150
# Get the root failing action's full inputs and outputs
151
root_action = root["actionName"]
152
detail = mcp("get_live_flow_run_action_outputs",
153
environmentName=ENV,
154
flowName=FLOW_ID,
155
runName=RUN_ID,
156
actionName=root_action)
157
158
reps = detail.get("actions") or detail.get("repetitions", [])
159
if len(reps) > 1:
160
print(f"{root_action} returned {len(reps)} repetitions; inspect iteration indexes")
161
out = reps[0] if reps else {}
162
print(f"Action: {out.get('actionName')}")
163
print(f"Status: {out.get('status')}")
164
165
# For HTTP actions, the real error is in outputs.body
166
if isinstance(out.get("outputs"), dict):
167
status_code = out["outputs"].get("statusCode")
168
body = out["outputs"].get("body", {})
169
print(f"HTTP {status_code}")
170
print(json.dumps(body, indent=2)[:500])
171
172
# Error bodies are often nested JSON strings — parse them
173
if isinstance(body, dict) and "error" in body:
174
err_detail = body["error"]
175
if isinstance(err_detail, str):
176
err_detail = json.loads(err_detail)
177
print(f"Error: {err_detail.get('message', err_detail)}")
178
179
# For expression errors, the error is in the error field
180
if out.get("error"):
181
print(f"Error: {out['error']}")
182
183
# Also check inputs — they show what expression/URL/body was used
184
if out.get("inputs"):
185
print(f"Inputs: {json.dumps(out['inputs'], indent=2)[:500]}")
186
```
187
188
### What the action outputs reveal (that error codes don't)
189
190
| Error code from `get_live_flow_run_error` | What `get_live_flow_run_action_outputs` reveals |
191
|---|---|
192
| `ActionFailed` | Which nested action actually failed and its HTTP response |
193
| `NotSpecified` | The HTTP status code + response body with the real error |
194
| `InternalServerError` | The server's error message, stack trace, or API error JSON |
195
| `InvalidTemplate` | The exact expression that failed and the null/wrong-type value |
196
| `BadRequest` | The request body that was sent and why the server rejected it |
197
198
### Foreach iterations
199
200
When `actionName` refers to an action inside a foreach, the output tool can
201
return every repetition of that action. Each item may include
202
`repetitionIndexes` with the loop name and zero-based `itemIndex`. Use
203
`iterationIndex` to inspect one iteration after you find the suspicious item:
204
205
```python
206
all_reps = mcp("get_live_flow_run_action_outputs",
207
environmentName=ENV, flowName=FLOW_ID,
208
runName=RUN_ID,
209
actionName=root_action)
210
211
for rep in all_reps["repetitions"][:10]:
212
print(rep.get("repetitionIndexes"), rep.get("status"), rep.get("error"))
213
214
one_rep = mcp("get_live_flow_run_action_outputs",
215
environmentName=ENV,
216
flowName=FLOW_ID,
217
runName=RUN_ID,
218
actionName=root_action,
219
iterationIndex=3)
220
```
221
222
### Evidence Compose Bookends
223
224
For uncertain connector work, add a `Compose_*_Request` before the risky action
225
and a `Compose_*_Result` after it, with the result action allowed on both
226
`Succeeded` and `Failed`. This gives future debugging a clean payload snapshot
227
without requiring another deploy. Do not include secrets or long binary payloads
228
in these bookends.
229
230
### Example: HTTP action returning 500
231
232
```
233
Error code: "InternalServerError" ← this tells you nothing
234
235
Action outputs reveal:
236
HTTP 500
237
body: {"error": "Cannot read properties of undefined (reading 'toLowerCase')
238
at getClientParamsFromConnectionString (storage.js:20)"}
239
← THIS tells you the Azure Function crashed because a connection string is undefined
240
```
241
242
### Example: Expression error on null
243
244
```
245
Error code: "BadRequest" ← generic
246
247
Action outputs reveal:
248
inputs: "body('HTTP_GetTokenFromStore')?['token']?['access_token']"
249
outputs: "" ← empty string, the path resolved to null
250
← THIS tells you the response shape changed — token is at body.access_token, not body.token.access_token
251
```
252
253
---
254
255
## Step 5 — Read the Flow Definition
256
257
```python
258
# summary: the action tree (name, type, runAfter, nesting), no inputs
259
tree = mcp("get_live_flow", environmentName=ENV, flowName=FLOW_ID, depth="summary")
260
print(tree["properties"]["definition"]["actionTree"])
261
# actions: just these, at any depth. Never save this back as a whole definition
262
defn = mcp("get_live_flow", environmentName=ENV, flowName=FLOW_ID, actions=[root_action])
263
264
# What changed since it last worked? A run name works as a version
265
# ("from" is a Python keyword, so pass it through **{})
266
ok = mcp("get_live_flow_runs", environmentName=ENV, flowName=FLOW_ID,
267
status="Succeeded", top=1)["runs"]
268
if ok:
269
print(mcp("diff_live_flow", environmentName=ENV, flowName=FLOW_ID,
270
**{"from": ok[0]["name"]})) # {added, removed, changed, triggers}
271
```
272
273
Inspect the failing action's `inputs` expression to see what data it expects.
274
275
---
276
277
## Step 6 — Walk Back from the Failure
278
279
When the failing action's inputs reference upstream actions, inspect those
280
too. Walk backward through the chain until you find the source of the
281
bad data:
282
283
```python
284
# No actionName: every action, any depth, one call; payloads capped at
285
# 4,000 chars ({truncated, preview}); the list is not in run order
286
survey = mcp("get_live_flow_run_action_outputs",
287
environmentName=ENV, flowName=FLOW_ID, runName=RUN_ID)
288
for out in sorted(survey["actions"], key=lambda a: a.get("startTime") or ""):
289
print(out["actionName"], out.get("status")) # names only: payloads can hold secrets
290
# Then read only the actions you suspect, with actionName (Step 4)
291
```
292
293
> ⚠️ A payload over 1 MB comes back as `{tooLarge, bytes, link, linkExpiresAt, note}`
294
> instead of the data: `link` downloads it with a plain GET, no sign-in, until it
295
> expires. Inside a foreach, pass `iterationIndex` to avoid every repetition.
296
297
---
298
299
## Step 7 — Pinpoint the Root Cause
300
301
### Expression Errors (e.g. `split` on null)
302
If the error mentions `InvalidTemplate` or a function name:
303
1. Find the action in the definition
304
2. Check what upstream action/expression it reads
305
3. **Inspect that upstream action's output** for null / missing fields
306
307
```python
308
# Example: action uses split(item()?['Name'], ' ')
309
# → null Name in the source data. A Compose's outputs IS the value;
310
# Select and Filter array put it in outputs.body
311
reps = mcp("get_live_flow_run_action_outputs", ..., actionName="Compose_Names")["actions"]
312
names = (reps[0].get("outputs") or []) if reps else []
313
nulls = [x for x in names if x.get("Name") is None]
314
print(f"{len(nulls)} records with null Name")
315
```
316
317
### Wrong Field Path
318
Expression `triggerBody()?['fieldName']` returns null → `fieldName` is wrong.
319
**Inspect the trigger output** to see the actual field names:
320
```python
321
trig = mcp("get_live_flow_run_action_outputs", ..., trigger=True) # not actionName
322
print(json.dumps(trig.get("outputs"), indent=2)[:500])
323
```
324
325
### HTTP Actions Returning Errors
326
The error code says `InternalServerError` or `NotSpecified` — **always inspect
327
the action outputs** to get the actual HTTP status and response body:
328
```python
329
out = mcp("get_live_flow_run_action_outputs", ..., actionName="HTTP_Get_Data")["actions"][0]
330
print(f"HTTP {out['outputs']['statusCode']}")
331
print(json.dumps(out['outputs']['body'], indent=2)[:500])
332
```
333
334
### Connection / Auth Failures
335
`ConnectionAuthorizationFailed` / `InvalidConnectionCredentials`: check it with
336
`test_live_connection`. `create_live_connection` with `connectionName` signs it in
337
again: give the person `signInLink` (you never sign in for them). Or bind a working
338
connection (`list_live_connections` `search` → template, then `update_live_flow`).
339
340
### Outlook user-picker failures (`DynamicListValuesUndefinedOrInvalid`)
341
Outlook `To`/`Cc`/`From`/`mailboxAddress` pickers use `AadGraph.GetUsers`, which
342
Power Automate's own lookup refuses. `resolve_live_parameters` searches people the
343
way the designer does: pass `search` or `match` (a name or email). An email address
344
typed directly also works.
345
346
---
347
348
## Step 8 — Apply the Fix
349
350
**For expression/data issues**:
351
```python
352
# Surgical edit; inside a loop the path is ["actions", "<Loop>", "actions", ...]
353
ops = [{"op": "set", "path": ["actions", "Compose_Names", "inputs"],
354
"value": "@coalesce(item()?['Name'], 'Unknown')"}]
355
print(mcp("update_live_flow", environmentName=ENV, flowName=FLOW_ID,
356
operations=ops, dryRun=True)["changes"]) # preview, writes nothing
357
result = mcp("update_live_flow", environmentName=ENV, flowName=FLOW_ID, operations=ops)
358
359
# Still saving after 25 s → {taskId, status: "working", pollIntervalMs}.
360
# NEVER call update_live_flow again (duplicates) — poll get_task:
361
while result.get("status") == "working":
362
time.sleep(result["pollIntervalMs"] / 1000)
363
result = mcp("get_task", taskId=result["taskId"])
364
if "taskId" in result: # the save's own reply is in result
365
if result["status"] == "failed" or result.get("isError"):
366
raise RuntimeError(result.get("statusMessage") or result.get("result"))
367
result = result["result"]
368
print(result.get("error")) # None = success
369
```
370
371
> ⚠️ A refused save raises (`isError`). If an unpublished portal draft blocks it
372
> (`XrmApiServerError`), it may hold someone else's work: ask the person to
373
> publish it, or to approve `discardDraft=True`.
374
375
---
376
377
## Step 9 — Verify the Fix
378
379
> **Use `resubmit_live_flow_run` to test ANY flow.** It replays a past run with
380
> its original trigger payload — Recurrence, SharePoint, connector webhooks,
381
> Button and HTTP alike — so there is no wait for the next real event. It cannot
382
> help a **brand-new flow that has never run**.
383
384
```python
385
# Resubmit the failed run — works for ANY trigger type
386
resubmit = mcp("resubmit_live_flow_run",
387
environmentName=ENV, flowName=FLOW_ID, runName=RUN_ID)
388
print(resubmit) # {"resubmitted": true, "triggerName": "..."}
389
390
# Wait ~30 s then check
391
time.sleep(30)
392
new_runs = mcp("get_live_flow_runs", environmentName=ENV, flowName=FLOW_ID, top=3)["runs"]
393
print(new_runs[0]["status"]) # Succeeded = done
394
```
395
396
### When to use resubmit vs trigger
397
398
| Scenario | Use | Why |
399
|---|---|---|
400
| **Testing a fix** on any flow | `resubmit_live_flow_run` | Replays the exact trigger payload that caused the failure — best way to verify |
401
| Recurrence / scheduled flow | `trigger_live_flow` (no `body`) | Runs it now, like the portal's "Run flow" button; resubmit replays a past run's data |
402
| SharePoint / connector trigger | `resubmit_live_flow_run` | Cannot be triggered without creating a real SP item |
403
| HTTP, Button, PowerApps or Skills trigger, **custom** payload | `trigger_live_flow` | When you need to send different data than the original run |
404
| Brand-new Request or Recurrence flow | `trigger_live_flow` | No prior run to resubmit |
405
406
### Testing HTTP, Button, PowerApps and Skills flows with custom payloads
407
408
For flows with a `Request` trigger (HTTP request, manual Button, PowerApps or Skills),
409
use `trigger_live_flow` when you need to send a **different** payload than the
410
original run. Pass trigger inputs as `body` for every kind:
411
412
```python
413
# First inspect what the trigger expects (summary keeps triggers whole)
414
defn = mcp("get_live_flow", environmentName=ENV, flowName=FLOW_ID, depth="summary")
415
manual = next(iter(defn["properties"]["definition"]["triggers"].values()))
416
print("Expected body schema:", manual.get("inputs", {}).get("schema"))
417
418
# Trigger with a test payload
419
result = mcp("trigger_live_flow",
420
environmentName=ENV,
421
flowName=FLOW_ID,
422
body={"name": "Test User", "value": 42})
423
print(f"Status: {result['responseStatus']}, Body: {result.get('responseBody')}")
424
print(f"Kind: {result['triggerKind']}, via: {result['invocation']}, run: {result.get('runName')}")
425
if result.get("warning"):
426
print(result["warning"]) # required trigger inputs you left out
427
```
428
429
> `trigger_live_flow` handles AAD-authenticated triggers. A scheduled flow runs
430
> now with no `body` (a body is refused); automated connector triggers only fire
431
> from their source event.
432
>
433
> Power Automate does not enforce a trigger's `required` inputs. If you leave
434
> one out the run still starts, with that input null, and the result carries a
435
> `warning` naming the missing keys. Cancel the run and call again with the
436
> full body if that matters.
437
>
438
> `runName` comes back only when a `body` went through the connector runtime
439
> (Button, PowerApps, Skills). Otherwise find the run with `get_live_flow_runs`.
440
>
441
> A browser-extension key sends inputs too, through the extension (1.0.19 or later).
442
443
---
444
445
## Quick-Reference Diagnostic Decision Tree
446
447
| Symptom | First Tool | Then ALWAYS Call | What to Look For |
448
|---|---|---|---|
449
| Flow shows as Failed | `get_live_flow_run_error` | `get_live_flow_run_action_outputs` on the failing action | HTTP status + response body in `outputs` |
450
| Error code is generic (`ActionFailed`, `NotSpecified`) | — | `get_live_flow_run_action_outputs` | The `outputs.body` contains the real error message, stack trace, or API error |
451
| HTTP action returns 500 | — | `get_live_flow_run_action_outputs` | `outputs.statusCode` + `outputs.body` with server error detail |
452
| Expression crash | — | `get_live_flow_run_action_outputs` on prior action | null / wrong-type fields in output body |
453
| Flow never starts | `get_live_flow` (`state`) | `get_live_flow_runs`, no filter | Failed in `byStatus`; Skipped is normal |
454
| Worked before, fails now | `get_live_flow_versions` | `diff_live_flow` | actions added, removed or changed |
455
| Action returns wrong data | `get_live_flow_run_action_outputs` | — | actual output body vs expected |
456
| Fix applied but still fails | `get_live_flow_runs` after resubmit | — | new run `status` field |
457
458
---
459
460
## Reference Files
461
462
- [common-errors.md](references/common-errors.md) — Error codes, likely causes, and fixes
463
- [debug-workflow.md](references/debug-workflow.md) — Full decision tree for complex failures
464
465
## Related Skills
466
467
- `flowstudio-power-automate-mcp` — Foundation skill: connection setup, MCP helper, tool discovery
468
- `flowstudio-power-automate-build` — Build and deploy new flows
469