> ## 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.

# MCP Usage Guide

> Version: 1.2.0 Last Updated: 2026-04-08 Purpose: Guide for using MCP (Model Context Protocol) servers in this project

**Version:** 1.2.0\
**Last Updated:** 2026-04-08\
**Purpose:** Guide for using MCP (Model Context Protocol) servers in this project

> **See:** Root `AGENTS.md` for quick reference (current version: [docs/VERSIONS.md](../VERSIONS.md)).

***

## Cursor MCP Governance (Local + Cloud)

### Security Baseline (REQUIRED)

* Never commit plaintext secrets in MCP configs.
* Use environment interpolation for credentials (for example: `${env:STITCH_API_KEY}`).
* Prefer `.cursor/mcp.json.example` as the shared template and keep machine/user secrets out of source control.
* Treat MCP allowlists as convenience, not a security boundary; still enforce command and data review discipline.

### Approved Repo MCP Servers

Current repo-level MCP servers in `.cursor/mcp.json`:

* `shadcn` - UI component and pattern tooling
* `fallow` - dead-code, duplication, and complexity analysis
* `stitch` - Google-hosted MCP endpoint (requires `STITCH_API_KEY`)

### Cloud Compatibility Notes

* Cloud agents run in isolated Linux environments; avoid shell-specific assumptions in MCP setup scripts.
* HTTP and stdio MCP servers are preferred for cloud portability.
* Keep required env vars documented alongside cloud setup docs so cloud runs are reproducible.

***

## Supabase MCP Usage (REQUIRED)

> **Purpose:** AI agents MUST use Supabase MCP for read operations and documentation lookup. Use Supabase CLI for write operations (migrations, deployments).

### When to Use Supabase MCP

**ALWAYS use Supabase MCP for:**

* ✅ **Reading project information** (project URL, branch list, project details)
* ✅ **Searching Supabase documentation** (RLS policies, branching, migrations)
* ✅ **Querying branch information** (list branches, get branch details)
* ✅ **Looking up API patterns** (best practices, examples)
* ✅ **Understanding Supabase features** (branching, migrations, RLS)

**DO NOT use Supabase MCP for:**

* ❌ Creating migrations (use CLI: `npx supabase migration new` or `supabase migration new`)
* ❌ Deploying migrations (use CLI: `npx supabase db push` or `supabase db push`)
* ❌ Generating types (use CLI: `npx supabase gen types typescript` or `supabase gen types typescript`)
* ❌ Local development (use CLI: `npx supabase start` or `supabase start`)

### When to Use Supabase CLI

**ALWAYS use Supabase CLI for:**

* ✅ **Creating migration files** (`npx supabase migration new` or `supabase migration new`)
* ✅ **Applying migrations** (`npx supabase db push`, `supabase migration up`)
* ✅ **Local development** (`npx supabase start`, `npx supabase db reset`, or `supabase start` / `supabase db reset` if on PATH)
* ✅ **Generating TypeScript types** (`npx supabase gen types typescript` or `supabase gen types typescript`)
* ✅ **Linking projects** (`npx supabase link --project-ref` or `supabase link`)
* ✅ **Managing branches** (`npx supabase --experimental branches create` or `supabase branches create`)

**Canonical CLI workflow:** See [SUPABASE\_CLI\_LOCAL\_WORKFLOW.md](./supabase/SUPABASE_CLI_LOCAL_WORKFLOW.md) for when/how to use the CLI, install/verify steps, and agent rules. **For AI agents:** If you suggest `supabase start` or `supabase db reset`, remind the user the Supabase CLI must be installed and on PATH; if the user does not have the CLI on PATH, they can run `npx supabase start` and `npx supabase db reset` from the project root instead of installing globally.

### Testing migrations locally (before committing)

**Prerequisite:** Supabase CLI available (install and add to PATH, or use `npx supabase` from project root). The CLI is not bundled with the repo.

**Before committing new or changed migrations:**

1. **Start local stack** (if not running): `npx supabase start` (or `supabase start` if CLI on PATH)
2. **Apply all migrations to local DB:** `npx supabase db reset` (or `supabase db reset` if on PATH; or `supabase migration up` for pending only)
3. **Run project validation:** `validate-migration --latest` (or `npx ts-node scripts/database/validate-migration.ts --latest`)
4. **Run RLS tests as needed:** `npm run test:rls` (or Cursor command `test-rls`)
5. **Then commit and push.** Use `npx supabase db push` (or `supabase db push`) only when targeting a linked remote (staging/production).

