1
---
2
name: flowstudio-power-automate-build
3
description: >-
4
Build, scaffold, and deploy Power Automate cloud flows using the FlowStudio
5
MCP server. Your agent constructs flow definitions, wires connections, deploys,
6
and tests — all via MCP without opening the portal.
7
Load this skill when asked to: create a flow, build a new flow,
8
deploy a flow definition, scaffold a Power Automate workflow, construct a flow
9
JSON, update an existing flow's actions, patch a flow definition, add actions
10
to a flow, wire up connections, or generate a workflow definition from scratch.
11
Requires a FlowStudio MCP subscription — see https://mcp.flowstudio.app
12
---
13
14
# Build & Deploy Power Automate Flows with FlowStudio MCP
15
16
Step-by-step guide for constructing and deploying Power Automate cloud flows
17
programmatically through the FlowStudio MCP server.
18
19
**Prerequisite**: A FlowStudio MCP server must be reachable with a valid API key or sign-in.
20
See the `flowstudio-power-automate-mcp` skill for connection setup.
21
Subscribe at https://mcp.flowstudio.app
22
23
Workflow:
24
1. Load current build tools.
25
2. Check for an existing flow.
26
3. Resolve connection references.
27
4. Build the definition.
28
5. Deploy.
29
6. Verify.
30
7. Test.
31
32
---
33
34
## Source of Truth
35
36
> If this file disagrees with `tool_search` or a real response, the server 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 saves: may not be JSON
64
raise RuntimeError(res["content"][0]["text"][:1000])
65
return json.loads(res["content"][0]["text"])
66
67
def save(**kwargs): # update_live_flow that waits out a save past 25 s
68
res = mcp("update_live_flow", **kwargs)
69
while res.get("status") == "working": # never call update_live_flow again
70
time.sleep(res["pollIntervalMs"] / 1000)
71
res = mcp("get_task", taskId=res["taskId"])
72
if "taskId" not in res:
73
return res
74
if res["status"] == "failed" or res.get("isError"):
75
raise RuntimeError(res.get("statusMessage") or res.get("result"))
76
return res["result"]
77
78
ENV = "<environment-id>" # e.g. Default-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
79
```
80
81
---
82
83
## 0. Load the Current Build Tools
84
85
For a brand-new flow, load the server's `create-flow` bundle. For editing an
86
existing flow, load `build-flow`; to put back an earlier version, `flow-versions`.
87
88
```python
89
schemas = mcp("tool_search", query="skill:create-flow")
90
# Includes list_live_environments, list_live_connections,
91
# describe_live_connector, resolve_live_parameters, update_live_flow.
92
```
93
94
If you need a tool outside the bundle, load it explicitly:
95
96
```python
97
mcp("tool_search", query="select:get_task,create_live_connection")
98
```
99
100
---
101
102
## 1. Safety Check: Does the Flow Already Exist?
103
104
Always look before you build to avoid duplicates:
105
106
```python
107
results = mcp("list_live_flows",
108
environmentName=ENV,
109
mode="owner",
110
search="My New Flow",
111
top=20)
112
113
# list_live_flows returns { "flows": [...], "mode": "...", ... }
114
matches = [f for f in results["flows"]
115
if "My New Flow".lower() in f["displayName"].lower()]
116
117
if len(matches) > 0:
118
# Flow exists — modify rather than create
119
FLOW_ID = matches[0]["id"] # plain UUID from list_live_flows
120
print(f"Existing flow: {FLOW_ID}")
121
defn = mcp("get_live_flow", environmentName=ENV, flowName=FLOW_ID)
122
else:
123
print("Flow not found — building from scratch")
124
FLOW_ID = None
125
```
126
127
For very large environments, `list_live_flows` may return a continuation URL.
128
Pass it back as `continuationUrl` with the same `mode` to retrieve the next
129
batch. Use `mode="admin"` only when the user needs all environment flows and
130
the MCP identity has admin rights.
131
132
---
133
134
## 2. Obtain Connection References
135
136
Every connector action needs a `connectionName` that points to a key in the
137
flow's `connectionReferences` map. That key links to an authenticated connection
138
in the environment.
139
140
> **MANDATORY**: You MUST call `list_live_connections` first — do NOT ask the
141
> user for connection names or GUIDs. The API returns the exact values you need.
142
> Only prompt the user if the API confirms that required connections are missing.
143
144
### 2a — Find active connections
145
146
```python
147
conns = mcp("list_live_connections", environmentName=ENV)
148
active = [c for c in conns["connections"]
149
if (c.get("statuses") or [{}])[0].get("status") == "Connected"]
150
conn_map = {c["connectorName"]: c["id"] for c in active}
151
```
152
153
For a known connector, pass `search` to reduce output and get paste-ready
154
`connectionReferenceTemplate` and `hostTemplate` values:
155
156
```python
157
sp_conns = mcp("list_live_connections",
158
environmentName=ENV,
159
search="shared_sharepointonline")
160
```
161
162
### 2b — Determine which connectors the flow needs
163
164
Common connector API names: SharePoint `shared_sharepointonline`, Outlook
165
`shared_office365`, Teams `shared_teams`, Approvals `shared_approvals`,
166
OneDrive `shared_onedriveforbusiness`, Excel `shared_excelonlinebusiness`,
167
Dataverse `shared_commondataserviceforapps`, Forms `shared_microsoftforms`.
168
169
Flows that need no connectors, such as Recurrence + Compose + HTTP only, can
170
omit `connectionReferences`.
171
172
### 2c — If connections are missing, create them with the user
173
174
```python
175
connectors_needed = ["shared_sharepointonline", "shared_office365"] # adjust per flow
176
missing = [c for c in connectors_needed if c not in conn_map]
177
for connector in missing:
178
# Shows the person a sign-in card; they sign in, never you. Give them
179
# signInLink too (expires in about 10 minutes), then re-run Step 2a.
180
new = mcp("create_live_connection", environmentName=ENV, connectorName=connector)
181
print(connector, new.get("signInLink"))
182
```
183
184
Connectors that need a key or account details are refused: the person creates
185
those in Power Automate.
186
187
### 2d — Build the connectionReferences block
188
189
```python
190
connection_references = {}
191
for connector in connectors_needed:
192
c = next(c for c in active if c["connectorName"] == connector)
193
connection_references[connector] = { # map key = inputs.host.connectionName
194
"connectionName": c["id"], # the connection id
195
"id": f"/providers/Microsoft.PowerApps/apis/{connector}",
196
}
197
```
198
199
In Step 3 action JSON, `inputs.host.connectionName` must be the map key such as
200
`shared_teams`, not the connection id. Leave out `"source": "Invoker"`: it saves
201
the connection as "provided by run-only user". `list_live_connections` with
202
`search` returns templates keyed by the connection id: merge
203
`connectionReferenceTemplate`; `inputs.host` is `hostTemplate` + `operationId`.
204
For a flow in a solution, copy `properties.connectionReferences` from
205
`get_live_flow` and keep `connectionReferenceLogicalName` and `source` exactly.
206
207
---
208
209
## 3. Build the Flow Definition
210
211
Construct the definition object. See [flow-schema.md](references/flow-schema.md)
212
for the full schema and these action pattern references for copy-paste templates:
213
- [action-patterns-core.md](references/action-patterns-core.md) — Variables, control flow, expressions
214
- [action-patterns-data.md](references/action-patterns-data.md) — Array transforms, HTTP, parsing
215
- [action-patterns-connectors.md](references/action-patterns-connectors.md) — SharePoint, Outlook, Teams, Approvals
216
217
```python
218
definition = {
219
"$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
220
"contentVersion": "1.0.0.0",
221
"triggers": { ... }, # see trigger-types.md / build-patterns.md
222
"actions": { ... } # see ACTION-PATTERNS-*.md / build-patterns.md
223
}
224
```
225
226
> See [build-patterns.md](references/build-patterns.md) for complete, ready-to-use
227
> flow definitions covering Recurrence+SharePoint+Teams, HTTP triggers, and more.
228
229
### Discover connector operations before guessing JSON
230
231
For connector-backed triggers/actions, prefer the live connector describer over
232
hand-written shapes. It returns authored hints, canonical examples, variant
233
keys, inputs/outputs, and which inputs need live values. `search="send email"`
234
without `connectorName` searches across connectors.
235
236
```python
237
op = mcp("describe_live_connector",
238
environmentName=ENV,
239
connectorName="shared_office365",
240
operationId="SendEmailV2")
241
hints = op.get("hints") or {}
242
print(hints.get("hint"), hints.get("exampleDefinition"))
243
```
244
245
If an operation has authored variants (Teams `PostMessageToConversation`:
246
`channel`, `groupchat`, `flowbot_chat`), pass `variant` for that example.
247
248
For live values — SharePoint sites, lists and columns, Teams teams and channels,
249
folders, people — call `resolve_live_parameters`. It resolves every input in one
250
call, or one with `parameterName`; `match` turns a display name into the value
251
to write:
252
253
```python
254
vals = mcp("resolve_live_parameters",
255
environmentName=ENV,
256
connectorName="shared_sharepointonline",
257
operationId="GetItems",
258
parameters={"dataset": "<site-url>"},
259
match={"table": "Invoices"})
260
print(vals["parameters"]) # values chosen so far, ready for inputs.parameters
261
for f in vals["fields"]: # status: ok, given, needs, nomatch, error
262
print(f["name"], f.get("status"), f.get("matched") or f.get("values", [])[:5])
263
```
264
265
`include=["outputs"]` returns the fields the action produces. For an action
266
already in a flow, pass `flowName` + `actionName` instead of the connector.
267
268
---
269
270
## 4. Deploy (Create or Update)
271
272
`update_live_flow` handles both creation and updates in a single tool.
273
274
### Create a new flow (no existing flow)
275
276
Omit `flowName` — Power Automate creates the flow and assigns its id. Preview
277
first with `dryRun=True`: it writes nothing and returns the flow it would create.
278
279
```python
280
definition["description"] = "Weekly SharePoint → Teams notification flow, built by agent"
281
282
result = save( # helper above: waits out a long save, raises on refusal
283
environmentName=ENV,
284
# flowName omitted → creates a new flow
285
definition=definition,
286
connectionReferences=connection_references,
287
displayName="Overdue Invoice Notifications"
288
)
289
FLOW_ID = result["flowName"] # created is just True; the new id is flowName
290
print(f"✅ Flow created: {FLOW_ID}")
291
```
292
293
### Update an existing flow
294
295
To change one action, pass `operations` instead of a whole definition, and
296
`dryRun=True` first to preview (writes nothing; `changes` shows before/after):
297
298
```python
299
ops = [{"op": "set", "path": ["actions", "Send_Email", "inputs", "parameters",
300
"emailMessage/Subject"], "value": "Weekly report"}]
301
result = save(environmentName=ENV, flowName=FLOW_ID, operations=ops)
302
```
303
304
`path` is a list of literal keys (array items by index); ops are `set`, `add`,
305
`remove`, `merge`. For a whole definition, pass `expectedLastModifiedTime`
306
(`get_live_flow`'s `properties.lastModifiedTime`) so the save is refused if the
307
flow changed in between.
308
309
> ⚠️ Read `result.get("hints")`: it names what the server fixed or warns about,
310
> such as a solution flow saved with a direct connection.
311
>
312
> ⚠️ Flow description lives at `definition["description"]` (required on create;
313
> reused on update when omitted). The server appends `#flowstudio-mcp`.
314
315
### Common deployment errors
316
317
| Error message (contains) | Cause | Fix |
318
|---|---|---|
319
| `missing from connectionReferences` | An action's `host.connectionName` references a key that doesn't exist in the `connectionReferences` map | Ensure `host.connectionName` uses the **key** from `connectionReferences` (e.g. `shared_teams`), not the raw GUID |
320
| `ConnectionAuthorizationFailed` / 403 | The connection GUID belongs to another user or is not authorized | Re-run Step 2a and use a connection owned by the current `x-api-key` user |
321
| `InvalidTemplate` / `InvalidDefinition` | Syntax error in the definition JSON | Check `runAfter` chains, expression syntax, and action type spelling |
322
| `ConnectionNotConfigured` | A connector action exists but the connection GUID is invalid or expired | Re-check `list_live_connections` for a fresh GUID |
323
| `XrmApiServerError` (unpublished draft) | A portal draft locks the solution flow | Ask the person: publish the draft, or approve `discardDraft=True` |
324
325
---
326
327
## 5. Verify the Deployment
328
329
```python
330
check = mcp("get_live_flow", environmentName=ENV, flowName=FLOW_ID)
331
332
# Confirm state
333
print("State:", check["properties"]["state"]) # Should be "Started"
334
# If state is "Stopped", use set_live_flow_state — NOT update_live_flow
335
# mcp("set_live_flow_state", environmentName=ENV, flowName=FLOW_ID, state="Started")
336
337
# Confirm the action we added is there
338
acts = check["properties"]["definition"]["actions"]
339
print("Actions:", list(acts.keys()))
340
```
341
342
If the person will call an HTTP-triggered flow by its address, read it with
343
`includeTriggerUrl=True` (`triggerUrls`); it is a credential. To put back an
344
earlier version, follow `tool_search` `skill:flow-versions`.
345
346
---
347
348
## 6. Test the Flow
349
350
> **MANDATORY**: Before triggering any test run, **ask the user for confirmation**.
351
> Running a flow has real side effects — it may send emails, post Teams messages,
352
> write to SharePoint, start approvals, or call external APIs. Explain what the
353
> flow will do and wait for explicit approval before calling `trigger_live_flow`
354
> or `resubmit_live_flow_run`.
355
356
### Updated flows (have prior runs) — ANY trigger type
357
358
> **Use `resubmit_live_flow_run` first.** It works for EVERY trigger type —
359
> Recurrence, SharePoint, connector webhooks, Button, and HTTP. It replays
360
> the original trigger payload. Do NOT ask the user to manually trigger the
361
> flow or wait for the next scheduled run.
362
363
```python
364
runs = mcp("get_live_flow_runs", environmentName=ENV, flowName=FLOW_ID, top=1)["runs"]
365
if runs:
366
# Works for Recurrence, SharePoint, connector triggers — not just HTTP
367
result = mcp("resubmit_live_flow_run",
368
environmentName=ENV, flowName=FLOW_ID, runName=runs[0]["name"])
369
print(result) # {"resubmitted": true, "triggerName": "..."}
370
```
371
372
### HTTP, Button, PowerApps and Skills flows — custom test payload
373
374
Only use `trigger_live_flow` when you need to send a **different** payload
375
than the original run. For verifying a fix, `resubmit_live_flow_run` is
376
better because it uses the exact data that caused the failure.
377
378
```python
379
defn = mcp("get_live_flow", environmentName=ENV, flowName=FLOW_ID)
380
triggers = defn["properties"]["definition"]["triggers"]
381
manual = next(iter(triggers.values()))
382
print("Expected body:", manual.get("inputs", {}).get("schema"))
383
384
result = mcp("trigger_live_flow",
385
environmentName=ENV, flowName=FLOW_ID,
386
body={"name": "Test", "value": 1})
387
print(f"Status: {result['responseStatus']}, via: {result['invocation']}")
388
print(result.get("warning")) # set when a required input was missing: the run still ran, with null
389
```
390
391
### Brand-new non-HTTP flows
392
393
A brand-new **Recurrence** flow needs no workaround: deploy it, then run it
394
immediately with `trigger_live_flow` and no `body` — same as the portal's
395
"Run flow" button. A body is refused; scheduled triggers take no inputs.
396
397
A brand-new **connector-triggered** flow (SharePoint, webhooks) has no prior
398
runs and cannot fire without a real source event. Deploy with a temporary
399
HTTP trigger, test the actions, then swap to the production trigger:
400
401
```python
402
production_trigger = definition["triggers"]
403
definition["triggers"] = {
404
"manual": {"type": "Request", "kind": "Http", "inputs": {"schema": {}}}
405
}
406
result = save(environmentName=ENV,
407
flowName=FLOW_ID, # omit if creating new
408
definition=definition, connectionReferences=connection_references,
409
displayName="Overdue Invoice Notifications")
410
FLOW_ID = FLOW_ID or result["flowName"]
411
412
mcp("trigger_live_flow", environmentName=ENV, flowName=FLOW_ID,
413
body={"sample": "payload"})
414
runs = mcp("get_live_flow_runs", environmentName=ENV, flowName=FLOW_ID, top=1)["runs"]
415
if runs[0]["status"] == "Failed":
416
err = mcp("get_live_flow_run_error",
417
environmentName=ENV, flowName=FLOW_ID, runName=runs[0]["name"])
418
raise Exception(err["failedActions"]) # name order, not run order
419
420
definition["triggers"] = production_trigger
421
save(environmentName=ENV, flowName=FLOW_ID,
422
definition=definition, connectionReferences=connection_references)
423
```
424
425
The trigger is only the entry point; testing through HTTP still exercises the
426
same actions. If actions use `triggerBody()` or `triggerOutputs()`, pass a
427
representative `body` shaped like the production trigger payload.
428
429
---
430
431
## Gotchas
432
433
| Mistake | Consequence | Prevention |
434
|---|---|---|
435
| Missing `connectionReferences` on create | "no connectionReferences were provided" | Always call `list_live_connections` first |
436
| `"operationOptions"` missing on Foreach | Parallel execution, race conditions on writes | Always add `"Sequential"` |
437
| `union(old_data, new_data)` | Old values override new (first-wins) | Use `union(new_data, old_data)` |
438
| `split()` on potentially-null string | `InvalidTemplate` crash | Wrap with `coalesce(field, '')` |
439
| Calling `update_live_flow` again after a `taskId` reply | Duplicate flows | Poll `get_task` until `completed` or `failed` (the `save` helper does) |
440
| Flow deployed but state is "Stopped" | Flow won't run on schedule | Call `set_live_flow_state` with `state: "Started"` — do **not** use `update_live_flow` for state changes |
441
| Teams "Chat with Flow bot" recipient as object | 400 `GraphUserDetailNotFound` | Use `"user@contoso.com;"` (string, trailing semicolon) |
442
| Copilot/Skills flow not in a solution | Copilot Studio may not discover it as an agent tool | After deploy, call `add_to_solution` with `flowName` and `solution` |
443
| Button/PowerApps/Skills trigger used for MCP testing | Runs even when a required input is missing (null) | Pass inputs in `trigger_live_flow` `body`; on `warning`, cancel and retry with the full body |
444
| Connector action missing `metadata.operationMetadataId` | Designer/run-only UI can behave inconsistently | Preserve existing IDs; add stable GUIDs for new connector actions |
445
| Placeholder Excel `scriptId` | Dynamic validation fails at save time | Resolve the real Office Script ID before deploying |
446
| SharePoint `PatchItem` omits required fields | Save can fail even if the field is not changing | Echo unchanged required fields such as `item/Title` |
447
| Copilot Studio connector calls a draft agent | Connector invocation can fail or hit stale behavior | Publish the agent before testing/resubmitting the flow |
448
449
---
450
451
## Reference Files
452
453
- [flow-schema.md](references/flow-schema.md) — Full flow definition JSON schema
454
- [trigger-types.md](references/trigger-types.md) — Trigger type templates
455
- [action-patterns-core.md](references/action-patterns-core.md) — Variables, control flow, expressions
456
- [action-patterns-data.md](references/action-patterns-data.md) — Array transforms, HTTP, parsing
457
- [action-patterns-connectors.md](references/action-patterns-connectors.md) — SharePoint, Outlook, Teams, Approvals
458
- [build-patterns.md](references/build-patterns.md) — Complete flow definition templates (Recurrence+SP+Teams, HTTP trigger)
459
460
## Related Skills
461
462
- `flowstudio-power-automate-mcp` — Core connection setup and tool reference
463
- `flowstudio-power-automate-debug` — Debug failing flows after deployment
464