> ## Documentation Index
> Fetch the complete documentation index at: https://docs.encoreos.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Claude Agent SDK Integration – Integration Documentation

> Feature ID: PF-72 Version: 1.0 Last Updated: 2026-03-13 Status: ✅ Complete (Phases 1–4); Phase 4 (MCP) implemented per PF-72-PHASE-4-EXPANSION

**Feature ID:** PF-72\
**Version:** 1.0\
**Last Updated:** 2026-03-13\
**Status:** ✅ Complete (Phases 1–4); Phase 4 (MCP) implemented per [PF-72-PHASE-4-EXPANSION](../../../specs/pf/specs/PF-72-PHASE-4-EXPANSION.md)

***

## Overview

PF-72 (Claude Agent SDK Integration) adds skill-aware agent execution via a new edge function `ai-skill-execute` and migrates existing AI edge functions to use the SDK. All integration is **within Platform Foundation**; there are no cross-core dependencies.

***

## Integration Pattern

**Pattern Type:** Platform internal — consumes existing PF capabilities only.

PF-72 depends on:

| Dependency               | Spec  | Usage                                                                                                                          |
| ------------------------ | ----- | ------------------------------------------------------------------------------------------------------------------------------ |
| Platform AI base         | PF-27 | PHI detection, usage logging (`pf_ai_usage_logs`), module context                                                              |
| AI Provider (OpenRouter) | PF-59 | Model routing, error handling, fallback when SDK unavailable                                                                   |
| AI Skills System         | PF-62 | Skill and override loading (`pf_ai_skills`, `pf_ai_skill_overrides`); category-based tool sets; `mergeSkillWithOverride` logic |
| RAG Infrastructure       | PF-60 | Semantic search for `search_documents` tool and skill `use_rag`                                                                |

***

## API Contract

**Consumer:** Frontend via `useAISkillChat` hook.

**Endpoint:** `POST /functions/v1/ai-skill-execute`

* **Request:** `skillCode`, `messages`, optional `stream`, optional `tools` (see spec `specs/pf/specs/PF-72-agent-sdk-integration.md` API Design).
* **Response:** `content`, `usage`, `model`, `sources?`, `structuredOutput?`, `schemaValidationFailed?`, `toolResults?` (see spec).

No events are published or consumed by PF-72.

***

## Quick Reference

