# Preflight

> ✈️ 24-tool MCP server for Claude Code: preflight checks for your prompts, cross-service context, session history search with LanceDB vectors, correction pattern learning, cost estimation

- **Type:** MCP server
- **Install:** `agentstack add mcp-preflight-dev-preflight`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [preflight-dev](https://agentstack.voostack.com/s/preflight-dev)
- **Installs:** 0
- **Category:** [AI & ML](https://agentstack.voostack.com/c/ai-and-ml)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [preflight-dev](https://github.com/preflight-dev)
- **Source:** https://github.com/preflight-dev/preflight
- **Website:** https://www.npmjs.com/package/preflight-dev

## Install

```sh
agentstack add mcp-preflight-dev-preflight
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# ✈️ preflight

**Stop burning tokens on vague prompts.**

A 24-tool MCP server for Claude Code that catches ambiguous instructions before they cost you 2-3x in wrong→fix cycles — plus semantic search across your entire session history, cross-service contract awareness, and 12-category scorecards.

[](https://www.typescriptlang.org/)
[](https://modelcontextprotocol.io/)
[](LICENSE)
[](https://www.npmjs.com/package/preflight-dev)
[](https://nodejs.org/)

[Quick Start](#quick-start) · [How It Works](#how-it-works) · [Tool Reference](#tool-reference) · [Configuration](#configuration) · [Scoring](#the-12-category-scorecard)

---

## What's New in v3.2.0

- **Unified `preflight_check` entry point** — one tool that triages every prompt and chains the right checks automatically
- **Smart triage classification** — routes prompts through a decision tree (trivial → ambiguous → multi-step → cross-service)
- **Correction pattern learning** — remembers past mistakes and warns you before repeating them
- **Cross-service contracts** — extracts types, interfaces, routes, and schemas across related projects
- **`.preflight/` config directory** — team-shareable YAML config for triage rules and thresholds
- **Trend & comparative scorecards** — weekly/monthly trend lines, cross-project comparisons, radar charts, PDF export
- **Cost estimator** — estimates token spend and waste from corrections

---

## The Problem

We built this after analyzing **9 months of real Claude Code usage** — 512 sessions, 32,000+ events, 3,200+ prompts, 1,642 commits, and 258 sub-agent spawns across a production Next.js/Prisma/Supabase app. The findings were brutal:

- **41% of prompts were under 50 characters** — things like `fix the tests`, `commit this`, `remove them`
- Each vague prompt triggers a **wrong→fix cycle costing 2-3x tokens**
- **~33K characters/day** duplicated from repeated context pastes
- **124 corrections logged** — places where Claude went the wrong direction and had to be steered back
- **94 context compactions** from unbounded session scope blowing past the context window
- Estimated **30-40% of tokens wasted** on avoidable back-and-forth

The pattern is always the same: vague prompt → Claude guesses → wrong output → you correct → repeat. That's your money evaporating.

## The Solution

24 tools in 5 categories that run as an MCP server inside Claude Code:

| Category | Tools | What it does |
|----------|-------|-------------|
| ✈️ **Preflight Core** | 1 | Unified entry point — triages every prompt, chains the right checks automatically |
| 🎯 **Prompt Discipline** | 12 | Catches vague prompts, enforces structure, prevents waste |
| 🔍 **Timeline Intelligence** | 4 | LanceDB vector search across months of session history |
| 📊 **Analysis & Reporting** | 4 | Scorecards, cost estimation, session stats, pattern detection |
| ✅ **Verification & Hygiene** | 3 | Type-check, test, audit, and contract search |

## Before / After

```
❌  "fix the auth bug"
     → Claude guesses which auth bug, edits wrong file
     → You correct it, 3 more rounds
     → 12,000 tokens burned

✅  preflight intercepts → clarify_intent fires
     → "Which auth bug? I see 3 open issues:
        1. JWT expiry not refreshing (src/auth/jwt.ts)
        2. OAuth callback 404 (src/auth/oauth.ts)
        3. Session cookie SameSite (src/middleware/session.ts)
        Pick one and I'll scope the fix."
     → 4,000 tokens, done right the first time
```

---

## Quick Start

### Option A: npx (fastest — no install)

```bash
claude mcp add preflight -- npx -y preflight-dev-serve
```

With environment variables:

```bash
claude mcp add preflight \
  -e CLAUDE_PROJECT_DIR=/path/to/your/project \
  -- npx -y preflight-dev-serve
```

### Option B: Clone & configure manually

```bash
git clone https://github.com/TerminalGravity/preflight.git
cd preflight && npm install
```

Add to your project's `.mcp.json`:

```json
{
  "mcpServers": {
    "preflight": {
      "command": "npx",
      "args": ["tsx", "/path/to/preflight/src/index.ts"],
      "env": {
        "CLAUDE_PROJECT_DIR": "/path/to/your/project"
      }
    }
  }
}
```

Restart Claude Code. The tools activate automatically.

### Option C: npm (global)

```bash
npm install -g preflight-dev
claude mcp add preflight -- preflight-dev-serve
```

> **Note:** `preflight-dev` runs the interactive setup wizard. `preflight-dev-serve` starts the MCP server — that's what you want in your Claude Code config.

---

## How It Works

### The Triage Decision Tree

Every prompt flows through a classification engine before any work begins. This is the actual decision tree from [`src/lib/triage.ts`](src/lib/triage.ts):

```mermaid
flowchart TD
    A[Prompt Arrives] --> B{Skip keyword?}
    B -->|Yes| T1[✅ TRIVIAL]
    B -->|No| C{Multi-step indicators?}
    C -->|Yes| MS[🔶 MULTI-STEP]
    C -->|No| D{Cross-service keywords?}
    D -->|Yes| CS[🔗 CROSS-SERVICE]
    D -->|No| E{always_check keyword?}
    E -->|Yes| AM1[⚠️ AMBIGUOUS]
    E -->|No| F{"|Yes| T2[✅ TRIVIAL]
    F -->|No| G{"|Yes| AM2[⚠️ AMBIGUOUS]
    G -->|No| H{Vague pronouns or verbs?}
    H -->|Yes| AM3[⚠️ AMBIGUOUS]
    H -->|No| CL[✅ CLEAR]

    style T1 fill:#2d6a4f,color:#fff
    style T2 fill:#2d6a4f,color:#fff
    style CL fill:#2d6a4f,color:#fff
    style AM1 fill:#e9c46a,color:#000
    style AM2 fill:#e9c46a,color:#000
    style AM3 fill:#e9c46a,color:#000
    style CS fill:#457b9d,color:#fff
    style MS fill:#e76f51,color:#fff
```

Each level triggers different tool chains:

| Level | What fires | Example prompt |
|-------|-----------|----------------|
| **Trivial** | Nothing — pass through | `commit` |
| **Clear** | File verification only | `fix null check in src/auth/jwt.ts line 42` |
| **Ambiguous** | Clarify intent + git state + workspace priorities | `fix the auth bug` |
| **Cross-service** | Clarify + search related projects + contracts | `add tiered rewards` |
| **Multi-step** | Clarify + scope + sequence + checkpoints | `refactor auth to OAuth2 and update all consumers` |

Additionally, **correction pattern matching** can boost any triage level. If your prompt matches 2+ keywords from a previously logged correction, it's bumped to at least `ambiguous` — even if it would otherwise pass through.

### Data Flow

```mermaid
flowchart LR
    A[User Prompt] --> B[Triage Engine]
    B --> C[Tool Chain]
    C --> D[Response]

    B -.-> E[".preflight/\nconfig.yml\ntriage.yml"]
    B -.-> F["Patterns\nLog"]
    C -.-> G["LanceDB\n(per-project)"]
    C -.-> H["Contracts\n(per-project)"]
    G -.-> I["~/.claude/projects/\n(session JSONL)"]

    style A fill:#264653,color:#fff
    style B fill:#2a9d8f,color:#fff
    style C fill:#e9c46a,color:#000
    style D fill:#e76f51,color:#fff
```

### Session Data Structure

Claude Code stores session data as JSONL files:

```
~/.claude/projects//
├── .jsonl              # Main session
├── /
│   └── subagents/
│       └── .jsonl          # Sub-agent sessions
```

Each JSONL line is an event. The [session parser](src/lib/session-parser.ts) extracts **8 event types**:

| Event Type | Source | What it captures |
|-----------|--------|-----------------|
| `prompt` | `user` messages | What the dev typed |
| `assistant` | `assistant` messages | Claude's text response |
| `tool_call` | `assistant` tool_use blocks | Tool invocations (Read, Write, Bash, etc.) |
| `sub_agent_spawn` | Task/dispatch_agent tool_use | When Claude delegates to a sub-agent |
| `correction` | `user` messages after assistant | Detected via negation patterns (no, wrong, actually, undo…) |
| `compaction` | `system` messages | Context was compressed (session hit token limit) |
| `error` | `tool_result` with is_error | Failed operations |
| `commit` | git log integration | Commits made during session |

### LanceDB Schema

Events are stored in per-project [LanceDB](https://lancedb.github.io/lancedb/) databases with vector embeddings for semantic search:

```
~/.preflight/projects//
├── timeline.lance/       # LanceDB vector database
├── contracts.json        # Extracted API contracts
└── meta.json             # Project metadata

Table: events
├── id: string            (UUID)
├── content: string       (event text)
├── content_preview: string (first 200 chars)
├── vector: float32[384]  (Xenova/all-MiniLM-L6-v2) or float32[1536] (OpenAI)
├── type: string          (event type from above)
├── timestamp: string     (ISO 8601)
├── session_id: string    (session UUID)
├── project: string       (decoded project path)
├── project_name: string  (short name)
├── branch: string        (git branch at time of event)
├── source_file: string   (path to JSONL file)
├── source_line: number   (line number in JSONL)
└── metadata: string      (JSON — model, tool name, etc.)
```

The project registry at `~/.preflight/projects/index.json` maps absolute paths to their SHA-256 hashes.

### Contract Extraction

The [contract extractor](src/lib/contracts.ts) scans your project for API surfaces:

| Pattern | What it finds |
|---------|--------------|
| `export interface/type/enum` | TypeScript type definitions |
| `export function GET/POST/…` | Next.js API routes |
| `router.get/post/…` | Express route handlers |
| `model Foo { … }` | Prisma models and enums |
| OpenAPI/Swagger specs | Routes and schema components |
| `.preflight/contracts/*.yml` | Manual contract definitions |

Contracts are stored per-project and searched across related projects during cross-service triage.

---

## Onboarding a Project

Run `onboard_project` to index a project's history. Here's what happens:

1. **Discovers sessions** — finds JSONL files in `~/.claude/projects//`, including subagent sessions
2. **Parses events** — extracts the 8 event types from each session file (streams files >10MB)
3. **Extracts contracts** — scans source for types, interfaces, enums, routes, Prisma models, OpenAPI schemas
4. **Loads manual contracts** — merges any `.preflight/contracts/*.yml` definitions (manual wins on name conflicts)
5. **Generates embeddings** — local [Xenova/all-MiniLM-L6-v2](https://huggingface.co/Xenova/all-MiniLM-L6-v2) by default (~90MB model download on first run, ~50 events/sec) or OpenAI if `OPENAI_API_KEY` is set (~200 events/sec)
6. **Stores in LanceDB** — per-project database at `~/.preflight/projects//timeline.lance/`
7. **Updates registry** — records the project in `~/.preflight/projects/index.json`

No data leaves your machine unless you opt into OpenAI embeddings.

After onboarding, you get:
- 🔎 **Semantic search** — "How did I set up auth middleware last month?" actually works
- 📊 **Timeline view** — see what happened across sessions chronologically
- 🔄 **Live scanning** — index new sessions as they happen
- 🔗 **Cross-service search** — query across related projects

---

## Tool Reference

### ✈️ Preflight Core

| Tool | What it does |
|------|-------------|
| `preflight_check` | **The main entry point.** Triages your prompt (trivial → multi-step), chains the right checks automatically, matches against known correction patterns. Accepts `force_level` override: `skip`, `light`, `full`. |

### 🎯 Prompt Discipline

| Tool | What it does |
|------|-------------|
| `scope_work` | Creates structured execution plans before coding starts |
| `clarify_intent` | Gathers project context (git state, workspace docs, ambiguity signals) to disambiguate vague prompts |
| `enrich_agent_task` | Enriches sub-agent tasks with file paths, patterns, and cross-service context |
| `sharpen_followup` | Resolves "fix it" / "do the others" to actual file targets |
| `token_audit` | Detects waste patterns, grades your session A–F |
| `sequence_tasks` | Orders tasks by dependency, locality, and risk |
| `checkpoint` | Save game before compaction — commits + resumption notes |
| `check_session_health` | Monitors uncommitted files, time since commit, turn count |
| `log_correction` | Tracks corrections and identifies recurring error patterns |
| `check_patterns` | Checks prompts against learned correction patterns — warns about known pitfalls |
| `session_handoff` | Generates handoff briefs for new sessions |
| `what_changed` | Summarizes diffs since last checkpoint |

### 🔍 Timeline Intelligence

| Tool | What it does |
|------|-------------|
| `onboard_project` | Indexes a project's session history + contracts into per-project LanceDB |
| `search_history` | Semantic search with scope: current project, related, or all indexed projects |
| `timeline` | Chronological view of events across sessions |
| `scan_sessions` | Live scanning of active session data |

### 📊 Analysis & Reporting

| Tool | What it does |
|------|-------------|
| `generate_scorecard` | 12-category report card — session, trend (week/month), or cross-project comparative. Radar chart SVG, PDF or markdown. |
| `estimate_cost` | Token usage, dollar cost, waste from corrections, preflight savings |
| `session_stats` | Lightweight session analysis — no embeddings needed |
| `prompt_score` | Gamified A–F grading on specificity, scope, actionability, done-condition |

### ✅ Verification & Hygiene

| Tool | What it does |
|------|-------------|
| `verify_completion` | Runs type check + tests + build before declaring done |
| `audit_workspace` | Finds stale/missing workspace docs vs git activity |
| `search_contracts` | Search API contracts, types, and schemas across current and related projects |

---

## Usage Examples

Real prompts you'd type in Claude Code once preflight is installed. The tools fire automatically via `preflight_check`, or you can call them directly.

### Catch a vague prompt before it wastes tokens

```
> fix the auth bug

preflight_check intercepts → clarify_intent fires:
  "I found 3 auth-related recent changes:
   1. JWT refresh logic in src/auth/jwt.ts (modified 2h ago)
   2. OAuth callback route in src/routes/oauth.ts (3 open TODOs)
   3. Session middleware in src/middleware/auth.ts (failing test)
   Which one? Or describe the symptoms."
```

### Scope a multi-step task before starting

```
> refactor the database layer to use Drizzle instead of Prisma

preflight_check triages as MULTI-STEP → scope_work + sequence_tasks fire:
  Phase 1: Install drizzle-orm, create schema (src/db/schema.ts)
  Phase 2: Migrate queries in src/services/ (12 files)
  Phase 3: Update tests (8 files reference prisma mocks)
  Phase 4: Remove prisma dependencies, delete prisma/ dir
  Estimated: 4 checkpoints, ~45 min
```

### Search your session history

```
> use search_history to find how I set up the rate limiter

Searches LanceDB across your indexed sessions:
  Found 3 relevant events (similarity > 0.82):
  - Session abc123 (Jan 15): Added express-rate-limit to src/middleware/
  - Session def456 (Jan 16): Configured per-route limits in src/routes/api.ts
  - Session ghi789 (Feb 2): Fixed rate limit bypass via X-Forwarded-For
```

### Grade your prompting habits

```
> use prompt_score on "update the thing"

  Grade: D
  - Specificity: 1/5 — no file paths, no identifiers
  - Scope: 1/5 — "the thing" is completely ambiguous
  - Actionability: 2/5 — "update" is vague (refactor? fix? add feature?)
  - Done-condition: 0/5 — no way to know when it's done
  Suggestion: "Update the price formatter in src/utils/currency.ts
  to handle JPY (zero-decimal currency)"
```

### Check session health mid-work

```
> use check_session_health

  ⚠️ 47 uncommitted files (last commit: 38 min ago)
  ⚠️ 23 turns since last checkpoint
  💡 Consider running `checkpoint` before context compaction hits
```

### Get a cost estimate

```
> use estimate_cost

  This session: ~$2.40 (148K tokens)
  Waste from corrections: ~$0.85 (3 wrong→fix cycles)
  Preflight savings: ~$1.20 (4 vague prompts caught early)
  Net: saving roughly 35% vs unchecked prompting
```

---

## The 12-Category Scorecard

`generate_scorecard` evaluates your prompt discipline across 12 categories. Each one measures something specific about how you interact with Claude Code:

| # | Category | What it mea

…

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [preflight-dev](https://github.com/preflight-dev)
- **Source:** [preflight-dev/preflight](https://github.com/preflight-dev/preflight)
- **License:** MIT
- **Homepage:** https://www.npmjs.com/package/preflight-dev

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** yes
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-preflight-dev-preflight
- Seller: https://agentstack.voostack.com/s/preflight-dev
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