**See:** [SUPABASE\_CLI\_LOCAL\_WORKFLOW.md](./supabase/SUPABASE_CLI_LOCAL_WORKFLOW.md) (full workflow) and [Troubleshooting Guide](./TROUBLESHOOTING_GUIDE.md#supabase-remote-migration-versions-not-found) if you see "Remote migration versions not found in local migrations directory" when pushing to a remote.

### Supabase MCP / CLI Operation Matrix

| Operation                                          | Preferred Tool           | Why                                                  |
| -------------------------------------------------- | ------------------------ | ---------------------------------------------------- |
| Get project metadata, branches, tables, migrations | Supabase MCP             | Fast read-only discovery in agent workflows          |
| Search Supabase docs / patterns                    | Supabase MCP             | Version-aware retrieval without context switching    |
| Create/apply migrations and schema diffs           | Supabase CLI             | Required write path and canonical migration workflow |
| Local stack lifecycle (`start`, `stop`, `reset`)   | Supabase CLI             | MCP does not manage local runtime                    |
| Edge function deploy/serve                         | Supabase CLI             | Deployment and local serve are CLI-native            |
| Type generation                                    | Supabase CLI (preferred) | Better reliability and error output than MCP         |

### Supabase MCP Read Operations

Use Supabase MCP for read/discovery tasks such as:

* Listing projects/branches and checking branch state
* Listing tables, migrations, extensions, advisors, and logs
* Retrieving edge function metadata/code for review
* Searching docs for RLS, branching, migration, and API patterns

### Common Supabase Workflow

1. Use **MCP** to discover current state and docs patterns.
2. Use **CLI** to create/apply migrations and deploy execution changes.
3. Use **MCP** again to verify resulting project state and advisor outputs.

### Branching Workflow

**Persistent Branches:**

* Map to Git branches (e.g., `staging` branch → `staging` Git branch)
* Automatically sync migrations via GitHub integration
* Use for long-lived environments (staging, production)

**Preview Branches:**

* Created automatically for PRs (if GitHub integration enabled)
* Short-lived, deleted after PR merge
* Use for testing feature migrations

**Branch Naming Convention:**

* `main` → Production Supabase project
* `staging` → Staging persistent branch
* `develop` → Development persistent branch (optional)
* Feature branches → Preview branches (auto-created)

**GitHub Integration:**

* Enable in Supabase Dashboard → Settings → Integrations → GitHub
* Maps Git branches to Supabase branches/projects
* Automatic migration deployment on push
* Preview branches created for PRs

### Data Isolation & Key Configuration (CRITICAL)

**Understanding Supabase Branching:**

| Aspect      | Behavior                  | Notes                                      |
| ----------- | ------------------------- | ------------------------------------------ |
| Project URL | **Same for all branches** | `https://zkgxozahyczcnzpwhbbf.supabase.co` |
| Anon Keys   | **Different per branch**  | Critical for isolation                     |
| Data        | **Completely isolated**   | Branch data never transfers                |
| Migrations  | **Merge on PR merge**     | Schema changes propagate                   |
| Seed Data   | **Branch-specific**       | Only runs when branch created              |

**Key Points:**

* ✅ **Same Supabase URL** for staging and production is CORRECT (using branching, not separate projects)
* ✅ **Different anon keys** per branch is REQUIRED (verify in dashboard)
* ✅ **Data stays isolated** - seed data in staging never appears in production
* ✅ **Only migrations merge** when PR is merged to main

**Pre-Migration Verification:**

* See `docs/testing/PRE_MIGRATION_TEST_PLAN.md` for migration test cases
* See `docs/testing/PRE_MIGRATION_CHECKLIST.md` for dashboard verification steps

**See:** `docs/migration/COMPLETION_PLAN.md` for complete branching setup guide and `docs/integrations/SUPABASE_SETUP.md` for branching configuration.

***

## Fallow MCP Usage (OPTIONAL — Codebase Analysis)

> **Purpose:** Fallow MCP exposes structured codebase analysis (dead code, duplication, complexity, boundaries) without manually parsing CLI output.
>
> **Config file:** `.cursor/mcp.json` — the `fallow` server is already configured. Restart Cursor after any MCP config change.

### Tools Available

| Tool           | Description                                                                         | When to Use                                               |
| -------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------- |
| `analyze`      | Dead-code analysis (unused files/exports/dependencies, cycles, boundary violations) | Before proposing deletions, especially in large refactors |
| `find_dupes`   | Duplication analysis                                                                | Detect repeated logic before consolidation/refactors      |
| `check_health` | Complexity and maintainability hotspots                                             | Prioritize refactor targets                               |
| `audit`        | Changed-files quality gate with verdict                                             | PR/branch validation                                      |
| `project_info` | Entry points/plugins/files metadata                                                 | Validate configuration and graph roots                    |

### When to Use Fallow MCP

**Use Fallow MCP when:**

* ✅ Running the dead-code-auditor agent to identify orphans and unused exports
* ✅ Proposing file deletions — run analysis first to confirm the file is genuinely unused
* ✅ Reviewing a module for cleanup (replaces manual graph inspection)
* ✅ Checking complexity and duplication before or after refactors

**Use CLI directly when:**

* ✅ Running in CI: `npm run check:dead-code:ci`
* ✅ Generating full dead-code audits: `npm run audit:unused-files`
* ✅ Running local checks: `npm run check:dead-code`, `npm run check:dupes`, `npm run check:health`

### Current Project Configuration

Fallow is configured in [`.fallowrc.json`](../../.fallowrc.json):

* **Entry points:** `src/routes/**/*.tsx`, `supabase/functions/*/index.ts`, `scripts/**/*.ts`
* **Ignored files:** Barrel indexes (`src/cores/*/index.ts`, `src/platform/**/index.ts`), docs workspace, test fixtures, `supabase/functions/_shared`
* **Architecture boundaries:** Zones for `platform`, `cores`, `shared`, and `routes`

### CI Behavior

The dead-code check is currently **informational** (step still runs with `continue-on-error`). Tighten the gate after baseline cleanup if the team wants dead-code findings to block builds.

### Related Commands and Agents

| Resource  | Path                                                    | Purpose                              |
| --------- | ------------------------------------------------------- | ------------------------------------ |
| Agent     | `.cursor/agents/dead-code-auditor.md`                   | Full dead-code audit workflow        |
| Skill     | `.cursor/skills/dead-code-audit/SKILL.md`               | Step-by-step dead-code removal guide |
| Command   | `.cursor/commands/development/check-dead-code.md`       | `check-dead-code` command definition |
| Command   | `.cursor/commands/development/review-module-orphans.md` | Per-module orphan review             |
| Quick ref | `.cursor/rules/quick-reference.mdc`                     | "Find dead code" row                 |

***

## Context7 MCP Usage (REQUIRED)

> **Purpose:** AI agents MUST use the Context7 MCP server to fetch up-to-date library documentation instead of relying on potentially outdated training data. This ensures accurate API usage for all project dependencies.
>
> **Reference:** See [Context7 Documentation](https://context7.com/docs) and [Context7 Tips](https://context7.com/docs/tips) for best practices.

### When to Use Context7

**ALWAYS use Context7 when:**

* ✅ Working with **any project dependency** (React, Supabase, TanStack Query, etc.)
* ✅ Implementing features using **third-party library APIs**
* ✅ Debugging issues related to **library behavior**
* ✅ Unsure about **correct API usage, parameters, or return types**
* ✅ Library version matters (this project uses **specific versions** - see `package.json`)

**DO NOT rely on training data for:**

* ❌ Library APIs that may have changed between versions
* ❌ Deprecated methods or patterns
* ❌ New features in recent library releases

### Project Dependencies (Use Context7 For)

The following key libraries are used in this project. **Always fetch Context7 documentation** before using their APIs:

| Library                | Version       | Context7 Library ID    | Use For                             |
| ---------------------- | ------------- | ---------------------- | ----------------------------------- |
| React                  | 18.3.1        | `react`                | Hooks, components, patterns         |
| React Router DOM       | 6.30.3        | `react-router`         | Routing, navigation, loaders        |
| TanStack React Query   | 5.90.15       | `tanstack-query`       | Data fetching, caching, mutations   |
| TanStack Query Persist | 5.90.22       | `tanstack-query`       | Offline query persistence           |
| Supabase JS            | 2.89.0        | `supabase`             | Database, auth, storage, realtime   |
| React Hook Form        | 7.69.0        | `react-hook-form`      | Form handling, validation           |
| Zod                    | 4.2.1         | `zod`                  | Schema validation                   |
| zod-to-json-schema     | 3.25.1        | `zod-to-json-schema`   | Form schema export/interoperability |
| date-fns               | 3.6.0         | `date-fns`             | Date manipulation                   |
| date-fns-tz            | 3.2.0         | `date-fns-tz`          | Timezone-aware date formatting      |
| @formkit/auto-animate  | 0.9.0         | `formkit-auto-animate` | List/form animations                |
| @tiptap/react          | 3.18.0        | `tiptap`               | Rich text editor                    |
| mathjs                 | 15.1.0        | `mathjs`               | Safe expression evaluation          |
| xstate                 | 5.26.0        | `xstate`               | Workflow state machines             |
| @xstate/react          | 6.0.0         | `xstate`               | XState React integration            |
| rrweb                  | 2.0.0-alpha.4 | `rrweb`                | Session recording/replay            |
| jspdf                  | 2.5.2         | `jspdf`                | PDF generation                      |
| html2canvas            | 1.4.1         | `html2canvas`          | HTML to canvas rendering            |
| @xyflow/react          | 12.10.0       | `xyflow`               | Workflow canvas/diagrams            |
| @dnd-kit               | 6.3.1         | `dnd-kit`              | Drag and drop                       |
| Radix UI               | Various       | `radix-ui`             | Accessible components               |
| Tailwind CSS           | 3.4.19        | `tailwindcss`          | Styling utilities                   |
| Vite                   | 7.3.0         | `vite`                 | Build tooling                       |
| Vitest                 | 4.0.16        | `vitest`               | Testing                             |
| Docusaurus             | 3.9.2         | `docusaurus`           | Documentation (packages/docs)       |

### Context7 Best Practices

**1. Resolve Library ID First:**

```
// Before fetching docs, resolve the library ID
// Use: resolve-library-id for "tanstack react query"
// Returns: /tanstack/query (use this for get-library-docs)
```

**2. Be Version-Specific:**

```
// ✅ CORRECT: Specify version when fetching docs
// get-library-docs for "@tanstack/react-query" version "5.x"

// ❌ WRONG: Generic queries without version context
// "How do I use React Query?" (may return outdated v3/v4 patterns)
```

**3. Use Focused Topics:**

```
// ✅ GOOD: Specific topic queries
"TanStack Query v5 useMutation with optimistic updates"
"Supabase JS v2 RLS policies with auth.uid()"
"React Router v6 data loaders and actions"

// ❌ AVOID: Overly broad queries
"How to use React Query" (too general)
```

**4. Verify Against Project Patterns:**
After fetching Context7 docs, cross-reference with project patterns:

* Check `AGENTS.md` for project-specific patterns (e.g., `staleTime`/`gcTime` requirements)
* Review existing code in `src/` for established conventions
* Ensure compatibility with project architecture

### Context7 Workflow

**Step 1: Identify the library** you need documentation for

**Step 2: Resolve the library ID** using Context7's resolve function

**Step 3: Fetch documentation** with specific topic focus and version

**Step 4: Cross-reference** with project patterns in this document

**Step 5: Implement** following both library best practices AND project conventions

### Example: TanStack Query Usage

```typescript theme={null}
// 1. Fetch Context7 docs for TanStack Query v5 useQuery
// 2. Context7 provides current API signature and options
// 3. Cross-reference with AGENTS.md QueryClient requirements
// 4. Result: Correct implementation with project patterns

const { data, error, isLoading } = useQuery({
  queryKey: ['hr-employees', organizationId],
  queryFn: async () => {
    const { data, error } = await supabase
      .from('hr_employees')
      .select('*')
      .eq('organization_id', organizationId);
    if (error) throw error;
    return data;
  },
  // From Context7: v5 uses 'gcTime' not 'cacheTime'
  // From AGENTS.md: REQUIRED values for this project
  staleTime: 5 * 60 * 1000,
  gcTime: 10 * 60 * 1000,
  enabled: !!organizationId,
});
```

### Anti-Patterns

* ❌ **Assuming API stability** - Always verify with Context7 for version-specific APIs
* ❌ **Using deprecated patterns** - Context7 shows current recommended patterns
* ❌ **Ignoring breaking changes** - v5 TanStack Query differs significantly from v4
* ❌ **Guessing parameter names** - Fetch docs to confirm exact API signatures

***

## See Also

* **Root AGENTS.md:** `AGENTS.md` (current: [docs/VERSIONS.md](../VERSIONS.md)) - Quick reference
* **Context7 Docs:** [https://context7.com/docs](https://context7.com/docs)
* **Supabase Branching:** `docs/migration/COMPLETION_PLAN.md`
* **Fallow Docs:** [https://docs.fallow.tools](https://docs.fallow.tools)
* **Fallow VS Code Extension:** [https://marketplace.visualstudio.com/items?itemName=fallow-rs.fallow-vscode](https://marketplace.visualstudio.com/items?itemName=fallow-rs.fallow-vscode)

***

**Last Updated:** 2026-03-05