| I need to…                           | Pattern                                                                                                 | Location                                                                             |
| ------------------------------------ | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Call skill-aware agent from frontend | Use `useAISkillChat` hook                                                                               | [Spec API Design](../../../specs/pf/specs/PF-72-agent-sdk-integration.md#api-design) |
| Invoke agent execution               | `POST /functions/v1/ai-skill-execute`                                                                   | [Spec API Design](../../../specs/pf/specs/PF-72-agent-sdk-integration.md#api-design) |
| Request fields                       | `skillCode`, `messages`, optional `stream`, optional `tools`                                            | Spec API Design                                                                      |
| Response fields                      | `content`, `usage`, `model`, `sources?`, `structuredOutput?`, `schemaValidationFailed?`, `toolResults?` | Spec API Design                                                                      |
| Dependencies                         | PF-27, PF-59, PF-62, PF-60                                                                              | Integration Pattern table above                                                      |
| Pattern type                         | Platform internal (skill-aware agent)                                                                   | Overview                                                                             |
| Configure MCP for a skill (Phase 4)  | Allowlist + skill-to-MCP mapping; no PHI to MCP                                                         | [MCP Integration (Phase 4)](#mcp-integration-phase-4)                                |

***

## MCP Integration (Phase 4)

> **Status:** ✅ Complete. Implemented per [PF-72-PHASE-4-EXPANSION](../../../specs/pf/specs/PF-72-PHASE-4-EXPANSION.md).

Phase 4 adds **Model Context Protocol (MCP)** server support so the agent can call external tools (e.g. Context7, Supabase MCP) in a governed way. All behavior is constrained by constitution §4.3 (AI calls through edge functions only; no PHI/PII to external services).

**MCP\_ENABLED=false by default — set MCP\_ENABLED=true only after MCP servers are configured and validated.**

### Allowlist

* Only **allowlisted** MCP servers may be invoked by `ai-skill-execute`.
* Allowlist is configured in edge function config or secrets (e.g. env or org-level config); no client-supplied MCP endpoints.
* At runtime, the edge function checks the skill’s requested MCP(s) against the allowlist before opening any MCP connection.

### Skill-to-MCP mapping

* A skill declares which MCP servers it needs (e.g. via `pf_ai_skills.custom_fields` such as `mcp_servers: string[]`, or dedicated columns if added later).
* `buildSkillAgent` (or equivalent) reads this mapping and passes only allowlisted MCP tools into the agent config.
* If a skill requests an MCP that is not allowlisted, that MCP is not attached; the agent runs with platform tools and other allowlisted MCPs only.

### Platform engineer guide: adding a new MCP

1. **Evaluate:** Confirm the MCP server is compatible with the Deno edge runtime or callable via HTTP from the edge (see expansion spec Phase 4.1).
2. **Security:** Ensure no PHI/PII is sent in MCP requests; sanitize tool results before including in agent context (constitution §4.3.2).
3. **Allowlist:** Add the MCP server identifier and connection params (e.g. URL, auth) to the allowlist used by `ai-skill-execute` (secrets/env or org config).
4. **Shared utility:** Use or extend `_shared/mcp-client.ts` (or equivalent) for connection and tool invocation; keep allowlist check in one place.
5. **Document:** Add the MCP to the integration doc (this section) and to any admin/API reference that describes available MCP tools.
6. **Governance:** Do not allow ad-hoc or client-supplied MCP endpoints; all MCPs must be pre-configured and allowlisted.

### References (Phase 4)

* **Expansion spec:** [PF-72-PHASE-4-EXPANSION](../../../specs/pf/specs/PF-72-PHASE-4-EXPANSION.md) — user stories, data model, implementation plan, rollback.
* **Constitution:** §4.3 — AI integration security; no PHI/PII to external AI or MCP.

***

## Code Examples

**Request: ai-skill-execute**

```json theme={null}
{
  "skillCode": "policy_writer",
  "messages": [{ "role": "user", "content": "Draft a privacy policy section for client data." }],
  "stream": false
}
```

**Response: ai-skill-execute**

```json theme={null}
{
  "content": "...",
  "usage": { "prompt_tokens": 120, "completion_tokens": 450, "total_tokens": 570 },
  "model": "anthropic/claude-3.5-sonnet",
  "sources": [],
  "structuredOutput": null,
  "schemaValidationFailed": false,
  "toolResults": []
}
```

When `schemaValidationFailed === true`, `structuredOutput` is absent; use `content` (e.g. Markdown fallback) and show a warning. When tools were invoked, `toolResults` contains `{ tool, result }` entries.

**Frontend: useAISkillChat and mergeSkillWithOverride**

The frontend calls `useAISkillChat(skillCode, …)`. When a skill is selected, the hook calls `ai-skill-execute` with that `skillCode` and `messages`. The edge function loads the skill and any org override, runs **mergeSkillWithOverride** (server-side), then executes via the SDK. The returned payload includes `content`, `usage`, `model`, and when applicable `sources`, `structuredOutput` (only if `schemaValidationFailed` is false), `schemaValidationFailed`, and `toolResults`. Merge affects which prompt, model, and tools are used; `toolResults` reflect the actual tool invocations during execution.

***

## Decision Tree

* **Should I use `ai-skill-execute` or `ai-assistant`?**
  → Use `ai-skill-execute` when a skill is selected (via `useAISkillChat`). Fall back to `ai-assistant` when no skill is active or when `ai-skill-execute` fails (e.g. skill not found, SDK error).

* **How does skill config get applied?**
  → Skill lookup from `pf_ai_skills` → load override from `pf_ai_skill_overrides` → **mergeSkillWithOverride** → SDK execution with effective prompt, model, and tools.

* **What if the SDK or provider fails?**
  → Provider fallback: retry with exponential backoff; if SDK unavailable, fall back to raw HTTP OpenRouter call per PF-59.

* **When are tools like `search_documents` used?**
  → Platform tools (e.g. `search_documents`, `lookup_data`, `validate_schema`) are invoked by the agent during execution when the skill enables tool use; results are returned in `toolResults`.

* **How are MCP servers used (Phase 4)?**
  → Only allowlisted MCPs; skills declare required MCPs via `custom_fields` (or schema). Edge function wires allowlisted MCP tools into the agent; no PHI/PII in MCP requests. See [MCP Integration (Phase 4)](#mcp-integration-phase-4).

***

## Pattern Library

| Pattern                                 | When to use                                                                                                                                                                                                                                                                                     | Tradeoffs                                                                                                                                                                                   |
| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Platform internal skill-aware agent** | AI must execute with skill-specific prompt, model, and tools (e.g. compliance policy writer, document search). Consumer calls `useAISkillChat`; edge function `ai-skill-execute` loads skill, runs **mergeSkillWithOverride**, executes via SDK, optionally runs tools like `search_documents`. | Centralizes skill execution in edge; avoids client-side skill application only. Requires PHI detection and usage logging before execution; fallback path when skill not found or SDK fails. |

***

## Common Mistakes

| Mistake                                       | Impact                                                                                       | Mitigation                                                                                                                           |
| --------------------------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| Ignoring `schemaValidationFailed` in response | Client may try to parse content as structured when it fell back to Markdown                  | Check `schemaValidationFailed === true` and show warning or retry; do not assume `structuredOutput` is present when this flag is set |
| Not handling `toolResults`                    | Tool invocations (e.g. `search_documents`) are invisible to UI; citations or actions missing | Read `toolResults` from response and surface sources or follow-up actions                                                            |
| Forgetting RAG fallback                       | When `use_rag=true` and PF-60 returns no sources, agent runs without RAG context             | Ensure skill still produces useful output when RAG returns empty; document expected behavior in spec                                 |
| Missing schema validation on request          | Invalid `tools` or `messages` shape causes runtime errors                                    | Validate request body (e.g. `skillCode` required, `messages` array) before calling `ai-skill-execute`                                |

***

## Deprecation (raw HTTP path)

The **raw HTTP OpenRouter path** used inside `ai-assistant` and `ai-document-analyze` (when SDK is unavailable or non-Anthropic model) is **deprecated**.

* **Sunset date:** 2026-05-24 — no new features should use this path.
* **Removal target:** 2026-08-22 (extensions require explicit justification).
* **Migration:** Call `ai-skill-execute` or use the SDK path; do not rely on the legacy HTTP path for new features.
* **Runtime:** When the deprecated path is invoked, both `ai-assistant` and `ai-document-analyze` emit a **structured warn-level log** with context: `{ model, reason, sunset, migration }`.
* **Implemented in:** PF-72 WS5 (2026-02-24). Both functions now try Anthropic REST API first for Anthropic models, falling back to OpenRouter with deprecation warnings.

***

## Pre-Flight Checklist

Before releasing or integrating with `ai-skill-execute`:

* [ ] **Spec conformance:** Implementation matches [specs/pf/specs/PF-72-agent-sdk-integration.md](../../../specs/pf/specs/PF-72-agent-sdk-integration.md) (API Design, FR/NFR).
* [ ] **Logging and usage capture:** All calls logged to `pf_ai_usage_logs` with `feature=skill_code`; token/cost/duration recorded.
* [ ] **PHI detection:** PHI detection runs before agent execution (PF-27 behavior preserved).
* [ ] **Model and tool fallback:** Fallback to `ai-assistant` when `ai-skill-execute` fails; provider fallback (raw HTTP) when SDK unavailable; `schemaValidationFailed` and `toolResults` handled in client.

***

## Integration Matrix

* **CROSS\_CORE\_INTEGRATIONS.md:** PF-72 is platform-internal only; row added under Platform Integration Layers for traceability.

***

## References

* **Spec:** [PF-72 Agent SDK Integration](../../../specs/pf/specs/PF-72-agent-sdk-integration.md)
* **Phase 4 expansion:** [PF-72-PHASE-4-EXPANSION](../../../specs/pf/specs/PF-72-PHASE-4-EXPANSION.md) (MCP Integration)
* **PF-27:** Platform AI — [Platform Integration Layers](./PLATFORM_INTEGRATION_LAYERS.md#pf-27-platform-ai-integration-layer)
* **PF-59:** AI Provider Migration (OpenRouter) — [PF-59](../../../specs/pf/specs/PF-59-ai-provider-migration.md)
* **PF-62:** AI Skills System — [PF-62 Spec](../../../specs/pf/specs/PF-62-ai-skills-system.md)
* **PF-60:** [PF-60 RAG Infrastructure](./rag-infrastructure-integration.md)
