Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

fix(power-automate): v2.5.0 — full feature set incl. large-flow update fix (#348)

Matt Townsend7fd7d329bf99
diff --git a/plugins/power-automate/.claude-plugin/plugin.json b/plugins/power-automate/.claude-plugin/plugin.json
index 10e6ea347..38a05479b 100644
--- a/plugins/power-automate/.claude-plugin/plugin.json
+++ b/plugins/power-automate/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "power-automate",
- "version": "2.3.1",
+ "version": "2.5.0",
"description": "Build, edit, run, and debug Power Automate cloud flows via the FlowAgent MCP server — connection lifecycle, surgical edits, copy across environments, run management, and validated expressions.",
"author": {
"name": "Microsoft",
diff --git a/plugins/power-automate/.plugin/plugin.json b/plugins/power-automate/.plugin/plugin.json
index 10e6ea347..38a05479b 100644
--- a/plugins/power-automate/.plugin/plugin.json
+++ b/plugins/power-automate/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "power-automate",
- "version": "2.3.1",
+ "version": "2.5.0",
"description": "Build, edit, run, and debug Power Automate cloud flows via the FlowAgent MCP server — connection lifecycle, surgical edits, copy across environments, run management, and validated expressions.",
"author": {
"name": "Microsoft",
diff --git a/plugins/power-automate/AGENTS.md b/plugins/power-automate/AGENTS.md
index 23ff9241f..59b185628 100644
--- a/plugins/power-automate/AGENTS.md
+++ b/plugins/power-automate/AGENTS.md
@@ -1,8 +1,8 @@
# AGENTS.md — power-automate plugin
Guidance for AI agents (Copilot CLI, Claude Code, Cursor) operating inside this
-plugin. The authoritative reference is the [FlowAgent repo CLAUDE.md](https://github.com/matow_microsoft/flow-agent/blob/main/CLAUDE.md);
-this file is the plugin-local routing rule.
+plugin. The authoritative reference is this plugin's `CLAUDE.md` and the
+`references/` docs; this file is the plugin-local routing rule.
## Tool routing (read first)
@@ -17,7 +17,10 @@ it handles auth (Azure CLI + MSAL), session-scoped current env/flow, structured
errors, and stays in-process. Shelling out re-pays auth cost and breaks session
state.
-Shell (`node dist/cli.js …`) is reserved for users who have the [FlowAgent engine repo](https://github.com/matow_microsoft/flow-agent) cloned and built, only for CLI-only commands the MCP does not wrap (connection lifecycle, sharing, solutions/admin), and not for plugin users when MCP tools are available.
+Shell (`node dist/cli.js …`) is reserved for users running the engine from a
+local build, only for CLI-only commands the MCP does not wrap (connection
+lifecycle, sharing, solutions/admin), and not for plugin users when MCP tools
+are available.
If the `flowagent-*` tools are missing, the MCP isn't wired — point the user at
this plugin's `.mcp.json` / the install steps in `README.md`.
@@ -32,7 +35,8 @@ this plugin's `.mcp.json` / the install steps in `README.md`.
- `.mcp.json` — MCP server wiring (FlowAgent + Microsoft Learn)
The flow-definition rules, auth model, error reference, and known issues live in
-the [FlowAgent repo CLAUDE.md](https://github.com/matow_microsoft/flow-agent/blob/main/CLAUDE.md) and apply whether you call via MCP or shell.
+this plugin's `CLAUDE.md` and `references/` docs, and apply whether you call via
+MCP or shell.
## Documentation lookup (hybrid pattern)
diff --git a/plugins/power-automate/CLAUDE.md b/plugins/power-automate/CLAUDE.md
index b8652196a..c7adffc7a 100644
--- a/plugins/power-automate/CLAUDE.md
+++ b/plugins/power-automate/CLAUDE.md
@@ -1,10 +1,10 @@
# CLAUDE.md — power-automate plugin
This is the marketplace plugin wrapper for **FlowAgent** (Power Automate cloud
-flow tooling). The **authoritative reference is the [FlowAgent repo CLAUDE.md](https://github.com/matow_microsoft/flow-agent/blob/main/CLAUDE.md)** —
-flow-definition rules, the two-provider auth model (Azure CLI + MSAL), the full
-CLI/MCP surface, the error reference, and known issues. Read it before building
-or editing flows.
+flow tooling). Flow-definition rules, the two-provider auth model (Azure CLI +
+MSAL), the error reference, and known issues are documented in `references/` —
+see `definition-reference.md`, `connection-patterns.md`, and
+`error-troubleshooting.md`. Read those before building or editing flows.
This file only covers plugin-local specifics; see `AGENTS.md` (this folder) for
the tool-routing rule.
@@ -15,13 +15,11 @@ the tool-routing rule.
`debug-flow`, `diagnose-flow`, `manage-flows`, `browse-flows`,
`manage-desktop-flows`, `route-environments`, `setup`)
- `references/` — shared docs referenced by skills via `../../references/…`
-- `.mcp.json` — launches the FlowAgent MCP server (`flowagent`)
+- `.mcp.json` — launches the FlowAgent MCP server (registered as `flowagent`)
## Engine vs plugin
-The MCP **engine** (TypeScript monorepo: `packages/core`, `packages/cli`)
-lives at the repo root and is built with `npm install &&
-npm run build`. This `plugins/power-automate/` folder is the **plugin** — it is
-designed to be lifted into the `microsoft/power-platform-skills` marketplace as
-`plugins/power-automate/`. In this source repo, `.mcp.json` launches the bundled `server/mcp.mjs` via a
-small Node bootstrap that resolves `PLUGIN_ROOT` / `CLAUDE_PLUGIN_ROOT`.
+This folder is the **plugin**: skills, references, MCP wiring, and a
+self-contained MCP engine bundled at `server/mcp.mjs`. `.mcp.json` loads that
+bundle through a small Node bootstrap that resolves the plugin's installation
+directory and reports an actionable error if the bundle is missing.
diff --git a/plugins/power-automate/README.md b/plugins/power-automate/README.md
index 2f8b7fd06..6562e879c 100644
--- a/plugins/power-automate/README.md
+++ b/plugins/power-automate/README.md
@@ -3,10 +3,8 @@
Build, edit, run, and debug **Power Automate cloud flows** from Claude Code or
GitHub Copilot CLI, powered by the **FlowAgent** MCP server.
-This plugin is the marketplace-packaged surface of
-[matow_microsoft/flow-agent](https://github.com/matow_microsoft/flow-agent). The
-MCP server (the engine) lives in that repo's `packages/` monorepo; this folder
-is the plugin (skills, MCP wiring).
+This folder is the marketplace-packaged plugin: skills, MCP wiring, and a
+self-contained MCP engine bundled at `server/mcp.mjs`.
## Install
@@ -18,12 +16,10 @@ From a Claude Code or GitHub Copilot CLI session:
```
> [!NOTE]
-> **Self-contained — no npm install or remote host required.** The plugin ships a
-> self-contained MCP engine at `server/mcp.mjs`, and `.mcp.json` launches it with
-> a small Node bootstrap that resolves `PLUGIN_ROOT` / `CLAUDE_PLUGIN_ROOT` and
-> dynamically imports `server/mcp.mjs`. (`@microsoft/power-automate-mcp` is not
-> yet on npm; the plugin does not need it.) Auth still uses your local
-> `az login` — see **MCP server** below.
+> **Runs offline — no npm install or remote host required.** The plugin ships a
+> self-contained MCP engine at `server/mcp.mjs`, and `.mcp.json` loads it through
+> a small Node bootstrap that resolves the plugin's installation directory. Auth
+> still uses your local `az login` — see **MCP server** below.
## Capabilities
@@ -31,7 +27,7 @@ From a Claude Code or GitHub Copilot CLI session:
(within/across environments), update, publish/disable, delete
- **Runs**: history, details, actions, **loop iteration drill-down**, **cancel**,
**cancel all**, **resubmit**, **diagnose**
-- **Connections**: lifecycle (CRUD, share, fix), auto-discovery, dynamic value
+- **Connections**: lifecycle (CRUD, fix), auto-discovery, dynamic value
resolution
- **Authoring**: templates/scaffolding, batch deploy, preflight + validation,
**expression help**
@@ -53,17 +49,12 @@ From a Claude Code or GitHub Copilot CLI session:
## MCP server
-`.mcp.json` launches the FlowAgent MCP server from the bundled engine with a
-small Node bootstrap that resolves `PLUGIN_ROOT` / `CLAUDE_PLUGIN_ROOT` and
-dynamically imports `server/mcp.mjs`. That file is a single self-contained ESM
-bundle (stdio transport, all 50+ tools, deps inlined), regenerated from
-`packages/cli/src/bin/mcp-stdio.ts` by `npm run build` (`scripts/bundle-plugin-mcp.mjs`).
-It needs only Node.js 18+ — no `npx`, no published npm package, no remote host.
+`.mcp.json` registers the FlowAgent MCP server under the name `flowagent` and
+loads it from the bundled engine at `server/mcp.mjs` via a small Node bootstrap
+that resolves the plugin's installation directory and reports an actionable
+error if the bundle is missing. That file is a single self-contained ESM bundle
+(stdio transport, all 50+ tools, deps inlined). It needs only Node.js 18+ — no
+`npx`, no published npm package, no remote host.
-> For local development against the monorepo you can point your client at the repo
-> root shim instead: `node <repo>/dist/mcp.js` (run `npm install && npm run build`
-> first). A publishable `@microsoft/power-automate-mcp` npm package may follow, but
-> the plugin does not depend on it.
-
-Auth uses Azure CLI (`az login`) plus MSAL for connectivity endpoints — see the
-[FlowAgent repo CLAUDE.md](https://github.com/matow_microsoft/flow-agent/blob/main/CLAUDE.md).
+Auth uses Azure CLI (`az login`) plus MSAL for connectivity endpoints — see
+`CLAUDE.md` and `references/connection-patterns.md` in this folder.
diff --git a/plugins/power-automate/references/cli-reference.md b/plugins/power-automate/references/cli-reference.md
index 87365dfbd..3cccb50bf 100644
--- a/plugins/power-automate/references/cli-reference.md
+++ b/plugins/power-automate/references/cli-reference.md
@@ -1,6 +1,6 @@
# Power Automate CLI Reference
-> Note: Shell commands below require the [FlowAgent engine repo](https://github.com/matow_microsoft/flow-agent) cloned and built. Plugin users should use MCP tools instead.
+> **Note:** These shell commands require a local engine build. If you installed this as a plugin, use the MCP tools instead — they cover the same operations.
All commands use `node dist/cli.js <command> [options]` from the project root.
diff --git a/plugins/power-automate/references/connection-patterns.md b/plugins/power-automate/references/connection-patterns.md
index 279d310a9..e85a52350 100644
--- a/plugins/power-automate/references/connection-patterns.md
+++ b/plugins/power-automate/references/connection-patterns.md
@@ -1,6 +1,6 @@
# Connection Resolution Patterns
-> Note: Shell commands below require the [FlowAgent engine repo](https://github.com/matow_microsoft/flow-agent) cloned and built. Plugin users should use MCP tools instead.
+> **Note:** These shell commands require a local engine build. If you installed this as a plugin, use the MCP tools instead — they cover the same operations.
## Discovering Connections
@@ -79,4 +79,4 @@ node dist/cli.js share-connection --env=$ENV --connector=shared_teams --connecti
1. **Always use `"source": "Embedded"`** for flows triggered via API/CLI. Invoker mode causes `InvokerConnectionOverrideFailed`.
2. **`list-connections` requires Dataverse** — if the environment lacks it, use `get-connections` instead (PowerApps API fallback).
-3. **`resolve-refs` fallback chain**: Tries Dataverse first → PowerApps API on failure → reports `NO_CONNECTION_FOUND`.
+3. **`resolve-refs` fallback chain**: Tries Dataverse first → PowerApps API on failure → reports `NO_CONNECTION_FOUND`.
\ No newline at end of file
diff --git a/plugins/power-automate/references/definition-reference.md b/plugins/power-automate/references/definition-reference.md
index 88795f7ed..ed0d2b856 100644
--- a/plugins/power-automate/references/definition-reference.md
+++ b/plugins/power-automate/references/definition-reference.md
@@ -57,6 +57,100 @@
- `Foreach`: `{ "type": "Foreach", "foreach": "@...", "actions": { ... } }`
- `Response`: `{ "type": "Response", "inputs": { "statusCode": 200, "body": "@..." } }`
+## AI Builder Prompt Action ("Run a prompt")
+
+Uses Copilot credits. The `recordId` points to a saved `msdyn_aiconfiguration` record (a prompt you've created in AI Builder). The connector is Dataverse (`shared_commondataserviceforapps`) with the virtual operation `aibuilderpredict_customprompt`.
+
+```json
+{
+ "type": "OpenApiConnection",
+ "inputs": {
+ "parameters": {
+ "recordId": "<msdyn_aiconfiguration GUID>",
+ "item/source": "{\"consumptionSource\":\"PowerAutomate\",\"partnerSource\":\"AIBuilder\",\"consumptionSourceVersion\":\"Flow\",\"partnerSourceVersion\":\"<flow-id>\"}"
+ },
+ "host": {
+ "apiId": "/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps",
+ "operationId": "aibuilderpredict_customprompt",
+ "connectionName": "shared_commondataserviceforapps"
+ }
+ },
+ "runAfter": {},
+ "metadata": {
+ "flowSystemMetadata": {
+ "portalOperationId": "aibuilderpredict_customprompt",
+ "portalOperationGroup": "aibuilder",
+ "portalOperationApiDisplayNameOverride": "AI Builder",
+ "portalOperationIconOverride": "https://content.powerapps.com/resource/makerx/static/pauto/images/designeroperations/aibuilderIcon2026.8e878397.png",
+ "portalOperationBrandColorOverride": "#0A76C4",
+ "portalOperationApiTierOverride": "Standard"
+ }
+ }
+}
+```
+
+**Key details:**
+- `recordId` — GUID of the AI configuration (prompt), NOT the AI model. Query: `GET /api/data/v9.2/msdyn_aiconfigurations?$filter=contains(msdyn_name,'<prompt name>')&$select=msdyn_aiconfigurationid,msdyn_name`
+- `item/source` — consumption tracking JSON. `partnerSourceVersion` should be the flow's own ID (set after creation via `edit_flow`).
+- `metadata.flowSystemMetadata` — required for the designer to render the action correctly as "AI Builder" instead of generic Dataverse.
+- Output path: `outputs('Run_a_prompt')?['body/responsev2/predictionOutput/text']`
+- Uses Dataverse connection (`shared_commondataserviceforapps`), counts as **Standard** tier (credits consumed from tenant Copilot pool).
+
+### Inline Prompt (PerformBoundActionWithOrganization / QuickTest)
+
+Alternative pattern where the prompt text is defined inline in the flow (not saved to AI Builder). More complex but doesn't require a pre-created prompt:
+
+```json
+{
+ "type": "OpenApiConnection",
+ "inputs": {
+ "parameters": {
+ "organization": "https://<org>.crm.dynamics.com/",
+ "entityName": "msdyn_aiconfigurations",
+ "actionName": "Microsoft.Dynamics.CRM.QuickTest",
+ "recordId": "<msdyn_aiconfiguration GUID>",
+ "item/version": "2.0",
+ "item/requestv2": {
+ "@@odata.type": "#Microsoft.Dynamics.CRM.expando",
+ "$customConfig": {
+ "@@odata.type": "#Microsoft.Dynamics.CRM.expando",
+ "[email protected]": "#Collection(Microsoft.Dynamics.CRM.expando)",
+ "prompt": [
+ { "@@odata.type": "#Microsoft.Dynamics.CRM.expando", "type": "literal", "text": "Your instruction here\n\n" },
+ { "@@odata.type": "#Microsoft.Dynamics.CRM.expando", "type": "dynamic", "text": "@triggerBody()['input']" }
+ ],
+ "definitions": {
+ "@@odata.type": "#Microsoft.Dynamics.CRM.expando",
+ "output": { "@@odata.type": "#Microsoft.Dynamics.CRM.expando", "[email protected]": "#Collection(String)", "formats": ["text"] }
+ },
+ "version": "GptDynamicPrompt-2",
+ "modelParameters": {
+ "@@odata.type": "#Microsoft.Dynamics.CRM.expando",
+ "modelType": "gpt-4o-mini",
+ "gptParameters": { "@@odata.type": "#Microsoft.Dynamics.CRM.expando", "temperature": 0.2 }
+ },
+ "settings": { "@@odata.type": "#Microsoft.Dynamics.CRM.expando", "recordRetrievalLimit": 30 }
+ }
+ },
+ "item/source": "{ \"consumptionSource\": \"Api\", \"partnerSource\": \"PowerAutomate\", \"consumptionSourceVersion\": \"GptApiClient\"}"
+ },
+ "host": {
+ "apiId": "/providers/Microsoft.PowerApps/apis/shared_commondataserviceforapps",
+ "operationId": "PerformBoundActionWithOrganization",
+ "connectionName": "shared_commondataserviceforapps"
+ },
+ "retryPolicy": { "type": "none" }
+ },
+ "runAfter": {}
+}
+```
+
+**Inline prompt details:**
+- `prompt` array: mix of `literal` (static text) and `dynamic` (expressions) segments
+- `modelParameters.modelType`: `"gpt-4o-mini"`, `"gpt-4o"`, `"claude-3-opus"`, etc.
+- `recordId` here points to the `GptPromptEngineering` model (`msdyn_aimodel`), which you can find via: `GET /api/data/v9.2/msdyn_aimodels?$filter=msdyn_name eq 'GptPromptEngineering model'`
+- Requires `organization` parameter (Dataverse instance URL)
+
## Expression Syntax
- String interpolation: `@{triggerBody()?['name']}`
diff --git a/plugins/power-automate/references/error-troubleshooting.md b/plugins/power-automate/references/error-troubleshooting.md
index 92f4ddee8..4b32a4b50 100644
--- a/plugins/power-automate/references/error-troubleshooting.md
+++ b/plugins/power-automate/references/error-troubleshooting.md
@@ -1,6 +1,6 @@
# Common API Errors & Fixes
-> Note: Shell commands below require the [FlowAgent engine repo](https://github.com/matow_microsoft/flow-agent) cloned and built. Plugin users should use MCP tools instead.
+> **Note:** These shell commands require a local engine build. If you installed this as a plugin, use the MCP tools instead — they cover the same operations.
| Error | Cause | Fix |
|-------|-------|-----|
diff --git a/plugins/power-automate/server/mcp.mjs b/plugins/power-automate/server/mcp.mjs
index 4fccdf2a5..95076a905 100644
--- a/plugins/power-automate/server/mcp.mjs
+++ b/plugins/power-automate/server/mcp.mjs
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-// FlowAgent MCP v2.3.1 — solution flow round-trip, resolvers, list_datasets/tables
+// FlowAgent MCP v2.5.0
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -27966,6 +27966,7 @@ async function followPagination(fetchPage, maxPages = DEFAULT_MAX_PAGES) {
}
// packages/core/dist/api/flow-diff.js
+import { createHash } from "node:crypto";
function jsonEqual(a, b) {
if (a === b)
return true;
@@ -28123,14 +28124,19 @@ function diffFlow(current, proposed) {
diff.summary = buildSummary(diff);
return diff;
}
-function hashProposal(body) {
- const stable = stableStringify(body);
- let h = 2166136261;
- for (let i = 0; i < stable.length; i++) {
- h ^= stable.charCodeAt(i);
- h = h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24)) >>> 0;
- }
- return ("0000000" + h.toString(16)).slice(-8);
+function hashUpdateBody(body) {
+ const p = body?.properties ?? {};
+ const normalized = {};
+ if (p.definition !== void 0)
+ normalized.definition = p.definition;
+ if (p.connectionReferences !== void 0)
+ normalized.connectionReferences = p.connectionReferences;
+ if (p.displayName !== void 0)
+ normalized.displayName = p.displayName;
+ if (p.state !== void 0)
+ normalized.state = p.state;
+ const stable = stableStringify(normalized);
+ return createHash("sha256").update(stable).digest("hex");
}
function stableStringify(v) {
if (v === null || v === void 0 || typeof v !== "object")
@@ -28334,6 +28340,76 @@ function applyFlowEdits(definition, operations) {
return { definition: next, applied };
}
+// packages/core/dist/connection-refs.js
+function extractConnectorKeysFromDefinition(definition) {
+ const keys = /* @__PURE__ */ new Set();
+ function scanActions(actions) {
+ if (!actions || typeof actions !== "object")
+ return;
+ for (const action of Object.values(actions)) {
+ const connName = action?.inputs?.host?.connectionName;
+ if (connName)
+ keys.add(connName);
+ if (action?.actions)
+ scanActions(action.actions);
+ if (action?.else?.actions)
+ scanActions(action.else.actions);
+ if (action?.cases) {
+ for (const c of Object.values(action.cases)) {
+ if (c?.actions)
+ scanActions(c.actions);
+ }
+ }
+ if (action?.default?.actions)
+ scanActions(action.default.actions);
+ }
+ }
+ scanActions(definition.actions);
+ const triggers = definition.triggers;
+ if (triggers) {
+ for (const trigger of Object.values(triggers)) {
+ const connName = trigger?.inputs?.host?.connectionName;
+ if (connName)
+ keys.add(connName);
+ }
+ }
+ return keys;
+}
+async function enrichRefsWithLogicalNames(client, envId, refs, log) {
+ const needsEnrichment = Object.values(refs).some((r) => !r.connectionReferenceLogicalName);
+ if (!needsEnrichment)
+ return refs;
+ let dvRefs;
+ try {
+ dvRefs = await client.listConnections(envId);
+ } catch {
+ log?.("Dataverse connection references unavailable; using direct connections");
+ return refs;
+ }
+ const connectorToLogical = {};
+ for (const dv of dvRefs) {
+ if (dv.connectorid && dv.connectionreferencelogicalname) {
+ connectorToLogical[dv.connectorid] = dv.connectionreferencelogicalname;
+ }
+ }
+ const enriched = { ...refs };
+ let count = 0;
+ for (const [key, ref] of Object.entries(enriched)) {
+ if (ref.connectionReferenceLogicalName)
+ continue;
+ const connectorId = ref.id ?? `/providers/Microsoft.PowerApps/apis/${key}`;
+ const logicalName = connectorToLogical[connectorId];
+ if (logicalName) {
+ enriched[key] = { ...ref, connectionReferenceLogicalName: logicalName };
+ count++;
+ }
+ }
+ if (count > 0) {
+ log?.(`Resolved ${count} connection reference logical name(s) from Dataverse`);
+ }
+ return enriched;
+}
+
// packages/core/dist/api/flow-client.js
import { execFile } from "node:child_process";
import { randomUUID as randomUUID2 } from "node:crypto";
@@ -28364,8 +28440,8 @@ function createSha256ContentDigest(value) {
return "00000000";
}
}
-var MAX_RETRIES = 3;
-var INITIAL_DELAY_MS = 1e3;
+var MAX_RETRIES = 2;
+var INITIAL_DELAY_MS = 500;
var APIHUB_RESOURCE = "https://apihub.azure.com";
function extractLogicalNamesFromFlow(flow) {
const refs = flow?.properties?.connectionReferences;
@@ -28388,10 +28464,35 @@ var FlowClient = class _FlowClient {
* Flow RP API instead of PPAPI (issues #269, #271, #274, #276, #278, #281, #282).
*/
ppapiUnavailableEnvs = /* @__PURE__ */ new Set();
+ /** Connection cache: key = `${envId}:${connector}`, TTL = 5 minutes. */
+ connectionCache = /* @__PURE__ */ new Map();
+ static CONNECTION_CACHE_TTL_MS = 5 * 60 * 1e3;
constructor(auth2, config3) {
this.auth = auth2;
this.config = config3;
}
+ /** Get cached connections or null if expired/missing. */
+ getCachedConnections(envId, connector) {
+ const key = `${envId}:${connector ?? "*"}`;
+ const entry = this.connectionCache.get(key);
+ if (entry && Date.now() < entry.expiresAt)
+ return entry.value;
+ if (entry)
+ this.connectionCache.delete(key);
+ return null;
+ }
+ /** Cache a connection list. */
+ setCachedConnections(envId, connector, value) {
+ const key = `${envId}:${connector ?? "*"}`;
+ this.connectionCache.set(key, { value, expiresAt: Date.now() + _FlowClient.CONNECTION_CACHE_TTL_MS });
+ }
+ /** Invalidate connection cache for an environment (after create/delete/fix). */
+ invalidateConnectionCache(envId, connector) {
+ if (connector) {
+ this.connectionCache.delete(`${envId}:${connector}`);
+ }
+ this.connectionCache.delete(`${envId}:*`);
+ }
/** Resolve the PPAPI base URL for an environment, respecting config overrides. */
ppapiBase(envId) {
return ppapiBaseUrl(envId, this.config.ppapiBaseUrlTemplate, this.config.cloudEndpoints.ppapiSuffix);
@@ -28513,13 +28614,20 @@ var FlowClient = class _FlowClient {
}
await this.assertNotManaged(envId, flowId, "update_flow", opts);
await this.snapshotBeforeMutation(envId, flowId, "update_flow", opts);
+ let autoMerged = [];
+ if (opts.autoResolveConnectionRefs !== false && body.properties?.definition) {
+ autoMerged = await this.autoMergeConnectionRefs(envId, flowId, body);
+ }
if (body.properties?.definition) {
try {
const ctx = await this.getFlowContext(envId, flowId);
if (ctx.inSolution && ctx.workflowId && !ctx.warning) {
const updated = await this.updateFlowViaDataverse(envId, flowId, ctx.workflowId, body);
- if (updated)
+ if (updated) {
+ if (autoMerged.length)
+ updated._autoMergedConnectionRefs = autoMerged;
return updated;
+ }
}
} catch {
logger.debug(`updateFlow: Dataverse path failed, falling through to PPAPI`);
@@ -28527,7 +28635,71 @@ var FlowClient = class _FlowClient {
}
this.stripInjectedAuthentication(body);
const path5 = `/powerautomate/flows/${flowId}${this.ppapiFlowQs({})}`;
- return this.ppapiRequestWithFallback(envId, path5, "PATCH", body);
+ const result = await this.ppapiRequestWithFallback(envId, path5, "PATCH", body);
+ if (autoMerged.length)
+ result._autoMergedConnectionRefs = autoMerged;
+ return result;
+ }
+ /**
+ * Detect connectors in the new definition that aren't in the current flow's
+ * connectionReferences. Auto-resolve by finding a connected connection for
+ * each missing connector. Fails on ambiguity (multiple candidates).
+ */
+ async autoMergeConnectionRefs(envId, flowId, body) {
+ const def = body.properties?.definition;
+ if (!def)
+ return [];
+ let currentRefs;
+ try {
+ const current = await this.getFlow(envId, flowId);
+ currentRefs = current.properties?.connectionReferences ?? {};
+ } catch {
+ return [];
+ }
+ const neededKeys = extractConnectorKeysFromDefinition(def);
+ const suppliedRefs = body.properties?.connectionReferences ?? {};
+ const effectiveRefs = { ...currentRefs, ...suppliedRefs };
+ const missing = [];
+ for (const key of neededKeys) {
+ if (!effectiveRefs[key])
+ missing.push(key);
+ }
+ if (missing.length === 0)
+ return [];
+ const resolved = {};
+ for (const connectorKey of missing) {
+ const connectorName = connectorKey.startsWith("shared_") ? connectorKey : `shared_${connectorKey}`;
+ try {
+ const conns = await this.listConnections(envId, { connector: connectorName });
+ const connected = conns.filter((c) => c.statuses?.[0]?.status === "Connected" || c.status === "Connected");
+ if (connected.length === 1) {
+ const conn = connected[0];
+ resolved[connectorKey] = {
+ connectionName: conn.connectionName ?? conn.name,
+ source: "Embedded",
+ id: `/providers/Microsoft.PowerApps/apis/${connectorName}`,
+ tier: "NotSpecified"
+ };
+ logger.info(`[auto-merge] Resolved ${connectorKey} \u2192 ${conn.connectionName ?? conn.name}`);
+ } else if (connected.length > 1) {
+ throw new Error(`Multiple connections available for ${connectorKey} (${connected.length} candidates). Pass explicit connectionRefs or use connectionSelection to disambiguate.`);
+ } else {
+ throw new Error(`No connected connection found for ${connectorKey}. Create one with: create-connection --env=${envId} --connector=${connectorName}`);
+ }
+ } catch (err) {
+ if (err.message?.includes("Multiple connections") || err.message?.includes("No connected connection")) {
+ throw err;
+ }
+ logger.debug(`[auto-merge] Could not resolve ${connectorKey}: ${err.message}`);
+ }
+ }
+ if (Object.keys(resolved).length > 0) {
+ if (!body.properties.connectionReferences) {
+ body.properties.connectionReferences = { ...currentRefs };
+ }
+ Object.assign(body.properties.connectionReferences, resolved);
+ }
+ return Object.keys(resolved);
}
/**
* Update a solution flow by PATCHing its Dataverse clientdata directly.
@@ -28579,11 +28751,12 @@ var FlowClient = class _FlowClient {
}
}
const fixHost = (inputs) => {
- if (!inputs)
+ if (!inputs || typeof inputs !== "object" || Array.isArray(inputs))
return;
- if ("authentication" in inputs)
- delete inputs.authentication;
- const host = inputs.host;
+ const inp = inputs;
+ if ("authentication" in inp)
+ delete inp.authentication;
+ const host = inp.host;
if (host && host.connectionName && !host.connectionReferenceName) {
const logicalName = connRefMap[host.connectionName];
if (logicalName) {
@@ -28595,13 +28768,13 @@ var FlowClient = class _FlowClient {
const actions = def.actions;
if (actions) {
for (const action of Object.values(actions)) {
- fixHost(action.inputs);
+ fixHost(action?.inputs);
}
}
const triggers = def.triggers;
if (triggers) {
for (const trigger of Object.values(triggers)) {
- fixHost(trigger.inputs);
+ fixHost(trigger?.inputs);
}
}
}
@@ -28652,7 +28825,7 @@ var FlowClient = class _FlowClient {
const currentSnap = toSnapshot(current);
const proposed = mergeProposal(currentSnap, body);
const diff = diffFlow(currentSnap, proposed);
- const proposalHash = hashProposal(proposed);
+ const proposalHash = hashUpdateBody(body);
const { token, expiresAt } = issueToken({
envId,
flowId,
@@ -28670,9 +28843,7 @@ var FlowClient = class _FlowClient {
};
}
async assertPreviewTokenMatches(envId, flowId, body, token) {
- const current = await this.getFlow(envId, flowId);
- const proposed = mergeProposal(toSnapshot(current), body);
- const proposalHash = hashProposal(proposed);
+ const proposalHash = hashUpdateBody(body);
const result = redeemToken(token, { envId, flowId, proposalHash });
if (!result.ok) {
if (result.code === "PreviewTokenMismatch") {
@@ -28687,6 +28858,42 @@ var FlowClient = class _FlowClient {
const path5 = `/powerautomate/flows/${flowId}${this.ppapiFlowQs({})}`;
await this.ppapiRequestWithFallback(envId, path5, "DELETE");
}
+ /**
+ * Copy a flow: reads the source flow's definition + connection references,
+ * then creates a new flow with the same definition under a new name.
+ * Optionally copies to a different environment.
+ *
+ * Returns `sameEnv` (whether the copy stayed in the source environment) and
+ * `unresolvedConnectors` — connection references that won't carry over to the
+ * target environment (always empty for a same-env copy, since the existing
+ * connections keep working; non-empty for cross-env copies, which need the
+ * connections re-bound in the target env).
+ */
+ async copyFlow(envId, flowId, opts = {}) {
+ const source = await this.getFlow(envId, flowId);
+ const displayName = opts.name ?? `${source.properties.displayName} (Copy)`;
+ const targetEnv = opts.targetEnv ?? envId;
+ const sameEnv = targetEnv === envId;
+ const state = opts.state ?? "Stopped";
+ const sourceRefs = source.properties.connectionReferences ?? {};
+ const body = {
+ properties: {
+ displayName,
+ definition: source.properties.definition,
+ connectionReferences: sourceRefs,
+ state
+ }
+ };
+ const unresolvedConnectors = sameEnv ? [] : Object.keys(sourceRefs);
+ const created = await this.createFlow(targetEnv, body, { autoInjectParams: false });
+ return {
+ flowId: created.name ?? created.id,
+ displayName,
+ state,
+ sameEnv,
+ unresolvedConnectors
+ };
+ }
/**
* Restore a flow from a previously captured backup. The current state of
* the flow is itself snapshotted first (with operation="restore_backup")
@@ -28740,7 +28947,28 @@ var FlowClient = class _FlowClient {
async publishFlow(envId, flowId, opts = {}) {
await this.assertNotManaged(envId, flowId, "publish_flow", opts);
const path5 = `/powerautomate/flows/${flowId}/start${this.ppapiFlowQs({})}`;
- await this.ppapiRequestWithFallback(envId, path5, "POST");
+ try {
+ await this.ppapiRequestWithFallback(envId, path5, "POST");
+ } catch (err) {
+ if (err instanceof FlowApiError && /CannotStartUnpublishedSolutionFlow/i.test(err.body)) {
+ logger.info(`[publish-flow] PPAPI blocked with CannotStartUnpublishedSolutionFlow, attempting Dataverse activation`);
+ const ctx = await this.getFlowContext(envId, flowId);
+ if (!ctx.workflowId)
+ throw err;
+ try {
+ const instanceUrl = await this.getDataverseInstanceUrl(envId);
+ const dvToken = await this.auth.getAccessToken(instanceUrl);
+ const patchUrl = `${instanceUrl}/api/data/v9.2/workflows(${ctx.workflowId})`;
+ await this.dataversePatch(patchUrl, { statecode: 1, statuscode: 2 }, dvToken);
+ logger.info(`[publish-flow] Activated via Dataverse statecode=1, statuscode=2`);
+ return;
+ } catch (dvErr) {
+ logger.warn(`[publish-flow] Dataverse activation failed: ${dvErr instanceof Error ? dvErr.message : dvErr}`);
+ throw err;
+ }
+ }
+ throw err;
+ }
}
async disableFlow(envId, flowId, opts = {}) {
await this.assertNotManaged(envId, flowId, "disable_flow", opts);
@@ -28873,6 +29101,108 @@ var FlowClient = class _FlowClient {
throw err;
}
}
+ // --- Run Management (cancel, resubmit, diagnose) ---
+ async cancelRun(envId, flowId, runId) {
+ const path5 = `/powerautomate/flows/${flowId}/runs/${runId}/cancel${this.ppapiFlowQs({})}`;
+ await this.ppapiRequestWithFallback(envId, path5, "POST");
+ return { cancelled: true, runId };
+ }
+ async resubmitRun(envId, flowId, runId, opts) {
+ let triggerName = opts?.triggerName;
+ if (!triggerName) {
+ const run = await this.getRunDetails(envId, flowId, runId);
+ triggerName = run.properties?.trigger?.name;
+ if (!triggerName)
+ throw new Error("Could not detect trigger name from run. Provide it explicitly.");
+ }
+ const path5 = `/powerautomate/flows/${flowId}/triggers/${triggerName}/histories/${runId}/resubmit${this.ppapiFlowQs({})}`;
+ await this.ppapiRequestWithFallback(envId, path5, "POST");
+ return { resubmitted: true, triggerName };
+ }
+ async getRunActionRepetitions(envId, flowId, runId, actionName) {
+ const path5 = `/powerautomate/flows/${flowId}/runs/${runId}/actions/${actionName}/repetitions${this.ppapiFlowQs({})}`;
+ return followPagination(async (nextUrl) => {
+ if (nextUrl)
+ return this.ppapiRequest("GET", nextUrl);
+ return this.ppapiRequestWithFallback(envId, path5, "GET");
+ });
+ }
+ /** Diagnose a failed run: classify each failed/timed-out action with an actionable remediation. */
+ async diagnoseRun(envId, flowId, runId) {
+ const run = await this.getRunDetails(envId, flowId, runId);
+ const actions = await this.getRunActionDetails(envId, flowId, runId);
+ const status = run.properties?.status ?? "Unknown";
+ const failed = (actions ?? []).filter((a) => a.properties?.status === "Failed" || a.properties?.status === "TimedOut");
+ const classified = failed.map((a) => {
+ const code = a.properties?.error?.code ?? a.properties?.code ?? "Unknown";
+ const message = a.properties?.error?.message ?? "";
+ return { name: a.name, code, message, remediation: this.classifyRemediation(code, message) };
+ });
+ const summary = classified.length === 0 ? `Run ${runId} status: ${status}. No failed actions found.` : `Run ${runId} status: ${status}. ${classified.length} failed action(s): ${classified.map((a) => a.name).join(", ")}`;
+ return { status, failedActions: classified, summary };
+ }
+ classifyRemediation(code, message) {
+ const codeLower = code.toLowerCase();
+ const msgLower = message.toLowerCase();
+ if (codeLower === "unauthorized" || codeLower === "authorizationfailed" || msgLower.includes("401"))
+ return "Connection expired or insufficient permissions. Re-authenticate the connection in the flow's connection references.";
+ if (codeLower === "forbidden" || msgLower.includes("403"))
+ return "The connected account lacks permissions for this resource. Verify role assignments.";
+ if (codeLower === "notfound" || codeLower === "resourcenotfound" || msgLower.includes("404"))
+ return "Target resource not found. Verify the item/list/folder still exists and the ID is correct.";
+ if (codeLower === "throttled" || codeLower === "ratelimitexceeded" || codeLower === "429" || msgLower.includes("throttl"))
+ return "API throttling. Add retry-after logic, reduce concurrency, or batch fewer items.";
+ if (codeLower === "timedout" || codeLower === "gatewayerror" || msgLower.includes("timed out"))
+ return "Action timed out. Increase the timeout in action settings or break into smaller operations.";
+ if (codeLower === "dependencyfailed" || codeLower === "actionconditionfailed")
+ return "Upstream dependency failed. Fix the earlier failing action first \u2014 this one was skipped.";
+ if (codeLower === "invalidtemplate" || msgLower.includes("expression"))
+ return "Expression or template error. Check the expression syntax in this action's inputs.";
+ return `Error code: ${code}. Review the error message and check the connector documentation.`;
+ }
+ async cancelAllRuns(envId, flowId, opts) {
+ try {
+ const ctx = await this.getFlowContext(envId, flowId);
+ if (ctx.warning !== "no-dataverse-instance" && ctx.workflowId) {
+ const instanceUrl = await this.getDataverseInstanceUrl(envId);
+ const url = `${instanceUrl}/api/data/v9.2/workflows(${ctx.workflowId})/Microsoft.Dynamics.CRM.CancelAllCloudFlowRuns`;
+ const token = await this.auth.getAccessToken(instanceUrl);
+ const resp = await fetch(url, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
+ body: JSON.stringify({})
+ });
+ if (!resp.ok && resp.status !== 204)
+ throw new Error(`CancelAllCloudFlowRuns failed: ${resp.status}`);
+ let turnedOff2 = false;
+ if (opts.turnOff) {
+ await this.disableFlow(envId, flowId, { forceManaged: opts.forceManaged });
+ turnedOff2 = true;
+ }
+ return { method: "dataverse-bulk", turnedOff: turnedOff2 };
+ }
+ } catch {
+ }
+ const runs = await this.getRunHistory(envId, flowId, { top: 100, filter: "status eq 'Running' or status eq 'Waiting'" });
+ const cancellable = runs.filter((r) => {
+ const st = r.properties?.status;
+ return st === "Running" || st === "Waiting";
+ });
+ let cancelled = 0;
+ for (const run of cancellable) {
+ try {
+ await this.cancelRun(envId, flowId, run.name);
+ cancelled++;
+ } catch {
+ }
+ }
+ let turnedOff = false;
+ if (opts.turnOff) {
+ await this.disableFlow(envId, flowId, { forceManaged: opts.forceManaged });
+ turnedOff = true;
+ }
+ return { method: "per-run", attempted: cancellable.length, cancelled, turnedOff };
+ }
/**
* Fetch trigger inputs from a past run. This is the same primitive the PA
* designer uses for "Test with previous run data". For each requested run,
@@ -29503,6 +29833,11 @@ var FlowClient = class _FlowClient {
} catch (err) {
lastError = err;
if (err instanceof FlowApiError) {
+ if (err.statusCode === 401 && attempt === 0) {
+ this.auth.invalidateAccessToken?.();
+ logger.debug("PPAPI 401 \u2014 invalidated token, retrying");
+ continue;
+ }
if (err.statusCode !== 429 && err.statusCode < 500) {
throw err;
}
@@ -30114,6 +30449,7 @@ var FlowClient = class _FlowClient {
} else {
logger.info(`Connection '${connName}' created but not yet authenticated. Status: ${(authed.properties?.statuses ?? []).map((s) => s.status).join(", ") || "Unknown"}. Run: flowagent fix-connection --env=${envId} --connector=${connector} --connection=${connName}`);
}
+ this.invalidateConnectionCache(envId, connector);
return authed;
}
async testConnection(envId, connector, connName) {
@@ -30134,6 +30470,7 @@ var FlowClient = class _FlowClient {
async deleteConnection(envId, connector, connName) {
const url = ppapiConnectionUrl(envId, connector, connName);
await this.connectivityRequest("DELETE", url);
+ this.invalidateConnectionCache(envId, connector);
}
async getConnectionPermissions(envId, connector, connName) {
const url = ppapiConnectionPermissionsUrl(envId, connector, connName);
@@ -30253,10 +30590,19 @@ var FlowClient = class _FlowClient {
}
// --- Connections (via Dataverse) ---
async listConnections(envId, opts) {
+ const connector = opts?.connectorFilter ?? opts?.connector;
+ if (opts?.useCache !== false) {
+ const cached3 = this.getCachedConnections(envId, connector);
+ if (cached3) {
+ logger.debug(`listConnections cache hit: ${envId}:${connector ?? "*"}`);
+ return cached3;
+ }
+ }
const instanceUrl = await this.getDataverseInstanceUrl(envId);
const dvToken = await this.auth.getAccessToken(instanceUrl);
- const url = dataverseConnectionReferencesUrl(instanceUrl, opts);
+ const url = dataverseConnectionReferencesUrl(instanceUrl, { connectorFilter: connector });
const data = await this.dataverseGet(url, dvToken);
+ this.setCachedConnections(envId, connector, data.value);
return data.value;
}
// --- Solutions (Dataverse) ---
@@ -30604,7 +30950,7 @@ var FlowClient = class _FlowClient {
const headers = {
Authorization: `Bearer ${token}`,
Accept: "application/json",
- "User-Agent": "power-automate-plugin/2.3.1",
+ "User-Agent": "power-automate-plugin/2.4.2",
...extraHeaders
};
if (body !== void 0) {
@@ -30812,7 +31158,7 @@ import { spawnSync } from "node:child_process";
import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
-import { createHash } from "node:crypto";
+import { createHash as createHash2 } from "node:crypto";
var SCHEMA_VERSION = 1;
function defaultCacheDir() {
const envOverride = process.env.FLOWAGENT_TOKEN_CACHE_DIR;
@@ -30846,11 +31192,11 @@ function parseJwtClaims(token) {
}
function cacheKeyFile(cacheDir, resource, tenantId2, accountId) {
const composite = `${resource}\0${tenantId2 ?? ""}\0${accountId ?? ""}`;
- const hash = createHash("sha256").update(composite).digest("hex").slice(0, 32);
+ const hash = createHash2("sha256").update(composite).digest("hex").slice(0, 32);
return path.join(cacheDir, `${hash}.json`);
}
function unkeyedFile(cacheDir, resource) {
- const hash = createHash("sha256").update(resource).digest("hex").slice(0, 32);
+ const hash = createHash2("sha256").update(resource).digest("hex").slice(0, 32);
return path.join(cacheDir, `_unknown-${hash}.json`);
}
var DiskTokenCache = class {
@@ -31063,6 +31409,11 @@ ${stdout}`.trim();
}
return parsed.accessToken;
}
+ /** Invalidate cached token for a resource, forcing re-acquisition on next getAccessToken(). */
+ invalidateAccessToken(resource) {
+ const res = resource ?? this.defaultResource;
+ this.tokenCache.delete(res);
+ }
};
var AzCliAuthError = class extends Error {
code;
@@ -33007,42 +33358,6 @@ function createTelemetryObserver(opts = {}) {
};
}
-// packages/core/dist/connection-refs.js
-async function enrichRefsWithLogicalNames(client, envId, refs, log) {
- const needsEnrichment = Object.values(refs).some((r) => !r.connectionReferenceLogicalName);
- if (!needsEnrichment)
- return refs;
- let dvRefs;
- try {
- dvRefs = await client.listConnections(envId);
- } catch {
- log?.("Dataverse connection references unavailable; using direct connections");
- return refs;
- }
- const connectorToLogical = {};
- for (const dv of dvRefs) {
- if (dv.connectorid && dv.connectionreferencelogicalname) {
- connectorToLogical[dv.connectorid] = dv.connectionreferencelogicalname;
- }
- }
- const enriched = { ...refs };
- let count = 0;
- for (const [key, ref] of Object.entries(enriched)) {
- if (ref.connectionReferenceLogicalName)
- continue;
- const connectorId = ref.id ?? `/providers/Microsoft.PowerApps/apis/${key}`;
- const logicalName = connectorToLogical[connectorId];
- if (logicalName) {
- enriched[key] = { ...ref, connectionReferenceLogicalName: logicalName };
- count++;
- }
- }
- if (count > 0) {
- log?.(`Resolved ${count} connection reference logical name(s) from Dataverse`);
- }
- return enriched;
-}
-
// packages/core/dist/current-env-store.js
var CurrentEnvStore = class {
state;
@@ -33106,6 +33421,11 @@ var CurrentFlowStore = class {
this.state = { flowId: null, displayName: null, envId: null, updatedAt: (/* @__PURE__ */ new Date()).toISOString(), source: "none" };
return this.state;
}
+ /** Clear only if the pinned flow matches the given ID (e.g. after delete or confirmed 404). */
+ clearIf(flowId) {
+ if (this.state.flowId === flowId)
+ this.clear();
+ }
};
var legacyCurrentFlowStore = new CurrentFlowStore();
@@ -41539,6 +41859,23 @@ function getNestedValue(obj, path5) {
}
return current;
}
+function isNotFoundError(err) {
+ return err instanceof FlowApiError && err.statusCode === 404;
+}
+function isConflictError(err) {
+ return err instanceof FlowApiError && err.statusCode === 409;
+}
+function notFoundResult(resource, id, remediation) {
+ const payload = {
+ found: false,
+ code: "not_found",
+ resource,
+ id,
+ message: `${resource} not found (it may have been deleted or moved to another environment).`,
+ remediation: remediation ?? `Call list_flows to see current flows in this environment.`
+ };
+ return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }] };
+}
// packages/core/dist/mcp/progress.js
function progress(extra) {
@@ -42133,7 +42470,7 @@ async function createMcpServer(authProvider, deps = {}) {
return safeError(e);
}
});
- server2.tool("list_flows", "List cloud flows. Supports name search.", { env: external_exports.string().optional().describe("Environment ID (session default if omitted)"), name: external_exports.string().optional().describe("Filter by display name"), top: external_exports.number().optional().describe("Max results (default 50)"), filter: external_exports.string().optional().describe("OData filter (advanced)") }, { readOnlyHint: true, title: "List Flows" }, async ({ env, name: name3, top, filter }) => {
+ server2.tool("list_flows", "List cloud flows. Supports name search.", { env: external_exports.string().optional().describe("Environment ID (session default if omitted)"), name: external_exports.string().optional().describe("Filter by display name"), top: external_exports.number().min(1).max(500).optional().describe("Max results (default 50)"), filter: external_exports.string().optional().describe("OData filter (advanced)") }, { readOnlyHint: true, title: "List Flows" }, async ({ env, name: name3, top, filter }) => {
try {
const envId = ctx.resolveEnv(env);
ctx.rememberEnv(envId);
@@ -42185,6 +42522,12 @@ async function createMcpServer(authProvider, deps = {}) {
}
return safeResult(result, { singleItem: true });
} catch (e) {
+ if (isNotFoundError(e)) {
+ const pinned = getActiveMcpContext().currentFlow.get();
+ if (pinned.flowId === flow)
+ getActiveMcpContext().currentFlow.clear();
+ return notFoundResult("Flow", flow);
+ }
return safeError(e);
}
});
@@ -42311,6 +42654,8 @@ async function createMcpServer(authProvider, deps = {}) {
await ctx.getClient().publishFlow(ctx.resolveEnv(env), flow, { forceManaged });
return safeResult({ success: true });
} catch (e) {
+ if (isConflictError(e))
+ return safeResult({ success: true, alreadyStarted: true, message: "Flow is already enabled." });
return safeError(e);
}
});
@@ -42325,6 +42670,7 @@ async function createMcpServer(authProvider, deps = {}) {
server2.tool("delete_flow", "Permanently delete a flow. **Refuses by default for managed-solution flows** (deletion is irreversible AND will be undone on next solution import). Pass forceManaged: true to override. **Use this when**: the flow is no longer needed AND you've confirmed no other flow / connection / app depends on it. **Do NOT use when**: you just want to stop the flow temporarily \u2014 use disable_flow (reversible). Auto-captures a backup snapshot before deletion, accessible via restore_backup for ~10 retentions.", { env: external_exports.string().optional().describe("Environment ID"), flow: external_exports.string().describe("Flow ID"), forceManaged: external_exports.boolean().optional().describe("Override the managed-solution read-only guard. Default false.") }, { destructiveHint: true, title: "Delete Flow" }, async ({ env, flow, forceManaged }) => {
try {
await ctx.getClient().deleteFlow(ctx.resolveEnv(env), flow, { forceManaged });
+ getActiveMcpContext().currentFlow.clearIf(flow);
return safeResult({ success: true });
} catch (e) {
return safeError(e);
@@ -42408,6 +42754,8 @@ async function createMcpServer(authProvider, deps = {}) {
const runs = await ctx.getClient().getRunHistory(ctx.resolveEnv(env), flow, top ? { top } : {});
return safeResult(summarizeList(runs, ["name", "properties.startTime", "properties.endTime", "properties.status", "properties.error.code", "properties.error.message"], { "properties.startTime": "startTime", "properties.endTime": "endTime", "properties.status": "status", "properties.error.code": "errorCode", "properties.error.message": "errorMessage" }));
} catch (e) {
+ if (isNotFoundError(e))
+ return notFoundResult("Flow", flow, "The flow may have been deleted. Call list_flows to see current flows.");
return safeError(e);
}
});
@@ -42415,6 +42763,8 @@ async function createMcpServer(authProvider, deps = {}) {
try {
return safeResult(await ctx.getClient().getRunDetails(ctx.resolveEnv(env), flow, run));
} catch (e) {
+ if (isNotFoundError(e))
+ return notFoundResult("Run", run, "The run may have expired or the flow was deleted.");
return safeError(e);
}
});
@@ -42423,6 +42773,8 @@ async function createMcpServer(authProvider, deps = {}) {
const actions = await ctx.getClient().getRunActionDetails(ctx.resolveEnv(env), flow, run);
return safeResult(summarizeList(actions, ["name", "properties.startTime", "properties.endTime", "properties.status", "properties.code", "properties.error.code", "properties.error.message"], { "properties.startTime": "startTime", "properties.endTime": "endTime", "properties.status": "status", "properties.code": "code", "properties.error.code": "errorCode", "properties.error.message": "errorMessage" }));
} catch (e) {
+ if (isNotFoundError(e))
+ return notFoundResult("Run", run, "The run may have expired or the flow was deleted.");
return safeError(e);
}
});
@@ -42476,10 +42828,15 @@ async function createMcpServer(authProvider, deps = {}) {
});
server2.tool("set_current_flow", "Pin a flow as the session's current flow. Once pinned, run/debug tools (cancel_run, resubmit_run, cancel_all_runs, get_run_action_repetitions, diagnose_run) use it when `flow` is omitted \u2014 a guardrail so an autonomous agent acts on exactly one flow.", { env: external_exports.string().optional().describe("Environment ID (for display only)"), flow: external_exports.string().describe("Flow ID to pin") }, { readOnlyHint: false, title: "Set Current Flow" }, async ({ env, flow }) => {
try {
+ const envId = ctx.resolveEnv(env);
let displayName = null;
try {
- displayName = (await ctx.getClient().getFlow(ctx.resolveEnv(env), flow)).properties?.displayName ?? null;
- } catch {
+ const f = await ctx.getClient().getFlow(envId, flow);
+ displayName = f?.properties?.displayName ?? null;
+ } catch (e) {
+ if (isNotFoundError(e)) {
+ return notFoundResult("Flow", flow, "Cannot pin a flow that does not exist. Call list_flows to find valid flow IDs.");
+ }
}
const next = getActiveMcpContext().currentFlow.set(flow, { displayName, envId: env ?? null, source: "set_tool" });
return safeResult(next);
@@ -42625,7 +42982,8 @@ async function createMcpServer(authProvider, deps = {}) {
if (!connName) {
const conns = await ctx.getClient().listConnections(envId, { connector });
const active = conns.find((c) => c.statuses?.[0]?.status === "Connected" || c.status === "Connected");
- connName = active?.name ?? active?.connectionName ?? conns[0]?.name ?? conns[0]?.connectionName;
+ const first = conns[0];
+ connName = active?.connectionName ?? active?.name ?? first?.connectionName ?? first?.name ?? first?.id;
if (!connName) {
return safeResult({ status: "connection_missing", connector, entityType, query, requiredAction: "create_connection" });
}
@@ -42829,23 +43187,40 @@ async function createMcpServer(authProvider, deps = {}) {
return safeError(e);
}
});
- server2.tool("scaffold_flow", "Generate flow definition from template. Pass env to auto-resolve connections.", { template: external_exports.string().describe("Template ID"), env: external_exports.string().optional().describe("Environment ID for connection resolution") }, { readOnlyHint: true, title: "Scaffold Flow" }, async ({ template, env }) => {
+ server2.tool("scaffold_flow", "Generate flow definition from template. Pass env to auto-resolve connections. When env is provided, connection resolution is REQUIRED \u2014 returns an error with missing connectors if any can't be resolved. Without env, returns placeholder refs for offline use.", { template: external_exports.string().describe("Template ID"), env: external_exports.string().optional().describe("Environment ID for connection resolution") }, { readOnlyHint: true, title: "Scaffold Flow" }, async ({ template, env }) => {
try {
const tmpl = getTemplate(template);
if (!tmpl)
return safeError(new Error(`Template "${template}" not found. Use list_templates.`));
const definition = injectTemplateMetadata(tmpl.definition);
let refs;
+ let connectionStatus = "placeholder";
+ const unresolvedConnectors = [];
if (env && tmpl.connectors.length > 0) {
try {
refs = await ctx.getClient().resolveConnectionRefs(ctx.resolveEnv(env), tmpl.connectors);
+ for (const connector of tmpl.connectors) {
+ const key = connector.replace("shared_", "shared_");
+ const ref = refs[key];
+ if (!ref?.connectionName || ref.connectionName.startsWith("REPLACE_WITH")) {
+ unresolvedConnectors.push(connector);
+ }
+ }
+ connectionStatus = unresolvedConnectors.length === 0 ? "resolved" : "partial";
} catch {
refs = generateConnectionRefs(tmpl.connectors);
+ unresolvedConnectors.push(...tmpl.connectors);
}
} else {
refs = generateConnectionRefs(tmpl.connectors);
}
- return safeResult({ definition, connectionReferences: refs, template: { id: tmpl.id, name: tmpl.name, connectors: tmpl.connectors } });
+ return safeResult({
+ definition,
+ connectionReferences: refs,
+ template: { id: tmpl.id, name: tmpl.name, connectors: tmpl.connectors },
+ connectionStatus,
+ ...unresolvedConnectors.length > 0 ? { unresolvedConnectors, hint: `Missing connections for: ${unresolvedConnectors.join(", ")}. Create them with create-connection or pick_or_create_connection.` } : {}
+ });
} catch (e) {
return safeError(e);
}
diff --git a/plugins/power-automate/skills/browse-flows/SKILL.md b/plugins/power-automate/skills/browse-flows/SKILL.md
index 07a1743e9..678e63ac3 100644
--- a/plugins/power-automate/skills/browse-flows/SKILL.md
+++ b/plugins/power-automate/skills/browse-flows/SKILL.md
@@ -15,8 +15,7 @@ Interactive skill for discovering Power Automate environments and flows.
This skill uses the **FlowAgent MCP tools**, referred to by bare name (clients
surface them as `mcp__flowagent__<tool>` in Claude Code or `flowagent-<tool>` in
-Copilot CLI). If MCP tools aren't available, run `/setup` to wire the FlowAgent
-MCP server.
+Copilot CLI). If no MCP tools are present, the plugin is not wired up — run the `setup` skill.
## Steps
diff --git a/plugins/power-automate/skills/build-flow/SKILL.md b/plugins/power-automate/skills/build-flow/SKILL.md
index ab83c8ea7..97855c101 100644
--- a/plugins/power-automate/skills/build-flow/SKILL.md
+++ b/plugins/power-automate/skills/build-flow/SKILL.md
@@ -4,7 +4,7 @@ description: Autonomously build a complete Power Automate flow from a descriptio
user-invocable: true
argument-hint: "<description>"
context: fork
-allowed-tools: Bash, Read, Write, Glob, Grep, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators
+allowed-tools: Bash, Read, Write, Glob, Grep, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators, mcp__flowagent__resolve_entity, mcp__flowagent__list_datasets, mcp__flowagent__list_tables
model: opus
---
@@ -20,8 +20,10 @@ The user's flow description is: `$ARGUMENTS`
This skill uses the **FlowAgent MCP tools**. Clients surface them with a
client-specific prefix — `mcp__flowagent__<tool>` (Claude Code) or
-`flowagent-<tool>` (Copilot CLI) — so they're referred to by bare name below.
-If MCP tools aren't available, run `/setup` to wire the FlowAgent MCP server.
+`flowagent-<tool>` (Copilot CLI) — so they're referred to by bare name below
+(e.g. `create_flow`). Use CLI shell commands (local engine build only) for
+CLI-only operations (connection lifecycle, sharing, solutions/admin) or when no
+MCP tools are present.
| Tool | Purpose |
|------|---------|
@@ -29,7 +31,10 @@ If MCP tools aren't available, run `/setup` to wire the FlowAgent MCP server.
| `get_connector` | Get the operation index for a connector |
| `get_operation_details` | Exact parameter names, types, enums, and required action type |
| `list_connections` | Verify connections exist |
-| `invoke_operation` | Resolve dynamic dropdown/tree values |
+| `resolve_entity` | Resolve display names to IDs (folders, teams, channels, lists, tables) |
+| `list_datasets` | Discover datasets for tabular connectors (SharePoint sites, SQL servers, Excel locations) |
+| `list_tables` | Discover tables/lists within a dataset (SharePoint lists, SQL tables) |
+| `invoke_operation` | Resolve dynamic dropdown/tree values (fallback for connectors not covered above) |
| `get_expression_help` | Look up Logic Apps expression functions + examples |
| `validate_flow` | Pre-flight definition check (offline rules) |
| `preflight_flow` | Multi-signal readiness check (missing refs, solution-wrap) |
@@ -61,25 +66,44 @@ If MCP tools aren't available, run `/setup` to wire the FlowAgent MCP server.
7. **Validate before creating.** Call `validate_flow` to catch errors before hitting the API.
+8. **NEVER use deprecated operations.** Common deprecated operations to avoid:
+ - Teams: `PostUserNotification`, `PostChannelNotification`, `PostMessageToChannel`, `PostMessageToChannelV2`, `PostMessageToChannelV3` → use `PostMessageToConversation`
+ - Teams: `PostUserAdaptiveCard`, `PostChannelAdaptiveCard` → use `PostCardToConversation`
+ - Outlook: `SendEmail` → use `SendEmailV2`; `OnNewEmail`/`OnNewEmailV2` → use `OnNewEmailV3`
+ - Approvals: `approvalSubscribeV2` → use `StartAndWaitForAnApproval`
+ - Planner: `CreateTask`/`CreateTask_V2` → use `CreateTask_V3`
+ - Forms: `GetFormResponses` (polling) → use `CreateFormWebhook` (webhook)
+
## Workflow
-1. **Discover environment**: Call `list_environments`. Use `query` param to filter by name if the user specified one.
+**Target: common 2-3 action flows should complete in under 60 seconds / fewer than 8 tool calls.**
-2. **Check for templates**: If the description matches a common pattern, call `list_templates` and `scaffold_flow` to start from a template instead of building from scratch.
+1. **Check for templates FIRST**: Call `list_templates`. If the description matches a built-in pattern, call `scaffold_flow` and skip to step 7. This is the fastest path.
-3. **Look up connector operations**: For each connector the flow needs, call `get_connector` with a `query` to find the right operation (e.g., `get_connector(connector="shared_teams", query="post message")`).
+2. **Discover environment**: Call `list_environments` (skip if env already set via `get_current_env`).
-4. **Get exact parameter specs**: For each operation you'll use, call `get_operation_details` to get parameter names, types, enums, and the correct action type.
+3. **Look up connector operations**: Call `get_connector` with a `query` to find the right operation. Verify the operation is NOT deprecated (see rule 8).
-5. **Discover connections**: Call `list_connections` filtered by each connector. Verify at least one has "Connected" status.
+4. **Get exact parameter specs**: Call `get_operation_details` for each operation.
-6. **Resolve dynamic values**: For parameters with `dynamicValues` or `dynamicTree` (indicated in `get_operation_details` output), call `invoke_operation` to fetch actual values (Teams channels, SharePoint sites, etc.).
+5. **Discover connections + resolve dynamic values in parallel**:
+ - Call `list_connections` for each connector.
+ - Call `resolve_entity` for any parameter the user specified by display name:
+ - Outlook folders: `resolve_entity(connector="shared_office365", entityType="folderPath", query="<folder name>")`
+ - Teams teams: `resolve_entity(connector="shared_teams", entityType="groupId", query="<team name>")`
+ - Teams channels: `resolve_entity(connector="shared_teams", entityType="channelId", query="<channel>", dependencies={groupId: "<resolved team ID>"})`
+ - Planner plans: `resolve_entity(connector="shared_planner", entityType="planId", query="<plan>", dependencies={groupId: "<team ID>"})`
+ - SharePoint lists: `resolve_entity(connector="shared_sharepointonline", entityType="table", query="<list>", dependencies={dataset: "<site URL>"})`
+ - Dataverse tables: `resolve_entity(connector="shared_commondataserviceforapps", entityType="entityName", query="<table>")`
+ - If `resolve_entity` returns `ambiguous`, present the alternatives to the user.
+ - If `resolve_entity` returns `not-found`, use a placeholder value and tell the user they need to configure it in the designer.
+ - **Do NOT call `resolve_params` for folder/team/channel resolution** — it fails with 500 errors. `resolve_entity` uses the API Hub directly and works.
-7. **Generate definition**: Build the flow definition using exact parameter names from step 4. Write to a JSON file.
+6. **Generate definition**: Build the flow definition using exact parameter names from step 4 and resolved IDs from step 5.
-8. **Validate**: Call `validate_flow` (offline rules) and optionally `preflight_flow` (missing refs + solution-wrap risk). Fix any errors.
+7. **Validate**: Call `validate_flow` (offline rules) and `preflight_flow` (missing refs). Fix errors.
-9. **Create flow**: Call `create_flow` in Stopped state.
+8. **Create flow**: Call `create_flow` in Stopped state.
10. **Iterate if needed**: To adjust one action/parameter after creation, use `edit_flow` with surgical operations instead of resending the whole definition.
@@ -95,3 +119,22 @@ validated function reference. Common patterns:
- Null handling: `coalesce()`, `@if(empty(...), 'default', ...)`
- `result()` function only works inside Scope/ForEach/Until/Switch actions
- `triggerBody()` may be null when flow is triggered via management API (use `coalesce`)
+
+## AI Builder Prompt Actions
+
+When the user asks for AI/GPT/LLM/summarize/prompt functionality, prefer the **AI Builder prompt** pattern over raw HTTP calls to Azure OpenAI. It uses Copilot credits and requires no API keys.
+
+**Two approaches:**
+
+1. **"Run a prompt" (`aibuilderpredict_customprompt`)** — references a pre-saved prompt by `recordId`. Simpler, but requires the prompt to already exist in AI Builder. Use template `ai-builder-prompt`.
+
+2. **Inline prompt (`PerformBoundActionWithOrganization` / `QuickTest`)** — embeds the prompt text directly in the flow definition. More complex but self-contained.
+
+Both use the Dataverse connector (`shared_commondataserviceforapps`). See `definition-reference.md` for the full action JSON shapes.
+
+**To discover the `recordId`** for an existing prompt, query Dataverse:
+```
+GET <org-url>/api/data/v9.2/msdyn_aiconfigurations?$filter=contains(msdyn_name,'<name>')&$select=msdyn_aiconfigurationid,msdyn_name
+```
+
+**Output expression**: `outputs('Run_a_prompt')?['body/responsev2/predictionOutput/text']`
diff --git a/plugins/power-automate/skills/create-flow/SKILL.md b/plugins/power-automate/skills/create-flow/SKILL.md
index 949a765bf..2443f8aa0 100644
--- a/plugins/power-automate/skills/create-flow/SKILL.md
+++ b/plugins/power-automate/skills/create-flow/SKILL.md
@@ -3,7 +3,7 @@ name: create-flow
description: Guided flow creation wizard. Use when the user wants to create a new flow interactively.
user-invocable: true
argument-hint: "[description]"
-allowed-tools: Bash, Read, Write, Glob, Grep, AskUserQuestion, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators
+allowed-tools: Bash, Read, Write, Glob, Grep, AskUserQuestion, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators, mcp__flowagent__resolve_entity, mcp__flowagent__list_datasets, mcp__flowagent__list_tables
model: opus
---
@@ -15,8 +15,10 @@ Walk the user through creating a Power Automate flow step by step.
This skill uses the **FlowAgent MCP tools**. Clients surface them with a
client-specific prefix — `mcp__flowagent__<tool>` (Claude Code) or
-`flowagent-<tool>` (Copilot CLI) — so they're referred to by bare name below.
-If MCP tools aren't available, run `/setup` to wire the FlowAgent MCP server.
+`flowagent-<tool>` (Copilot CLI) — so they're referred to by bare name below
+(e.g. `create_flow`). Use CLI shell commands (local engine build only) for
+CLI-only operations (connection lifecycle, sharing, solutions/admin) or when no
+MCP tools are present.
## Steps
diff --git a/plugins/power-automate/skills/debug-flow/SKILL.md b/plugins/power-automate/skills/debug-flow/SKILL.md
index 5cd590d18..e4653f33e 100644
--- a/plugins/power-automate/skills/debug-flow/SKILL.md
+++ b/plugins/power-automate/skills/debug-flow/SKILL.md
@@ -3,7 +3,7 @@ name: debug-flow
description: Debug a failed Power Automate flow run. Use when a flow failed, has errors, or the user wants to troubleshoot a run.
user-invocable: true
argument-hint: "[flow-id] [run-id]"
-allowed-tools: Bash, Read, Write, Glob, Grep, AskUserQuestion, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators
+allowed-tools: Bash, Read, Write, Glob, Grep, AskUserQuestion, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators, mcp__flowagent__resolve_entity, mcp__flowagent__list_datasets, mcp__flowagent__list_tables
model: opus
---
@@ -15,8 +15,9 @@ You are helping the user debug a failed Power Automate flow run.
This skill uses the **FlowAgent MCP tools**. Clients surface them with a
client-specific prefix — `mcp__flowagent__<tool>` (Claude Code) or
-`flowagent-<tool>` (Copilot CLI) — so they're referred to by bare name below.
-If MCP tools aren't available, run `/setup` to wire the FlowAgent MCP server.
+`flowagent-<tool>` (Copilot CLI) — so they're referred to by bare name below
+(e.g. `get_run_actions`). Use CLI shell commands (local engine build only) for
+CLI-only operations or when no MCP tools are present.
| Tool | Purpose |
|------|---------|
diff --git a/plugins/power-automate/skills/diagnose-flow/SKILL.md b/plugins/power-automate/skills/diagnose-flow/SKILL.md
index 832c61eea..b54dba52e 100644
--- a/plugins/power-automate/skills/diagnose-flow/SKILL.md
+++ b/plugins/power-automate/skills/diagnose-flow/SKILL.md
@@ -4,7 +4,7 @@ description: Deep autonomous diagnosis of a failed flow run. Provide environment
user-invocable: true
argument-hint: "<env-id> <flow-id> <run-id>"
context: fork
-allowed-tools: Bash, Read, Write, Glob, Grep, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators
+allowed-tools: Bash, Read, Write, Glob, Grep, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators, mcp__flowagent__resolve_entity, mcp__flowagent__list_datasets, mcp__flowagent__list_tables
model: opus
---
@@ -20,8 +20,7 @@ Parse `$ARGUMENTS` for: environment ID, flow ID, run ID.
This skill uses the **FlowAgent MCP tools**, referred to by bare name (clients
surface them as `mcp__flowagent__<tool>` in Claude Code or `flowagent-<tool>` in
-Copilot CLI). If MCP tools aren't available, run `/setup` to wire the FlowAgent
-MCP server.
+Copilot CLI). If no MCP tools are present, the plugin is not wired up — run the `setup` skill.
## Workflow
diff --git a/plugins/power-automate/skills/manage-desktop-flows/SKILL.md b/plugins/power-automate/skills/manage-desktop-flows/SKILL.md
index dfdaeec4d..2499748fb 100644
--- a/plugins/power-automate/skills/manage-desktop-flows/SKILL.md
+++ b/plugins/power-automate/skills/manage-desktop-flows/SKILL.md
@@ -15,8 +15,7 @@ Manage Power Automate Desktop (RPA) flows, machine groups, and run sessions.
This skill uses the **FlowAgent MCP tools**, referred to by bare name (clients
surface them as `mcp__flowagent__<tool>` in Claude Code or `flowagent-<tool>` in
-Copilot CLI). If MCP tools aren't available, run `/setup` to wire the FlowAgent
-MCP server.
+Copilot CLI). If no MCP tools are present, the plugin is not wired up — run the `setup` skill.
| Tool | Purpose |
|------|---------|
diff --git a/plugins/power-automate/skills/manage-flows/SKILL.md b/plugins/power-automate/skills/manage-flows/SKILL.md
index aba8dcc61..511680ef6 100644
--- a/plugins/power-automate/skills/manage-flows/SKILL.md
+++ b/plugins/power-automate/skills/manage-flows/SKILL.md
@@ -4,7 +4,7 @@ description: Manage flow lifecycle - publish, test, batch operations, inventory
user-invocable: true
argument-hint: "<operation> [flow-ids...]"
context: fork
-allowed-tools: Bash, Read, Write, Glob, Grep, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators
+allowed-tools: Bash, Read, Write, Glob, Grep, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment, mcp__flowagent__list_flows, mcp__flowagent__get_flow, mcp__flowagent__create_flow, mcp__flowagent__update_flow, mcp__flowagent__edit_flow, mcp__flowagent__copy_flow, mcp__flowagent__publish_flow, mcp__flowagent__disable_flow, mcp__flowagent__delete_flow, mcp__flowagent__run_flow, mcp__flowagent__get_run_history, mcp__flowagent__get_run_details, mcp__flowagent__get_run_actions, mcp__flowagent__get_run_action_repetitions, mcp__flowagent__cancel_run, mcp__flowagent__cancel_all_runs, mcp__flowagent__resubmit_run, mcp__flowagent__diagnose_run, mcp__flowagent__list_connections, mcp__flowagent__list_connectors, mcp__flowagent__get_connector, mcp__flowagent__search_operations, mcp__flowagent__get_operation_details, mcp__flowagent__pick_or_create_connection, mcp__flowagent__resolve_refs, mcp__flowagent__resolve_params, mcp__flowagent__scaffold_flow, mcp__flowagent__list_templates, mcp__flowagent__validate_flow, mcp__flowagent__preflight_flow, mcp__flowagent__smoke_test, mcp__flowagent__get_expression_help, mcp__flowagent__list_desktop_flows, mcp__flowagent__list_machine_groups, mcp__flowagent__run_desktop_flow, mcp__flowagent__get_flow_context, mcp__flowagent__set_current_flow, mcp__flowagent__clear_current_flow, mcp__flowagent__invoke_operation, mcp__flowagent__get_past_trigger_inputs, mcp__flowagent__test_connection, mcp__flowagent__fix_connection, mcp__flowagent__delete_connection, mcp__flowagent__preview_update, mcp__flowagent__get_backup, mcp__flowagent__list_backups, mcp__flowagent__restore_backup, mcp__flowagent__list_trigger_emulators, mcp__flowagent__resolve_entity, mcp__flowagent__list_datasets, mcp__flowagent__list_tables
model: opus
---
@@ -16,8 +16,9 @@ Autonomous agent for flow lifecycle operations: publish-and-test, batch operatio
This skill uses the **FlowAgent MCP tools**, referred to by bare name (clients
surface them as `mcp__flowagent__<tool>` in Claude Code or `flowagent-<tool>` in
-Copilot CLI). If MCP tools aren't available, run `/setup` to wire the FlowAgent
-MCP server.
+Copilot CLI). Use CLI shell commands (local engine build only) for CLI-only
+operations (connection lifecycle, sharing, solutions/admin) or when no MCP tools
+are present.
## Capabilities
diff --git a/plugins/power-automate/skills/route-environments/SKILL.md b/plugins/power-automate/skills/route-environments/SKILL.md
index 43b944d1d..a4fcb82a9 100644
--- a/plugins/power-automate/skills/route-environments/SKILL.md
+++ b/plugins/power-automate/skills/route-environments/SKILL.md
@@ -1,69 +1,65 @@
---
name: route-environments
-description: Manage environment resolution — check which environment you create flows in by default, list available environments, and set your working environment. Use when the user asks about environments, their default environment, where to create flows, or switching environments.
+description: Check Power Platform environment routing status and understand default environment resolution. Use when the user asks about environment routing, developer environments, or new maker landing. Routing is configured in the admin center, not here. NOT for listing flows or managing connections.
user-invocable: true
-argument-hint: "[list|check|set]"
+argument-hint: "[check|explain]"
allowed-tools: Bash, Read, Write, Glob, Grep, AskUserQuestion, mcp__flowagent__list_environments, mcp__flowagent__set_current_env, mcp__flowagent__get_current_env, mcp__flowagent__resolve_environment
model: opus
---
-# Environment Resolution
+# Environment Routing Manager
-You are helping the user understand and manage which Power Automate environment
-they work in — where their flows are created, where they should build new ones,
-and how to switch between environments.
+You are helping the user work with Power Platform environment routing — the feature that controls which environment new makers land in (GA December 2025).
> Uses the **FlowAgent MCP tools** (`resolve_environment`, `list_environments`,
-> `set_current_env`, `get_current_env`).
+> `set_current_env`), referred to by bare name. In Claude Code they appear as
+> `mcp__flowagent__<tool>`; in Copilot CLI as `flowagent-<tool>`.
-## Step 1: Understand what the user needs
+## Step 1: Check Current State
-- **"Which environment am I in?"** → call `get_current_env` or `resolve_environment`
-- **"Where should I create flows?"** → help them pick the right environment
-- **"What environments do I have?"** → call `list_environments`
-- **"Switch my environment"** → call `set_current_env`
+Call `resolve_environment` to see how the user's default environment resolves
+(routing → poll → fallback).
-## Step 2: List and explain environments
+## Step 2: Determine Operation
-Call `list_environments` and present a clear summary:
+### Check Routing Status
+Explain that environment routing redirects new makers from the default environment to a designated developer environment.
-| Environment | Type | Location | Notes |
-|-------------|------|----------|-------|
-| ... | Default / Developer / Sandbox / Production | ... | ... |
+Key facts:
+- Generally available since December 2025
+- Most tenants scope routing with `specificGroups` rather than tenant-wide
+- Common uses: steering new makers to developer environments, Copilot Studio isolation
-Help the user identify:
-- **Default environment** — shared, not recommended for production flows
-- **Developer environments** — personal, ideal for building and testing
-- **Production/Sandbox** — team environments for deployed flows
+### List Environments
+Call `list_environments` (use the `query` param to filter by name).
-## Step 3: Set the working environment
+Show environment types and help the user identify:
+- Their default environment
+- Any developer/sandbox environments
+- Environment with Dataverse linked
-If the user wants to create flows in a specific environment, call
-`set_current_env` with that environment ID. This pins all subsequent
-FlowAgent operations to that environment (no need to pass `--env` each time).
-
-**Recommendation for new users**: If they have a Developer environment, suggest
-using that. If not, suggest they ask their admin to provision one, or use the
-default environment for simple personal automations.
+### Resolve Default Environment
+Help the user understand which environment they'd land in by calling
+`resolve_environment`.
## Guidance
-- `resolve_environment` shows how the environment resolves (routing → poll → fallback)
-- `set_current_env` changes the session default — it does NOT change tenant-level routing
-- Tenant-level environment routing (which env new makers land in by default) is
- configured at the admin level in `admin.powerplatform.microsoft.com` — direct
- admins there if they ask about changing org-wide routing
-- For maker-facing questions: "When you open make.powerautomate.com, your default
- environment determines where new flows are created"
+- Environment routing is configured at the **tenant admin** level in the Power Platform admin center
+- It cannot be configured here — direct the user to `admin.powerplatform.microsoft.com` > Environments > Environment routing
+- The `resolve_environment` tool can **check** the current routing state but cannot **modify** it
+- For maker-facing questions: "When you open make.powerautomate.com, environment routing determines which environment you see first"
## Decision Tree
```
-User asks about environments?
-├── "Which environment am I in?" → get_current_env / resolve_environment
-├── "What environments exist?" → list_environments with summary table
-├── "Where should I build?" → Recommend Developer env; set_current_env
-├── "Switch to X environment" → set_current_env
-├── "How do I create a new environment?" → Direct to PPAC admin center
-└── "What is environment routing?" → Explain: determines default for new makers
+User asks about environment routing?
+├── "What is it?" → Explain: redirects new makers from default to dev env
+├── "Is it enabled?" → resolve_environment to check
+├── "How do I enable it?" → Direct to PPAC admin center
+├── "Which environment am I in?" → list_environments + resolve_environment
+└── "What environments exist?" → list_environments with details
```
+
+## References
+
+- [CLI Command Reference](../../references/cli-reference.md) — Environment commands
diff --git a/plugins/power-automate/skills/setup/SKILL.md b/plugins/power-automate/skills/setup/SKILL.md
index 7133dd173..63f547acb 100644
--- a/plugins/power-automate/skills/setup/SKILL.md
+++ b/plugins/power-automate/skills/setup/SKILL.md
@@ -62,29 +62,29 @@ az account get-access-token --resource https://service.flow.microsoft.com --outp
## Step 4: Check the FlowAgent tools are wired
The plugin talks to Power Automate through the **FlowAgent MCP server**, which is
-launched automatically from the plugin's `.mcp.json` via a small Node
-bootstrap that resolves `PLUGIN_ROOT` / `CLAUDE_PLUGIN_ROOT` and imports
-`server/mcp.mjs`.
+registered as `flowagent` in the plugin's `.mcp.json` and started automatically.
+`.mcp.json` loads the bundled `server/mcp.mjs` through a small Node bootstrap
+that resolves the plugin's installation directory (`PLUGIN_ROOT`, else
+`CLAUDE_PLUGIN_ROOT`, else the current directory) and prints an actionable error
+if the bundle can't be found.
- **If `flowagent-*` / `mcp__flowagent__*` tools appear in your tool list**: tell
them "The Power Automate tools are connected" and move on.
-- **If they're missing**: the MCP server isn't registered. Ask the user for
- confirmation before fixing:
+- **If they're missing**: the MCP server isn't registered. Fix it automatically:
- **Tell them**: "The FlowAgent MCP server isn't wired up yet. I can fix this
- by adding it to your `~/.copilot/mcp-config.json`. Shall I go ahead?"
-
- **If they confirm**, fix it:
-
- 1. **Locate the installed plugin's MCP bundle.** Run:
+ 1. **Locate the installed plugin's MCP bundle.** This only matches a bundle
+ inside a `power-automate` plugin directory, so it can't pick up another
+ plugin's MCP server:
```bash
- node -e "const fs=require('fs'),p=require('path'),d=p.join(process.env.HOME||process.env.USERPROFILE,'.copilot','installed-plugins');try{const find=(dir)=>{for(const e of fs.readdirSync(dir,{withFileTypes:true})){const f=p.join(dir,e.name);if(e.isDirectory())try{const r=find(f);if(r)return r}catch{}if(e.name==='mcp.mjs'&&dir.split(p.sep).includes('power-automate'))return dir}return null};const r=find(d);if(r)console.log(JSON.stringify({found:true,serverDir:r,mcpMjs:p.join(r,'mcp.mjs')}));else console.log(JSON.stringify({found:false}))}catch(e){console.log(JSON.stringify({found:false,error:e.message}))}"
+ node -e "const fs=require('fs'),p=require('path'),d=p.join(process.env.HOME||process.env.USERPROFILE,'.copilot','installed-plugins');const find=(dir)=>{let out=[];for(const e of fs.readdirSync(dir,{withFileTypes:true})){const f=p.join(dir,e.name);if(e.isDirectory()){try{out=out.concat(find(f))}catch{}}else if(e.name==='mcp.mjs'&&p.basename(p.dirname(dir))==='power-automate'){out.push(dir)}}return out};try{const hits=find(d);if(hits.length===1)console.log(JSON.stringify({found:true,serverDir:hits[0],mcpMjs:p.join(hits[0],'mcp.mjs')}));else if(hits.length>1)console.log(JSON.stringify({found:false,reason:'multiple power-automate bundles',candidates:hits}));else console.log(JSON.stringify({found:false}))}catch(e){console.log(JSON.stringify({found:false,error:e.message}))}"
```
+ If it reports `multiple power-automate bundles`, show the candidates and ask
+ the user which one to register rather than guessing.
- 2. **If found**, read `~/.copilot/mcp-config.json`, add the `flowagent` MCP
- entry, and write it back:
+ 2. **If exactly one was found**, read `~/.copilot/mcp-config.json`, add the
+ `flowagent` MCP entry, and write it back:
```bash
- node -e "const fs=require('fs'),p=require('path');const cfgPath=p.join(process.env.HOME||process.env.USERPROFILE,'.copilot','mcp-config.json');let cfg;try{cfg=JSON.parse(fs.readFileSync(cfgPath,'utf8'))}catch{cfg={mcpServers:{}}};if(!cfg.mcpServers)cfg.mcpServers={};if(cfg.mcpServers.flowagent){console.log('already registered');process.exit(0)}const pluginDir=p.join(process.env.HOME||process.env.USERPROFILE,'.copilot','installed-plugins');const find=(dir)=>{for(const e of fs.readdirSync(dir,{withFileTypes:true})){const f=p.join(dir,e.name);if(e.isDirectory())try{const r=find(f);if(r)return r}catch{}if(e.name==='mcp.mjs'&&dir.split(p.sep).includes('power-automate'))return dir}return null};const srvDir=find(pluginDir);if(!srvDir){console.log('mcp.mjs not found');process.exit(1)}const mcpPath=p.join(srvDir,'mcp.mjs');cfg.mcpServers.flowagent={command:'node',args:[mcpPath]};fs.writeFileSync(cfgPath,JSON.stringify(cfg,null,2)+'\n');console.log('registered flowagent MCP at '+mcpPath)"
+ node -e "const fs=require('fs'),p=require('path');const home=process.env.HOME||process.env.USERPROFILE;const cfgPath=p.join(home,'.copilot','mcp-config.json');let cfg;try{cfg=JSON.parse(fs.readFileSync(cfgPath,'utf8'))}catch{cfg={mcpServers:{}}};if(!cfg.mcpServers)cfg.mcpServers={};if(cfg.mcpServers.flowagent){console.log('already registered');process.exit(0)}const d=p.join(home,'.copilot','installed-plugins');const find=(dir)=>{let out=[];for(const e of fs.readdirSync(dir,{withFileTypes:true})){const f=p.join(dir,e.name);if(e.isDirectory()){try{out=out.concat(find(f))}catch{}}else if(e.name==='mcp.mjs'&&p.basename(p.dirname(dir))==='power-automate'){out.push(dir)}}return out};const hits=find(d);if(hits.length!==1){console.log(hits.length?'ambiguous: '+JSON.stringify(hits):'mcp.mjs not found');process.exit(1)}const mcpPath=p.join(hits[0],'mcp.mjs');cfg.mcpServers.flowagent={command:'node',args:[mcpPath]};fs.writeFileSync(cfgPath,JSON.stringify(cfg,null,2)+'\n');console.log('registered flowagent MCP at '+mcpPath)"
```
3. **Tell the user** to restart the agent (Copilot CLI: `/restart`, Claude Code:
@@ -94,9 +94,8 @@ bootstrap that resolves `PLUGIN_ROOT` / `CLAUDE_PLUGIN_ROOT` and imports
plugin first:
```
/plugin marketplace add microsoft/power-platform-skills
- /plugin install power-automate@power-platform-skills
```
- Then run `/setup` again.
+ Then select `power-automate` and run `/setup` again.
## Step 5: Smoke Test