[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M699KY0SBFPSJ63T3P4665YS":3,"skill-same:01M699KY0SBFPSJ63T3P4665YS":75},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":23,"publishedAt":44,"linkOnly":45,"markdownContent":46,"markdownBody":47,"frontMatter":48,"refName":52,"commitSha":53,"skillDirectory":54,"forksCount":55,"repositoryHtmlUrl":56,"repositoryHomepageUrl":57,"ownerHtmlUrl":58,"ownerBlogUrl":59,"ownerDescription":60,"updatedAt":61,"install":62,"resources":74},"01M699KY0SBFPSJ63T3P4665YS","add-workiq",null,"Adds Work IQ (M365 Copilot Search) to a Power Apps code app via the Work IQ Copilot MCP connector (shared_a365copilotchatmcp), then wires up a production-ready McpSession wrapper for AI-powered, knowledge-grounded search and chat. Use when integrating Microsoft 365 Copilot search\u002Fchat. The CopilotChat tool searches internal Microsoft 365 content (documents, emails, chats, sites, files) across your organization — prefer workload-specific tools (SharePoint, OneDrive, Teams, Mail) when the workload is explicit; do not use it for general knowledge, news, public web, or external information.","microsoft\u002Fpower-platform-skills","microsoft","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6154722?v=4","01M698VYDXZ6JW5WH3CRV650R8","Microsoft","01M699JVYJFB75D9JM70BN4H0Q",1146,"MIT","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fpower-platform-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fcode-apps\u002Fskills\u002Fadd-workiq\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43],"workiq","add","add workiq","copilot","Bash","when","documents","apps","information","files","production-ready","knowledge","lsp","up","search","power","ready","app","shared","MCP","2026-11-10 10:12:30",false,"---\nname: add-workiq\ndescription: Adds Work IQ (M365 Copilot Search) to a Power Apps code app via the Work IQ Copilot MCP connector (shared_a365copilotchatmcp), then wires up a production-ready McpSession wrapper for AI-powered, knowledge-grounded search and chat. Use when integrating Microsoft 365 Copilot search\u002Fchat. The CopilotChat tool searches internal Microsoft 365 content (documents, emails, chats, sites, files) across your organization — prefer workload-specific tools (SharePoint, OneDrive, Teams, Mail) when the workload is explicit; do not use it for general knowledge, news, public web, or external information.\nuser-invocable: true\nallowed-tools: Read, Edit, Write, Grep, Glob, Bash, LSP, TaskCreate, TaskUpdate, TaskList, TaskGet, AskUserQuestion, Skill\nmodel: sonnet\n---\n\n**? Shared Instructions: [shared-instructions.md](..\u002F..\u002Fshared\u002Fshared-instructions.md)** - Cross-cutting concerns.\n\n# Add Work IQ (M365 Copilot Search)\n\nWork IQ is accessed through the dedicated **Work IQ Copilot MCP** connector (`shared_a365copilotchatmcp`; shown as \"Work IQ Copilot MCP (Preview)\" in the maker portal). It exposes an MCP (Model Context Protocol) endpoint whose `CopilotChat` tool performs AI-powered, knowledge-grounded search and conversation over Microsoft 365 content.\n\n> This is the purpose-built Work IQ connector and generates a `WorkIQCopilotMCPService` with a single `mcp_m365copilot` operation. **Every command and code reference in this skill is specific to `shared_a365copilotchatmcp`** (connection commands, and the generated `WorkIQCopilotMCPService` \u002F `WorkIQCopilotMCPModel` files). Do not run this skill for a different connector. If you instead need the broader `shared_a365mcpservers` \"Microsoft 365 MCP Servers\" bundle (Mail\u002FTeams\u002FSharePoint MCP servers), add it via `\u002Fadd-connector` — its generated service is `MicrosoftMCPServersService`, so you must adjust the Step 2 commands and the wrapper imports accordingly.\n\n> ⚠️ **Work IQ uses MCP.** A JSON-RPC `initialize` handshake runs before the first `tools\u002Fcall`. This connector's server (`Microsoft.MCPPlatform.WebApi`) is **stateless-tolerant** — do **NOT** send an `Mcp-Session-Id` on `initialize` (the server treats it as a session lookup and returns `-32001 Session not found`). Drive the connector through the `McpSession` wrapper below, which runs the handshake, sends **no** session id by default, sequences JSON-RPC ids, auto-retries on `Session not found`, and parses the nested response for you.\n\n## Workflow\n\n1. Check Memory Bank → 2. Add Connector → 3. Inspect Generated Service → 4. Create McpSession Wrapper → 5. Use Work IQ → 6. Build → 7. Update Memory Bank\n\n---\n\n### Step 1: Check Memory Bank\n\nCheck for `memory-bank.md` per [shared-instructions.md](..\u002F..\u002Fshared\u002Fshared-instructions.md).\n\n### Step 2: Add Connector\n\nThe Power Apps code-app CLI (`@microsoft\u002Fpower-apps-cli`, invoked as `pa` or `power-apps` — resolve via [cli-binary.md](..\u002F..\u002Fshared\u002Fcli-binary.md)) adds the data source and generates the typed service. Make sure the CLI is installed in the project (see cli-binary.md) and you are signed in (`pa auth status`, or `power-apps auth-status` on `power-apps`-only projects; it shares the same auth as the rest of the code-app skills).\n\nWork IQ is a **non-tabular** connector (api id `shared_a365copilotchatmcp`, shown as **Work IQ Copilot MCP (Preview)**). Get its connection as described in [connector-reference.md](..\u002F..\u002Fshared\u002Fconnector-reference.md#connections).\n\n#### CLI 1.3.0+ (`PA_INLINE_CONNECTIONS=yes`)\n\nTell the user that adding Work IQ may create a connection with their account, then run the add without `-c`:\n\n```bash\npa app add data-source --connector shared_a365copilotchatmcp --non-interactive\n```\n\nHandle the result with the outcome table in connector-reference.md. Work IQ supports single sign-on, so when the user has no Work IQ connection the CLI either creates one itself or suggests `--use-sso`; with the user's OK, re-run with `--use-sso`.\n\n#### Older CLIs: Find or Create the Connection\n\n**Check for an existing connection first:**\n\n```bash\npa connection list\n```\n\nLook for a **Work IQ Copilot MCP (Preview)** connection (api id `shared_a365copilotchatmcp`) in the output. If one is listed, note its Connection ID and skip to \"Older CLIs: Add the Data Source\" below.\n\n**Otherwise create one**, after asking the user, with the native `create-connection` verb:\n\n```bash\npa connection create --connector shared_a365copilotchatmcp\n```\n\n- The environment is read automatically from the app's `power.config.json` — you do **not** need to pass an environment id.\n- If the connection needs a browser sign-in, the CLI can only do that from an interactive terminal. If it says so, follow [Create a connection with the user](..\u002F..\u002Fshared\u002Fconnector-reference.md#create-a-connection-with-the-user): the user runs the same command in their own terminal.\n- On success it prints the **Connection ID** — save it for the next step.\n\n**STOP HERE if a browser sign-in is needed:**\n\n1. Tell the user the browser has opened (or ask them to run the command in their own terminal).\n2. Ask them to sign in with their Microsoft 365 account and grant consent to the **Work IQ Copilot MCP** connector.\n3. **Wait for the user to confirm** the browser shows success before continuing.\n\n**If `create-connection` fails:**\n- \"not signed in\" \u002F auth error → run `pa auth login` (or `power-apps login` on `power-apps`-only projects), then retry.\n- \"Connection creation was cancelled.\" → the browser flow was closed early; re-run and complete it.\n- Any other non-zero exit → report the exact error and STOP.\n\nAs a fallback, the user can create the connection manually in the maker portal: `https:\u002F\u002Fmake.powerapps.com\u002Fenvironments\u002F\u003Cenvironment-id>\u002Fconnections` → **+ New connection** → search for \"Work IQ Copilot MCP\" → Create, then re-run `list-connections`.\n\n#### Older CLIs: Add the Data Source\n\nOnce the connection exists, add it to the code app (this is what generates the typed service + model):\n\n```bash\npa app add data-source --connector shared_a365copilotchatmcp -c \u003Cconnection-id>\n```\n\nThis is a **non-tabular** connector — only `--connector` (api id) and `-c` (connection id) are needed.\n\n### Step 3: Inspect Generated Service\n\nAfter adding the connector, confirm the generated service is present. This is a small, single-operation service, so you can read it directly or grep it:\n\n```\nGrep pattern=\"async \\w+\" path=\"src\u002Fgenerated\u002Fservices\u002FWorkIQCopilotMCPService.ts\"\n```\n\nThe `WorkIQCopilotMCPService` exposes exactly one operation — **`mcp_m365copilot`** (\"Work IQ Copilot (Preview)\"), plus a `Getmcp_m365copilot` GET variant used only for connection verification. Work IQ \u002F CopilotChat is driven through **`mcp_m365copilot`**.\n\nIts generated signature is:\n\n```typescript\npublic static async mcp_m365copilot(\n  Mcp_Session_Id?: string,\n  queryRequest?: QueryRequest\n): Promise\u003CIOperationResult\u003Cvoid>>\n```\n\n- First argument is the **MCP session id** (the connector's `Mcp-Session-Id` parameter). Leave it **`undefined`** — this server assigns\u002Fneeds no client session id, and sending one on `initialize` returns `-32001` (see below).\n- Second argument is the JSON-RPC body, typed as `QueryRequest` (`{ jsonrpc?, id?, method?, params?, result?, error? }`) — exported from `src\u002Fgenerated\u002Fmodels\u002FWorkIQCopilotMCPModel.ts`.\n- Return type is `IOperationResult\u003Cvoid>`; the actual JSON-RPC \u002F SSE body arrives in `result.data` at runtime.\n\n**Facts you can rely on (do not try to discover them at runtime):**\n\n- The tool name is **`CopilotChat`** (case-sensitive). Do not substitute `query`, `search`, or `find`.\n- The argument key is **`message`** — not `query`, `prompt`, or `question`.\n- **Do NOT send an `Mcp-Session-Id` on the `initialize` handshake.** This connector's server treats an incoming id as an existing-session lookup and returns `-32001 Session not found`. The server is **stateless-tolerant**: `initialize` and `tools\u002Fcall` both succeed with **no** session id, so the `McpSession` wrapper below tracks none by default.\n\n> **Session-id handling (verified during testing).** This connector's MCP server is **stateless-tolerant**. `initialize` with **no** `Mcp-Session-Id` returns `200` with server capabilities, and a subsequent `tools\u002Fcall` with **no** id returns the Copilot reply — no session id needs to be tracked or echoed. Do **not** generate a client id and send it on `initialize`: the server treats it as a lookup and returns `404 \u002F -32001 Session not found` (this was a real bug in an earlier version of this wrapper). Note that the code-apps data layer's `IOperationResult\u003CTResponse>` exposes only `{ success, data, error, skipToken, count, fileName }` — it does **not** surface response headers — so if a future MCP server returns a session id only in the `Mcp-Session-Id` **response header**, it would be unreadable here. The wrapper still defensively adopts a server id if one ever appears inside `result.data`.\n\n### Step 4: Create McpSession Wrapper\n\n⚠️ **CRITICAL:** MCP session handling and response parsing are intricate. Copy the production-ready `McpSession` class below **exactly**. It runs the `initialize` handshake (sending **no** session id), sequences JSON-RPC ids, auto-retries on \"Session not found\", persists the conversation id, and parses the deeply nested response.\n\nCreate `src\u002Fconnectors\u002FmcpClient.ts`:\n\n```typescript\n\u002F\u002F src\u002Fconnectors\u002FmcpClient.ts\nimport type { IOperationResult } from '@microsoft\u002Fpower-apps\u002Fdata'\nimport { WorkIQCopilotMCPService } from '..\u002Fgenerated\u002Fservices\u002FWorkIQCopilotMCPService'\nimport type { QueryRequest } from '..\u002Fgenerated\u002Fmodels\u002FWorkIQCopilotMCPModel'\n\nexport interface JsonRpcRequest {\n  jsonrpc: '2.0'\n  id?: string\n  method: string\n  params?: Record\u003Cstring, unknown>\n}\n\nexport interface JsonRpcResponse {\n  jsonrpc?: string\n  id?: string\n  result?: Record\u003Cstring, unknown>\n  error?: { code?: number; message?: string; data?: unknown }\n}\n\ntype CopilotConversationMessage = {\n  text?: string\n  attributions?: Array\u003C{\n    attributionType?: string\n    providerDisplayName?: string\n    seeMoreWebUrl?: string\n  }>\n}\n\ntype CopilotConversation = {\n  messages?: CopilotConversationMessage[]\n}\n\nfunction parseRpc(result: IOperationResult\u003Cunknown>): JsonRpcResponse {\n  if (!result.success && result.error) {\n    return { error: { message: result.error.message } }\n  }\n\n  const data: unknown = result.data\n  if (data == null) return {}\n  if (typeof data === 'object') return data as JsonRpcResponse\n  if (typeof data === 'string') {\n    \u002F\u002F Handle SSE framing: \"event: message\\ndata: {JSON}\"\n    const dataLines = data\n      .split(\u002F\\r?\\n\u002F)\n      .filter((line) => line.startsWith('data:'))\n      .map((line) => line.slice(5).trim())\n    \u002F\u002F Per the SSE spec, multiple `data:` lines are joined with newlines — a single\n    \u002F\u002F JSON object can be split across lines, so joining with '' would corrupt it.\n    const payload = dataLines.length ? dataLines.join('\\n') : data\n    try {\n      return JSON.parse(payload) as JsonRpcResponse\n    } catch {\n      return { result: { raw: data } }\n    }\n  }\n\n  return { result: { raw: data } }\n}\n\nexport class McpSession {\n  private nextId = 1\n  \u002F\u002F MCP Streamable HTTP: the client must NOT send a session id on `initialize` —\n  \u002F\u002F the server assigns one. Sending a client-generated id makes this connector's\n  \u002F\u002F server return `404 \u002F -32001 Session not found`. This server is stateless-\n  \u002F\u002F tolerant, so we send no id at all; `extractSessionId` still adopts a server\n  \u002F\u002F id if one ever surfaces in the response body.\n  private sessionId: string | undefined = undefined\n  private conversationId: string | undefined\n  private initialized = false\n\n  private extractSessionId(raw: IOperationResult\u003Cunknown>): string | undefined {\n    const container = raw as unknown as Record\u003Cstring, unknown>\n    const dataObj =\n      raw.data && typeof raw.data === 'object'\n        ? (raw.data as Record\u003Cstring, unknown>)\n        : undefined\n    const resultObj =\n      dataObj?.result && typeof dataObj.result === 'object'\n        ? (dataObj.result as Record\u003Cstring, unknown>)\n        : undefined\n\n    const candidates: Array\u003Cunknown> = [\n      dataObj?.['Mcp-Session-Id'],\n      dataObj?.mcpSessionId,\n      dataObj?.sessionId,\n      resultObj?.['Mcp-Session-Id'],\n      resultObj?.mcpSessionId,\n      resultObj?.sessionId,\n      container['Mcp-Session-Id'],\n      container.mcpSessionId,\n      container.sessionId,\n    ]\n\n    const found = candidates.find((value) => typeof value === 'string' && value.length > 0)\n    return typeof found === 'string' ? found : undefined\n  }\n\n  private isSessionNotFound(res: JsonRpcResponse): boolean {\n    const message = (res.error?.message ?? '').toLowerCase()\n    return message.includes('session not found') || res.error?.code === -32001\n  }\n\n  private resetSession(): void {\n    \u002F\u002F Drop any session id and re-handshake from scratch (no id on `initialize`).\n    this.sessionId = undefined\n    this.initialized = false\n  }\n\n  private async send(\n    method: string,\n    params?: Record\u003Cstring, unknown>,\n    allowRetry = true\n  ): Promise\u003CJsonRpcResponse> {\n    const req: JsonRpcRequest = { jsonrpc: '2.0', id: String(this.nextId++), method, params }\n\n    \u002F\u002F Send no session id on `initialize` (server treats any id as existing-session lookup).\n    const sessionId = method === 'initialize' ? undefined : this.sessionId\n    const raw = (await WorkIQCopilotMCPService.mcp_m365copilot(\n      sessionId,\n      req as unknown as QueryRequest\n    )) as unknown as IOperationResult\u003Cunknown>\n\n    const negotiatedSessionId = this.extractSessionId(raw)\n    if (negotiatedSessionId) {\n      this.sessionId = negotiatedSessionId\n    }\n\n    const parsed = parseRpc(raw)\n\n    if (allowRetry && method !== 'initialize' && this.isSessionNotFound(parsed)) {\n      this.resetSession()\n      await this.initialize()\n      return this.send(method, params, false)\n    }\n\n    return parsed\n  }\n\n  async initialize(): Promise\u003CJsonRpcResponse> {\n    const res = await this.send('initialize', {\n      protocolVersion: '2025-06-18',\n      capabilities: {},\n      clientInfo: { name: 'Power Apps Code App', version: '1.0.0' },\n    })\n    \u002F\u002F Fail fast: surface a failed handshake instead of continuing to `tools\u002Fcall`.\n    if (res.error) {\n      throw new Error(`MCP initialize failed: ${res.error.message ?? JSON.stringify(res.error)}`)\n    }\n    this.initialized = true\n    return res\n  }\n\n  \u002F** Discover the available MCP tools (optional; the tool name is fixed as `CopilotChat`). *\u002F\n  async listTools(): Promise\u003CJsonRpcResponse> {\n    if (!this.initialized) await this.initialize()\n    return this.send('tools\u002Flist', {})\n  }\n\n  async callCopilotChat(message: string): Promise\u003C{ text: string; conversationId?: string }> {\n    if (!this.initialized) await this.initialize()\n    const raw = await this.send('tools\u002Fcall', {\n      name: 'CopilotChat',\n      arguments: {\n        message,\n        ...(this.conversationId ? { conversationId: this.conversationId } : {}),\n      },\n    })\n\n    \u002F\u002F Surface MCP\u002Fconnector errors as thrown exceptions so callers can `try\u002Fcatch`\n    \u002F\u002F instead of string-matching the returned text.\n    if (raw.error) {\n      throw new Error(raw.error.message ?? JSON.stringify(raw.error))\n    }\n\n    const parsed = extractCopilotText(raw)\n    if (parsed.conversationId) {\n      this.conversationId = parsed.conversationId\n    }\n\n    return { text: parsed.text, conversationId: parsed.conversationId }\n  }\n}\n\nfunction extractContentText(res: JsonRpcResponse): string | undefined {\n  const content = res.result?.content as Array\u003C{ type?: string; text?: string }> | undefined\n  if (!Array.isArray(content)) {\n    return undefined\n  }\n\n  const textBlocks = content\n    .filter((c) => c.type === 'text' && typeof c.text === 'string')\n    .map((c) => c.text!.trim())\n    .filter((value) => value.length > 0)\n\n  if (textBlocks.length === 0) {\n    return undefined\n  }\n\n  \u002F\u002F Prefer the JSON payload block. Some responses append metadata text blocks\n  \u002F\u002F such as \"CorrelationId: ...\" that should not be concatenated.\n  const jsonBlock = textBlocks.find(\n    (block) => block.startsWith('{') && \u002F\"conversationId\"|\"rawResponse\"|\"reply\"\u002F.test(block)\n  )\n  if (jsonBlock) {\n    return jsonBlock\n  }\n\n  const nonMetadata = textBlocks.find((block) => !\u002F^CorrelationId\\s*:\u002Fi.test(block))\n  return nonMetadata ?? textBlocks[0]\n}\n\nexport function extractCopilotText(res: JsonRpcResponse): {\n  text: string\n  conversationId?: string\n} {\n  const rawText = extractContentText(res)\n  if (!rawText) {\n    return { text: res.result ? JSON.stringify(res.result, null, 2) : '(no content returned)' }\n  }\n\n  try {\n    const inner = JSON.parse(rawText) as {\n      conversationId?: string\n      reply?: string\n      message?: string\n      rawResponse?: string\n    }\n\n    if (typeof inner.rawResponse === 'string') {\n      try {\n        const convo = JSON.parse(inner.rawResponse) as CopilotConversation\n        const messages = Array.isArray(convo.messages) ? convo.messages : []\n        \u002F\u002F messages[0] echoes the user query; the AI reply is the one carrying\n        \u002F\u002F attributions (citations). Fall back to index 1, then the last message.\n        const attributed = messages.find(\n          (m) => Array.isArray(m.attributions) && m.attributions.length > 0\n        )\n        const selected = attributed ?? messages[1] ?? messages[messages.length - 1]\n        const replyText = selected?.text?.trim()\n        if (replyText) {\n          return { text: replyText, conversationId: inner.conversationId }\n        }\n      } catch {\n        \u002F\u002F Fall through to simple reply extraction.\n      }\n    }\n\n    const fallbackText = inner.reply?.trim() || inner.message?.trim() || rawText\n    return { text: fallbackText, conversationId: inner.conversationId }\n  } catch {\n    return { text: rawText }\n  }\n}\n```\n\n> **Session-id note (verified during testing).** `McpSession` starts with **no** session id and sends none on the `initialize` handshake. Testing against `shared_a365copilotchatmcp` (server `Microsoft.MCPPlatform.WebApi`) confirmed it is **stateless-tolerant**: `initialize` with no id returns `200` + capabilities, and `tools\u002Fcall` with no id returns the Copilot reply. Sending a client-generated id on `initialize` instead makes the server return `404 \u002F -32001 Session not found` — that was the original bug. `IOperationResult` exposes only `{ success, data, error, skipToken, count, fileName }` (no response headers), so a header-only session id would be unreadable here; `extractSessionId` still adopts a server id if one ever appears inside `result.data`, and the handshake auto-retries on `Session not found` for resilience.\n>\n> If you ever bind a *different* MCP connector that is genuinely stateful and returns its session id only in the `Mcp-Session-Id` response header, this SDK cannot read it — capture one raw `mcp_m365copilot` result in the debugger to confirm where the id surfaces, and if it appears inside `result.data`, add that path to `extractSessionId`.\n\n### Step 5: Use Work IQ\n\nInitialize **once per app** (e.g., in a React `useEffect` on boot or a module singleton) and reuse for all Work IQ calls:\n\n```typescript\nimport { McpSession } from '.\u002Fconnectors\u002FmcpClient'\n\n\u002F\u002F Initialize once per app session and reuse across calls.\nconst workIqSession = new McpSession()\n\nexport async function queryWorkIQ(userPrompt: string): Promise\u003Cstring> {\n  try {\n    const { text } = await workIqSession.callCopilotChat(userPrompt)\n    return text\n  } catch (error) {\n    const msg = error instanceof Error ? error.message : 'Work IQ query failed'\n    console.error('Work IQ Error:', msg)\n    throw error\n  }\n}\n```\n\n**Key patterns:**\n\n- ✅ Initialize once, reuse across multiple calls (never `new McpSession()` per request)\n- ✅ Pass context-specific prompts to `callCopilotChat()`\n- ✅ The session auto-reinitializes if a \"Session not found\" error occurs\n- ✅ `conversationId` is automatically persisted across calls for multi-turn chats\n\n#### Prompt Structure\n\nWork IQ responds well to **context-rich, structured prompts**. Adapt this pattern for your scenario:\n\n```typescript\nconst prompt = `\nYou are [role\u002Fexpert description].\n\n**Context:**\n- [Relevant data or background information]\n- [Additional context as needed]\n\n**Task:** [Clear, specific instruction]\n\n**Format:**\n- Use markdown with clear section headings (## Summary, ## Action Items, etc.)\n- Specify limits (word count, number of items, etc.)\n`.trim()\n\nconst { text } = await workIqSession.callCopilotChat(prompt)\n```\n\nAdaptable scenarios: meeting summaries with action items, prioritized daily action items from email, project risk analysis from documents, team performance insights, or any knowledge-grounded analysis over M365 data.\n\n#### Response Parsing\n\n`callCopilotChat()` already unwraps the nested JSON-RPC \u002F SSE response and returns clean `text`. Parse that text according to the format you requested.\n\n**For structured markdown output** (when you asked for `## sections`):\n\n```typescript\nfunction extractSection(text: string, sectionName: string): string[] {\n  const regex = new RegExp(`##\\\\s*${sectionName}\\\\s*([\\\\s\\\\S]*?)(?=##|$)`)\n  const match = text.match(regex)\n  if (!match) return []\n\n  return match[1]\n    .split('\\n')\n    .filter((line) => line.trim().startsWith('-'))\n    .map((line) => line.replace(\u002F^-\\s*\u002F, '').trim())\n    .filter(Boolean)\n}\n\nconst { text } = await workIqSession.callCopilotChat(prompt)\nconst summary = extractSection(text, 'Summary')\nconst actionItems = extractSection(text, 'Action Items')\n```\n\n**For unstructured output** — use `text` directly (display as-is or format for your UI).\n\n#### Why the McpSession Pattern Is Required\n\nWork IQ uses **MCP (Model Context Protocol)**. Driving it correctly requires:\n\n1. **Session initialization** before the first call (handshake to exchange capabilities)\n2. **Session handling** — this connector is **stateless-tolerant**, so the wrapper sends **no** session id (sending one on `initialize` triggers `-32001 Session not found`); it defensively adopts a server id only if one ever surfaces in the response body (see the session-id note above)\n3. **JSON-RPC id sequencing** (each request needs a unique incrementing id)\n4. **Multi-turn conversation support** via conversation-id persistence\n5. **Nested response parsing** (JSON-RPC → text content → inner JSON → Graph conversation)\n6. **Automatic recovery** on session timeouts (`-32001` \u002F \"Session not found\")\n\n`McpSession` handles all of this. Bypassing it (ad-hoc per-call ids or direct calls without the handshake) leads to \"Session not found\" errors and failed integrations.\n\n### Step 6: Build\n\n```bash\nnpm run build\n```\n\nFix TypeScript errors before proceeding. Do NOT deploy yet.\n\n### Step 7: Update Memory Bank\n\nUpdate `memory-bank.md` with: connector added (`shared_a365copilotchatmcp`), McpSession wrapper created at `src\u002Fconnectors\u002FmcpClient.ts`, Work IQ usage wired up, build status.\n\n**IMPORTANT — Do NOT save sensitive information:**\n\n- ❌ OAuth URLs or consent links\n- ❌ Connection IDs\n- ❌ Session IDs or tokens\n- ❌ Environment IDs\n- ❌ Any authentication credentials\n\nOnly save high-level progress like \"Work IQ Copilot MCP connector configured\" or \"Work IQ CopilotChat integration implemented via McpSession\".\n","**? Shared Instructions: [shared-instructions.md](..\u002F..\u002Fshared\u002Fshared-instructions.md)** - Cross-cutting concerns.\n\n# Add Work IQ (M365 Copilot Search)\n\nWork IQ is accessed through the dedicated **Work IQ Copilot MCP** connector (`shared_a365copilotchatmcp`; shown as \"Work IQ Copilot MCP (Preview)\" in the maker portal). It exposes an MCP (Model Context Protocol) endpoint whose `CopilotChat` tool performs AI-powered, knowledge-grounded search and conversation over Microsoft 365 content.\n\n> This is the purpose-built Work IQ connector and generates a `WorkIQCopilotMCPService` with a single `mcp_m365copilot` operation. **Every command and code reference in this skill is specific to `shared_a365copilotchatmcp`** (connection commands, and the generated `WorkIQCopilotMCPService` \u002F `WorkIQCopilotMCPModel` files). Do not run this skill for a different connector. If you instead need the broader `shared_a365mcpservers` \"Microsoft 365 MCP Servers\" bundle (Mail\u002FTeams\u002FSharePoint MCP servers), add it via `\u002Fadd-connector` — its generated service is `MicrosoftMCPServersService`, so you must adjust the Step 2 commands and the wrapper imports accordingly.\n\n> ⚠️ **Work IQ uses MCP.** A JSON-RPC `initialize` handshake runs before the first `tools\u002Fcall`. This connector's server (`Microsoft.MCPPlatform.WebApi`) is **stateless-tolerant** — do **NOT** send an `Mcp-Session-Id` on `initialize` (the server treats it as a session lookup and returns `-32001 Session not found`). Drive the connector through the `McpSession` wrapper below, which runs the handshake, sends **no** session id by default, sequences JSON-RPC ids, auto-retries on `Session not found`, and parses the nested response for you.\n\n## Workflow\n\n1. Check Memory Bank → 2. Add Connector → 3. Inspect Generated Service → 4. Create McpSession Wrapper → 5. Use Work IQ → 6. Build → 7. Update Memory Bank\n\n---\n\n### Step 1: Check Memory Bank\n\nCheck for `memory-bank.md` per [shared-instructions.md](..\u002F..\u002Fshared\u002Fshared-instructions.md).\n\n### Step 2: Add Connector\n\nThe Power Apps code-app CLI (`@microsoft\u002Fpower-apps-cli`, invoked as `pa` or `power-apps` — resolve via [cli-binary.md](..\u002F..\u002Fshared\u002Fcli-binary.md)) adds the data source and generates the typed service. Make sure the CLI is installed in the project (see cli-binary.md) and you are signed in (`pa auth status`, or `power-apps auth-status` on `power-apps`-only projects; it shares the same auth as the rest of the code-app skills).\n\nWork IQ is a **non-tabular** connector (api id `shared_a365copilotchatmcp`, shown as **Work IQ Copilot MCP (Preview)**). Get its connection as described in [connector-reference.md](..\u002F..\u002Fshared\u002Fconnector-reference.md#connections).\n\n#### CLI 1.3.0+ (`PA_INLINE_CONNECTIONS=yes`)\n\nTell the user that adding Work IQ may create a connection with their account, then run the add without `-c`:\n\n```bash\npa app add data-source --connector shared_a365copilotchatmcp --non-interactive\n```\n\nHandle the result with the outcome table in connector-reference.md. Work IQ supports single sign-on, so when the user has no Work IQ connection the CLI either creates one itself or suggests `--use-sso`; with the user's OK, re-run with `--use-sso`.\n\n#### Older CLIs: Find or Create the Connection\n\n**Check for an existing connection first:**\n\n```bash\npa connection list\n```\n\nLook for a **Work IQ Copilot MCP (Preview)** connection (api id `shared_a365copilotchatmcp`) in the output. If one is listed, note its Connection ID and skip to \"Older CLIs: Add the Data Source\" below.\n\n**Otherwise create one**, after asking the user, with the native `create-connection` verb:\n\n```bash\npa connection create --connector shared_a365copilotchatmcp\n```\n\n- The environment is read automatically from the app's `power.config.json` — you do **not** need to pass an environment id.\n- If the connection needs a browser sign-in, the CLI can only do that from an interactive terminal. If it says so, follow [Create a connection with the user](..\u002F..\u002Fshared\u002Fconnector-reference.md#create-a-connection-with-the-user): the user runs the same command in their own terminal.\n- On success it prints the **Connection ID** — save it for the next step.\n\n**STOP HERE if a browser sign-in is needed:**\n\n1. Tell the user the browser has opened (or ask them to run the command in their own terminal).\n2. Ask them to sign in with their Microsoft 365 account and grant consent to the **Work IQ Copilot MCP** connector.\n3. **Wait for the user to confirm** the browser shows success before continuing.\n\n**If `create-connection` fails:**\n- \"not signed in\" \u002F auth error → run `pa auth login` (or `power-apps login` on `power-apps`-only projects), then retry.\n- \"Connection creation was cancelled.\" → the browser flow was closed early; re-run and complete it.\n- Any other non-zero exit → report the exact error and STOP.\n\nAs a fallback, the user can create the connection manually in the maker portal: `https:\u002F\u002Fmake.powerapps.com\u002Fenvironments\u002F\u003Cenvironment-id>\u002Fconnections` → **+ New connection** → search for \"Work IQ Copilot MCP\" → Create, then re-run `list-connections`.\n\n#### Older CLIs: Add the Data Source\n\nOnce the connection exists, add it to the code app (this is what generates the typed service + model):\n\n```bash\npa app add data-source --connector shared_a365copilotchatmcp -c \u003Cconnection-id>\n```\n\nThis is a **non-tabular** connector — only `--connector` (api id) and `-c` (connection id) are needed.\n\n### Step 3: Inspect Generated Service\n\nAfter adding the connector, confirm the generated service is present. This is a small, single-operation service, so you can read it directly or grep it:\n\n```\nGrep pattern=\"async \\w+\" path=\"src\u002Fgenerated\u002Fservices\u002FWorkIQCopilotMCPService.ts\"\n```\n\nThe `WorkIQCopilotMCPService` exposes exactly one operation — **`mcp_m365copilot`** (\"Work IQ Copilot (Preview)\"), plus a `Getmcp_m365copilot` GET variant used only for connection verification. Work IQ \u002F CopilotChat is driven through **`mcp_m365copilot`**.\n\nIts generated signature is:\n\n```typescript\npublic static async mcp_m365copilot(\n  Mcp_Session_Id?: string,\n  queryRequest?: QueryRequest\n): Promise\u003CIOperationResult\u003Cvoid>>\n```\n\n- First argument is the **MCP session id** (the connector's `Mcp-Session-Id` parameter). Leave it **`undefined`** — this server assigns\u002Fneeds no client session id, and sending one on `initialize` returns `-32001` (see below).\n- Second argument is the JSON-RPC body, typed as `QueryRequest` (`{ jsonrpc?, id?, method?, params?, result?, error? }`) — exported from `src\u002Fgenerated\u002Fmodels\u002FWorkIQCopilotMCPModel.ts`.\n- Return type is `IOperationResult\u003Cvoid>`; the actual JSON-RPC \u002F SSE body arrives in `result.data` at runtime.\n\n**Facts you can rely on (do not try to discover them at runtime):**\n\n- The tool name is **`CopilotChat`** (case-sensitive). Do not substitute `query`, `search`, or `find`.\n- The argument key is **`message`** — not `query`, `prompt`, or `question`.\n- **Do NOT send an `Mcp-Session-Id` on the `initialize` handshake.** This connector's server treats an incoming id as an existing-session lookup and returns `-32001 Session not found`. The server is **stateless-tolerant**: `initialize` and `tools\u002Fcall` both succeed with **no** session id, so the `McpSession` wrapper below tracks none by default.\n\n> **Session-id handling (verified during testing).** This connector's MCP server is **stateless-tolerant**. `initialize` with **no** `Mcp-Session-Id` returns `200` with server capabilities, and a subsequent `tools\u002Fcall` with **no** id returns the Copilot reply — no session id needs to be tracked or echoed. Do **not** generate a client id and send it on `initialize`: the server treats it as a lookup and returns `404 \u002F -32001 Session not found` (this was a real bug in an earlier version of this wrapper). Note that the code-apps data layer's `IOperationResult\u003CTResponse>` exposes only `{ success, data, error, skipToken, count, fileName }` — it does **not** surface response headers — so if a future MCP server returns a session id only in the `Mcp-Session-Id` **response header**, it would be unreadable here. The wrapper still defensively adopts a server id if one ever appears inside `result.data`.\n\n### Step 4: Create McpSession Wrapper\n\n⚠️ **CRITICAL:** MCP session handling and response parsing are intricate. Copy the production-ready `McpSession` class below **exactly**. It runs the `initialize` handshake (sending **no** session id), sequences JSON-RPC ids, auto-retries on \"Session not found\", persists the conversation id, and parses the deeply nested response.\n\nCreate `src\u002Fconnectors\u002FmcpClient.ts`:\n\n```typescript\n\u002F\u002F src\u002Fconnectors\u002FmcpClient.ts\nimport type { IOperationResult } from '@microsoft\u002Fpower-apps\u002Fdata'\nimport { WorkIQCopilotMCPService } from '..\u002Fgenerated\u002Fservices\u002FWorkIQCopilotMCPService'\nimport type { QueryRequest } from '..\u002Fgenerated\u002Fmodels\u002FWorkIQCopilotMCPModel'\n\nexport interface JsonRpcRequest {\n  jsonrpc: '2.0'\n  id?: string\n  method: string\n  params?: Record\u003Cstring, unknown>\n}\n\nexport interface JsonRpcResponse {\n  jsonrpc?: string\n  id?: string\n  result?: Record\u003Cstring, unknown>\n  error?: { code?: number; message?: string; data?: unknown }\n}\n\ntype CopilotConversationMessage = {\n  text?: string\n  attributions?: Array\u003C{\n    attributionType?: string\n    providerDisplayName?: string\n    seeMoreWebUrl?: string\n  }>\n}\n\ntype CopilotConversation = {\n  messages?: CopilotConversationMessage[]\n}\n\nfunction parseRpc(result: IOperationResult\u003Cunknown>): JsonRpcResponse {\n  if (!result.success && result.error) {\n    return { error: { message: result.error.message } }\n  }\n\n  const data: unknown = result.data\n  if (data == null) return {}\n  if (typeof data === 'object') return data as JsonRpcResponse\n  if (typeof data === 'string') {\n    \u002F\u002F Handle SSE framing: \"event: message\\ndata: {JSON}\"\n    const dataLines = data\n      .split(\u002F\\r?\\n\u002F)\n      .filter((line) => line.startsWith('data:'))\n      .map((line) => line.slice(5).trim())\n    \u002F\u002F Per the SSE spec, multiple `data:` lines are joined with newlines — a single\n    \u002F\u002F JSON object can be split across lines, so joining with '' would corrupt it.\n    const payload = dataLines.length ? dataLines.join('\\n') : data\n    try {\n      return JSON.parse(payload) as JsonRpcResponse\n    } catch {\n      return { result: { raw: data } }\n    }\n  }\n\n  return { result: { raw: data } }\n}\n\nexport class McpSession {\n  private nextId = 1\n  \u002F\u002F MCP Streamable HTTP: the client must NOT send a session id on `initialize` —\n  \u002F\u002F the server assigns one. Sending a client-generated id makes this connector's\n  \u002F\u002F server return `404 \u002F -32001 Session not found`. This server is stateless-\n  \u002F\u002F tolerant, so we send no id at all; `extractSessionId` still adopts a server\n  \u002F\u002F id if one ever surfaces in the response body.\n  private sessionId: string | undefined = undefined\n  private conversationId: string | undefined\n  private initialized = false\n\n  private extractSessionId(raw: IOperationResult\u003Cunknown>): string | undefined {\n    const container = raw as unknown as Record\u003Cstring, unknown>\n    const dataObj =\n      raw.data && typeof raw.data === 'object'\n        ? (raw.data as Record\u003Cstring, unknown>)\n        : undefined\n    const resultObj =\n      dataObj?.result && typeof dataObj.result === 'object'\n        ? (dataObj.result as Record\u003Cstring, unknown>)\n        : undefined\n\n    const candidates: Array\u003Cunknown> = [\n      dataObj?.['Mcp-Session-Id'],\n      dataObj?.mcpSessionId,\n      dataObj?.sessionId,\n      resultObj?.['Mcp-Session-Id'],\n      resultObj?.mcpSessionId,\n      resultObj?.sessionId,\n      container['Mcp-Session-Id'],\n      container.mcpSessionId,\n      container.sessionId,\n    ]\n\n    const found = candidates.find((value) => typeof value === 'string' && value.length > 0)\n    return typeof found === 'string' ? found : undefined\n  }\n\n  private isSessionNotFound(res: JsonRpcResponse): boolean {\n    const message = (res.error?.message ?? '').toLowerCase()\n    return message.includes('session not found') || res.error?.code === -32001\n  }\n\n  private resetSession(): void {\n    \u002F\u002F Drop any session id and re-handshake from scratch (no id on `initialize`).\n    this.sessionId = undefined\n    this.initialized = false\n  }\n\n  private async send(\n    method: string,\n    params?: Record\u003Cstring, unknown>,\n    allowRetry = true\n  ): Promise\u003CJsonRpcResponse> {\n    const req: JsonRpcRequest = { jsonrpc: '2.0', id: String(this.nextId++), method, params }\n\n    \u002F\u002F Send no session id on `initialize` (server treats any id as existing-session lookup).\n    const sessionId = method === 'initialize' ? undefined : this.sessionId\n    const raw = (await WorkIQCopilotMCPService.mcp_m365copilot(\n      sessionId,\n      req as unknown as QueryRequest\n    )) as unknown as IOperationResult\u003Cunknown>\n\n    const negotiatedSessionId = this.extractSessionId(raw)\n    if (negotiatedSessionId) {\n      this.sessionId = negotiatedSessionId\n    }\n\n    const parsed = parseRpc(raw)\n\n    if (allowRetry && method !== 'initialize' && this.isSessionNotFound(parsed)) {\n      this.resetSession()\n      await this.initialize()\n      return this.send(method, params, false)\n    }\n\n    return parsed\n  }\n\n  async initialize(): Promise\u003CJsonRpcResponse> {\n    const res = await this.send('initialize', {\n      protocolVersion: '2025-06-18',\n      capabilities: {},\n      clientInfo: { name: 'Power Apps Code App', version: '1.0.0' },\n    })\n    \u002F\u002F Fail fast: surface a failed handshake instead of continuing to `tools\u002Fcall`.\n    if (res.error) {\n      throw new Error(`MCP initialize failed: ${res.error.message ?? JSON.stringify(res.error)}`)\n    }\n    this.initialized = true\n    return res\n  }\n\n  \u002F** Discover the available MCP tools (optional; the tool name is fixed as `CopilotChat`). *\u002F\n  async listTools(): Promise\u003CJsonRpcResponse> {\n    if (!this.initialized) await this.initialize()\n    return this.send('tools\u002Flist', {})\n  }\n\n  async callCopilotChat(message: string): Promise\u003C{ text: string; conversationId?: string }> {\n    if (!this.initialized) await this.initialize()\n    const raw = await this.send('tools\u002Fcall', {\n      name: 'CopilotChat',\n      arguments: {\n        message,\n        ...(this.conversationId ? { conversationId: this.conversationId } : {}),\n      },\n    })\n\n    \u002F\u002F Surface MCP\u002Fconnector errors as thrown exceptions so callers can `try\u002Fcatch`\n    \u002F\u002F instead of string-matching the returned text.\n    if (raw.error) {\n      throw new Error(raw.error.message ?? JSON.stringify(raw.error))\n    }\n\n    const parsed = extractCopilotText(raw)\n    if (parsed.conversationId) {\n      this.conversationId = parsed.conversationId\n    }\n\n    return { text: parsed.text, conversationId: parsed.conversationId }\n  }\n}\n\nfunction extractContentText(res: JsonRpcResponse): string | undefined {\n  const content = res.result?.content as Array\u003C{ type?: string; text?: string }> | undefined\n  if (!Array.isArray(content)) {\n    return undefined\n  }\n\n  const textBlocks = content\n    .filter((c) => c.type === 'text' && typeof c.text === 'string')\n    .map((c) => c.text!.trim())\n    .filter((value) => value.length > 0)\n\n  if (textBlocks.length === 0) {\n    return undefined\n  }\n\n  \u002F\u002F Prefer the JSON payload block. Some responses append metadata text blocks\n  \u002F\u002F such as \"CorrelationId: ...\" that should not be concatenated.\n  const jsonBlock = textBlocks.find(\n    (block) => block.startsWith('{') && \u002F\"conversationId\"|\"rawResponse\"|\"reply\"\u002F.test(block)\n  )\n  if (jsonBlock) {\n    return jsonBlock\n  }\n\n  const nonMetadata = textBlocks.find((block) => !\u002F^CorrelationId\\s*:\u002Fi.test(block))\n  return nonMetadata ?? textBlocks[0]\n}\n\nexport function extractCopilotText(res: JsonRpcResponse): {\n  text: string\n  conversationId?: string\n} {\n  const rawText = extractContentText(res)\n  if (!rawText) {\n    return { text: res.result ? JSON.stringify(res.result, null, 2) : '(no content returned)' }\n  }\n\n  try {\n    const inner = JSON.parse(rawText) as {\n      conversationId?: string\n      reply?: string\n      message?: string\n      rawResponse?: string\n    }\n\n    if (typeof inner.rawResponse === 'string') {\n      try {\n        const convo = JSON.parse(inner.rawResponse) as CopilotConversation\n        const messages = Array.isArray(convo.messages) ? convo.messages : []\n        \u002F\u002F messages[0] echoes the user query; the AI reply is the one carrying\n        \u002F\u002F attributions (citations). Fall back to index 1, then the last message.\n        const attributed = messages.find(\n          (m) => Array.isArray(m.attributions) && m.attributions.length > 0\n        )\n        const selected = attributed ?? messages[1] ?? messages[messages.length - 1]\n        const replyText = selected?.text?.trim()\n        if (replyText) {\n          return { text: replyText, conversationId: inner.conversationId }\n        }\n      } catch {\n        \u002F\u002F Fall through to simple reply extraction.\n      }\n    }\n\n    const fallbackText = inner.reply?.trim() || inner.message?.trim() || rawText\n    return { text: fallbackText, conversationId: inner.conversationId }\n  } catch {\n    return { text: rawText }\n  }\n}\n```\n\n> **Session-id note (verified during testing).** `McpSession` starts with **no** session id and sends none on the `initialize` handshake. Testing against `shared_a365copilotchatmcp` (server `Microsoft.MCPPlatform.WebApi`) confirmed it is **stateless-tolerant**: `initialize` with no id returns `200` + capabilities, and `tools\u002Fcall` with no id returns the Copilot reply. Sending a client-generated id on `initialize` instead makes the server return `404 \u002F -32001 Session not found` — that was the original bug. `IOperationResult` exposes only `{ success, data, error, skipToken, count, fileName }` (no response headers), so a header-only session id would be unreadable here; `extractSessionId` still adopts a server id if one ever appears inside `result.data`, and the handshake auto-retries on `Session not found` for resilience.\n>\n> If you ever bind a *different* MCP connector that is genuinely stateful and returns its session id only in the `Mcp-Session-Id` response header, this SDK cannot read it — capture one raw `mcp_m365copilot` result in the debugger to confirm where the id surfaces, and if it appears inside `result.data`, add that path to `extractSessionId`.\n\n### Step 5: Use Work IQ\n\nInitialize **once per app** (e.g., in a React `useEffect` on boot or a module singleton) and reuse for all Work IQ calls:\n\n```typescript\nimport { McpSession } from '.\u002Fconnectors\u002FmcpClient'\n\n\u002F\u002F Initialize once per app session and reuse across calls.\nconst workIqSession = new McpSession()\n\nexport async function queryWorkIQ(userPrompt: string): Promise\u003Cstring> {\n  try {\n    const { text } = await workIqSession.callCopilotChat(userPrompt)\n    return text\n  } catch (error) {\n    const msg = error instanceof Error ? error.message : 'Work IQ query failed'\n    console.error('Work IQ Error:', msg)\n    throw error\n  }\n}\n```\n\n**Key patterns:**\n\n- ✅ Initialize once, reuse across multiple calls (never `new McpSession()` per request)\n- ✅ Pass context-specific prompts to `callCopilotChat()`\n- ✅ The session auto-reinitializes if a \"Session not found\" error occurs\n- ✅ `conversationId` is automatically persisted across calls for multi-turn chats\n\n#### Prompt Structure\n\nWork IQ responds well to **context-rich, structured prompts**. Adapt this pattern for your scenario:\n\n```typescript\nconst prompt = `\nYou are [role\u002Fexpert description].\n\n**Context:**\n- [Relevant data or background information]\n- [Additional context as needed]\n\n**Task:** [Clear, specific instruction]\n\n**Format:**\n- Use markdown with clear section headings (## Summary, ## Action Items, etc.)\n- Specify limits (word count, number of items, etc.)\n`.trim()\n\nconst { text } = await workIqSession.callCopilotChat(prompt)\n```\n\nAdaptable scenarios: meeting summaries with action items, prioritized daily action items from email, project risk analysis from documents, team performance insights, or any knowledge-grounded analysis over M365 data.\n\n#### Response Parsing\n\n`callCopilotChat()` already unwraps the nested JSON-RPC \u002F SSE response and returns clean `text`. Parse that text according to the format you requested.\n\n**For structured markdown output** (when you asked for `## sections`):\n\n```typescript\nfunction extractSection(text: string, sectionName: string): string[] {\n  const regex = new RegExp(`##\\\\s*${sectionName}\\\\s*([\\\\s\\\\S]*?)(?=##|$)`)\n  const match = text.match(regex)\n  if (!match) return []\n\n  return match[1]\n    .split('\\n')\n    .filter((line) => line.trim().startsWith('-'))\n    .map((line) => line.replace(\u002F^-\\s*\u002F, '').trim())\n    .filter(Boolean)\n}\n\nconst { text } = await workIqSession.callCopilotChat(prompt)\nconst summary = extractSection(text, 'Summary')\nconst actionItems = extractSection(text, 'Action Items')\n```\n\n**For unstructured output** — use `text` directly (display as-is or format for your UI).\n\n#### Why the McpSession Pattern Is Required\n\nWork IQ uses **MCP (Model Context Protocol)**. Driving it correctly requires:\n\n1. **Session initialization** before the first call (handshake to exchange capabilities)\n2. **Session handling** — this connector is **stateless-tolerant**, so the wrapper sends **no** session id (sending one on `initialize` triggers `-32001 Session not found`); it defensively adopts a server id only if one ever surfaces in the response body (see the session-id note above)\n3. **JSON-RPC id sequencing** (each request needs a unique incrementing id)\n4. **Multi-turn conversation support** via conversation-id persistence\n5. **Nested response parsing** (JSON-RPC → text content → inner JSON → Graph conversation)\n6. **Automatic recovery** on session timeouts (`-32001` \u002F \"Session not found\")\n\n`McpSession` handles all of this. Bypassing it (ad-hoc per-call ids or direct calls without the handshake) leads to \"Session not found\" errors and failed integrations.\n\n### Step 6: Build\n\n```bash\nnpm run build\n```\n\nFix TypeScript errors before proceeding. Do NOT deploy yet.\n\n### Step 7: Update Memory Bank\n\nUpdate `memory-bank.md` with: connector added (`shared_a365copilotchatmcp`), McpSession wrapper created at `src\u002Fconnectors\u002FmcpClient.ts`, Work IQ usage wired up, build status.\n\n**IMPORTANT — Do NOT save sensitive information:**\n\n- ❌ OAuth URLs or consent links\n- ❌ Connection IDs\n- ❌ Session IDs or tokens\n- ❌ Environment IDs\n- ❌ Any authentication credentials\n\nOnly save high-level progress like \"Work IQ Copilot MCP connector configured\" or \"Work IQ CopilotChat integration implemented via McpSession\".\n",{"name":5,"model":49,"description":7,"allowed-tools":50,"user-invocable":51},"sonnet","Read, Edit, Write, Grep, Glob, Bash, LSP, TaskCreate, TaskUpdate, TaskList, TaskGet, AskUserQuestion, Skill",true,"main","9d26fde082b47f04e9bb97cb30a46dd1eaaa776e","plugins\u002Fcode-apps\u002Fskills\u002Fadd-workiq",230,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fpower-platform-skills","https:\u002F\u002Fmicrosoft.github.io\u002Fpower-platform-skills\u002F","https:\u002F\u002Fgithub.com\u002Fmicrosoft","https:\u002F\u002Fopensource.microsoft.com","Open source projects and samples from Microsoft","2026-11-14 02:26:14",{"source":8,"skillName":5,"commands":63,"prompt":73,"zipAvailable":51},[64,67,70],{"tool":65,"command":66},"npx","npx skills add microsoft\u002Fpower-platform-skills --skill add-workiq",{"tool":68,"command":69},"bunx","bunx skills add microsoft\u002Fpower-platform-skills --skill add-workiq",{"tool":71,"command":72},"pnpm","pnpm dlx skills add microsoft\u002Fpower-platform-skills --skill add-workiq","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fpower-platform-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fcode-apps\u002Fskills\u002Fadd-workiq\u002FSKILL.md",[],[76,96,119,137,151,161],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":44},"01M699WVHX0XN59EPBTTPEKYPG","setup","Use when Process Intelligence needs building, explicit cloud\u002Faccount\u002Fenvironment configuration, sign-in, connection diagnostics, or recovery from an authentication error.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fpower-platform-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fprocess-intelligence\u002Fskills\u002Fsetup\u002FSKILL.md",[],[78,83,29,84,85,86,87,88,89,90,91,92,93,94,95,28],"read","connection","error","sign","intelligence","configuration","use","process","diagnostics","environment","authentication","cloud","recovery",{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":107,"publishedAt":44},"01M699WSR9EX55YY1WD9J22FEG","report-issue","Use when the user wants a Process Intelligence bug-report draft or support summary for a failed operation.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fpower-platform-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fprocess-intelligence\u002Fskills\u002Freport-issue\u002FSKILL.md",[102],{"categoryNo":103,"categoryName":104,"taxonomyType":105,"taxonomyTypeDesc":106},"01JBSEEDCAT000000000000034","行政与办公人员","PROFESSION","适用职业",[108,109,110,111,112,90,89,113,114,87,115,116,117,29,118],"report issue","report","issue","support","user","bug","summary","draft","operation","for","bug-report",{"skillNo":120,"name":121,"nameZh":6,"description":122,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":123,"categories":124,"keywords":125,"publishedAt":44},"01M699WR26YQ9Q21KE6MJF5B2G","investigate-process","Use when a broad Process Mining business question, observed pattern or competing explanation needs investigation across analytical perspectives.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fpower-platform-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fprocess-intelligence\u002Fskills\u002Finvestigate-process\u002FSKILL.md",[],[90,126,127,128,29,129,130,131,132,83,133,89,134,135,136],"investigate","investigate process","mining","process mining","investigation","perspectives","question","business","pattern","across","analytical",{"skillNo":138,"name":139,"nameZh":6,"description":140,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":141,"categories":142,"keywords":143,"publishedAt":44},"01M699WP9SDG5ZR12P8VYNXKTN","derive-metric","Use when a requested measure is missing, a saved custom metric needs reuse, or an ephemeral formula or derived scalar is needed.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fpower-platform-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fprocess-intelligence\u002Fskills\u002Fderive-metric\u002FSKILL.md",[],[144,145,83,89,146,147,148,149,150,29],"metric","derive metric","formula","missing","reuse","saved","custom",{"skillNo":152,"name":153,"nameZh":6,"description":154,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":155,"categories":156,"keywords":157,"publishedAt":44},"01M699WMG5R8P6SMTDAS1TKF9E","compare-cohorts","Use when comparing process cohorts, departments, periods or before-and-after results under matched definitions.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fpower-platform-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fprocess-intelligence\u002Fskills\u002Fcompare-cohorts\u002FSKILL.md",[],[158,159,29,89,90,160,83],"compare","compare cohorts","results",{"skillNo":162,"name":163,"nameZh":6,"description":164,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":165,"categories":166,"keywords":167,"publishedAt":44},"01M699WJWNVTMP9XK3NCJHV14D","analyze-variants","Use when investigating common or slow variants, repeated work, unusual paths, or a specific Process Mining case.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fpower-platform-skills\u002Fblob\u002Fmain\u002Fplugins\u002Fprocess-intelligence\u002Fskills\u002Fanalyze-variants\u002FSKILL.md",[],[168,169,170,129,29,128,171,172,89,90,83,173,174],"analyze","variants","analyze variants","case","paths","work","common"]