# Project export: PromptPilot

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: UC Berkeley AI Hackathon 2025
- Tagline: We built PromptPilot, a platform that stores, manages, and optimizes prompts. It uses a Model Context Protocol (MCP) server that streamlines your workflow and enhances your productivity.
- Devpost: https://devpost.com/software/promptpilot-0okgyd
- GitHub: https://github.com/DavidWangwjh/prompt-pilot
- Demo: https://prompt-ai-pilot.vercel.app/
- Team: 2 GitHub contributor(s) — DavidWangwjh (36 commits), Aaron41402 (11 commits)

## Devpost submission (written by the team)

### Inspiration

As the use of AI tools surged, we noticed a critical bottleneck: while users rely heavily on prompts, there's no standardized way to manage, share, or execute them across tools and teams. More importantly, users were stuck manually selecting or crafting prompts for each task—wasting time and reducing consistency. We were inspired by the potential of a new standard: MCP (Model Context Protocol). Imagine a world where any AI tool—like Cursor, Claude, or VSCode extensions—can automatically pull the best prompt for your task, intelligently selected and explained. That’s the vision PromptPilot is helping make real.

### What it does

Stores, optimizes, and versions AI prompts. Runs an MCP server that understands user intent and intelligently returns the best-fit prompt for external tools or in-app tasks. Lets users configure personal MCP endpoints to plug PromptPilot directly into apps like Claude desktop or IDEs. Includes a Prompt Playground with an AI judge (built using Agentverse) that compares multiple prompts and provides objective, model-based feedback. Encourages community-driven prompt reuse and remixing. But the heart of the platform is its intelligent MCP integration—a game-changing layer for automated prompt delivery and AI workflow optimization.

### How we built it

We used Next.js with TypeScript and TailwindCSS for the frontend, and Supabase for the database. The website is deployed using Vercel.

### Challenges we ran into

Defining the MCP standard: There was no widely adopted format for AI prompt delivery over API. We had to build a usable, minimal configuration system and ensure it worked smoothly with tools expecting different levels of flexibility. Prompt selection logic: Building a reliable scoring model for prompts based on task intent took time and experimentation. Security concerns: Since MCP endpoints expose access to user data, we had to ensure strict token-based access and private-by-default behavior. Cross-tool compatibility: Ensuring the MCP server could be consumed by tools like Claude, Cursor, or AI-powered extensions required us to maintain a clean, well-documented API spec.

### Accomplishments we're proud of

Launched one of the first working MCP server interfaces for prompt selection, opening up a new paradigm for AI task execution. Developed a plug-and-play MCP configuration system, making PromptPilot instantly usable as a backend for third-party AI tools. Enabled automated, intelligent prompt selection, removing friction for users and enhancing the quality of outputs. Created a version-controlled, remixable ecosystem that combines utility and creativity in the prompt design space.

### What we learned

The future of AI tooling lies in interoperability. MCP showed us that standardizing how models receive prompts unlocks huge productivity gains. Prompt reuse isn’t enough—intelligent selection and automation must follow. Users want results, not prompt engineering. People will remix and collaborate when given clear attribution and useful defaults—but only if privacy is preserved. Model feedback can be trusted when combined with structured scoring and AI judges—empowering users with real metrics over guesswork.

### What's next

MCP 2.0 Spec: Add support for multi-step workflows (e.g., generate → critique → rewrite), prompt chaining, and fallback prompts. Multi-model execution: Allow the MCP agent to select prompts and models across OpenAI, Claude, Gemini, and local LLMs based on performance history. CLI + IDE Plugins: Let developers use MCP directly inside their coding environment. MCP Prompt Marketplace: Allow verified creators to offer premium prompts via MCP endpoints. Analytics + Feedback Loop: Use real-world execution data to continuously retrain and improve prompt selection.

## README (from the GitHub repository)

# PromptPilot - Intelligent Task Execution MCP

PromptPilot is an advanced Model Context Protocol (MCP) tool that intelligently analyzes user tasks, breaks them down into components, and retrieves suitable prompts from your personal vault for execution in Cursor or Claude Desktop.

## 🚀 Key Features

### **Intelligent Task Analysis**
- **Automatic Task Classification**: Identifies task types (research, writing, coding, planning, etc.)
- **Complexity Assessment**: Determines task complexity (low, medium, high)
- **Keyword Extraction**: Extracts relevant keywords for better prompt matching
- **Step Estimation**: Predicts required steps based on task complexity

### **Dynamic Prompt Retrieval**
- **Smart Matching**: Finds the most relevant prompts from your vault
- **Step-based Search**: Looks for prompts matching workflow steps
- **Keyword Matching**: Searches by extracted keywords
- **Relevance Scoring**: Ranks prompts by relevance to the task

### **Execution Planning**
- **Step-by-step Instructions**: Clear guidance for executing prompt chains
- **Time Estimates**: Predicts execution time
- **Context Building**: Each prompt builds on previous outputs
- **Cursor/Claude Ready**: Optimized for MCP clients

## 🛠️ How It Works

### 1. **Task Analysis**
When you provide a task like "research AI safety and create a summary":

1. **Pattern Recognition**: Identifies task type using regex patterns
2. **Complexity Assessment**: Analyzes task length and keyword count
3. **Step Estimation**: Determines optimal number of steps
4. **Breakdown Planning**: Maps task to workflow steps

### 2. **Prompt Retrieval**
The system searches your vault using:

- **Step Matching**: Looks for prompts matching workflow steps (background_research, deep_analysis, etc.)
- **Keyword Matching**: Finds prompts containing task keywords
- **Relevance Scoring**: Ranks prompts by match quality
- **Deduplication**: Avoids duplicate prompts

### 3. **Execution Plan Creation**
Generates a comprehensive plan with:

- **Task Analysis**: Shows detected type, complexity, keywords
- **Prompt Chain**: Ordered list of prompts to execute
- **Instructions**: Step-by-step execution guidance
- **Time Estimates**: Expected completion time

## 📋 Supported Task Types

| Task Type | Keywords | Example Tasks |
|-----------|----------|---------------|
| **Research** | research, analyze, investigate, study, explore | "research AI safety", "analyze market trends" |
| **Writing** | write, compose, create, draft, generate content | "write a blog post", "compose an email" |
| **Summary** | summarize, condense, brief, overview, recap | "summarize this document", "create a brief" |
| **Coding** | code, program, develop, debug, review code | "review this code", "implement a feature" |
| **Planning** | plan, strategy, roadmap, outline, design | "plan a project", "create a roadmap" |
| **Review** | review, evaluate, assess, critique, analyze | "review this proposal", "evaluate options" |
| **Brainstorming** | brainstorm, ideate, generate, suggest | "brainstorm solutions", "generate ideas" |
| **Problem Solving** | solve, fix, resolve, troubleshoot, debug | "solve this bug", "fix the problem" |
| **Learning** | learn, understand, explain, educate | "explain this concept", "teach me about" |
| **Creative** | creative, artistic, design, imagine | "design a logo", "create artwork" |

## 🔧 MCP Tool Specification

### Tool: `execute_task_workflow`

**Description**: Intelligently analyzes a user's task, breaks it down into components, retrieves suitable prompts from their vault, and returns an executable workflow for Cursor or Claude Desktop.

**Input Schema**:
```json
{
  "type": "object",
  "properties": {
    "task": {
      "type": "string",
      "description": "The task you want to accomplish. For example: 'research AI safety and create a summary' or 'write a blog post about machine learning trends'."
    }
  },
  "required": ["task"]
}
```

**Response Format**:
```json
{
  "task": "research AI safety and create a summary",
  "analysis": {
    "primaryType": "research",
    "secondaryTypes": ["summary"],
    "complexity": "medium",
    "estimatedSteps": 3,
    "keywords": ["research", "safety", "summary"],
    "breakdown": ["background_research", "deep_analysis", "synthesis", "summary"]
  },
  "prompts": [
    {
      "id": 1,
      "title": "Background Research Prompt",
      "content": "Conduct initial research on...",
      "order": 1,
      "step": "background_research",
      "instructions": "Execute this prompt and use its output as input for the next step."
    }
  ],
  "totalSteps": 3,
  "estimatedTime": "6-9 minutes",
  "executionInstructions": "1. Execute each prompt in order... 2. Use output as context..."
}
```

## 🎯 Usage Examples

### Example 1: Research Task
**Input**: "research AI safety and create a comprehensive summary"

**Analysis**:
- Primary Type: research
- Secondary Type: summary
- Complexity: medium
- Estimated Steps: 3

**Result**: 3-step prompt chain:
1. Background Research Prompt
2. Deep Analysis Prompt
3. Summary Creation Prompt

### Example 2: Writing Task
**Input**: "write a blog post about machine learning trends in 2024"

**Analysis**:
- Primary Type: writing
- Complexity: medium
- Estimated Steps: 3

**Result**: 3-step prompt chain:
1. Outline Creation Prompt
2. Content Drafting Prompt
3. Review and Polish Prompt

### Example 3: Coding Task
**Input**: "review and optimize this Python code for performance"

**Analysis**:
- Primary Type: coding
- Secondary Type: review
- Complexity: medium
- Estimated Steps: 3

**Result**: 3-step prompt chain:
1. Code Analysis Prompt
2. Performance Review Prompt
3. Optimization Suggestions Prompt

## 🏗️ Architecture

```
User Task → MCP API → Task Analysis → Prompt Retrieval → Execution Plan
     ↓
Task Analysis Engine
├── Pattern matching for task types
├── Complexity assessment
├── Keyword extraction
└── Step estimation

Prompt Retrieval Engine
├── Step-based matching
├── Keyword-based matching
├── Relevance scoring
└── Deduplication

Execution Plan Generator
├── Prompt ordering
├── Instruction generation
├── Time estimation
└── Context building
```

## 🚀 Getting Started

### 1. **Install Dependencies**
```bash
npm install
```

### 2. **Set up Supabase**
- Configure your Supabase credentials in environment variables
- Ensure the prompts table exists with the required schema

### 3. **Add Prompts to Vault**
- Use the Vault interface to add diverse prompts
- Tag prompts appropriately for better matching
- Include prompts for different task types

### 4. **Test the MCP**
- Visit `/test-mcp` to test the workflow engine
- Try different task types to see dynamic execution plans
- Check the execution instructions and prompt chains

### 5. **Use with Cursor/Claude Desktop**
- Configure the MCP server URL in your MCP client
- Use the `execute_task_workflow` tool with your tasks
- Follow the execution plan to accomplish your goals

## 🎨 Test Interface

The test page at `/test-mcp` provides:

- **Quick Test Examples**: Pre-defined tasks to try
- **Task Input**: Text area for custom tasks
- **Task Analysis Display**: Shows detected type, complexity, keywords
- **Execution Plan**: Step-by-step instructions and time estimates
- **Prompt Chain**: Ordered list of prompts with content and instructions
- **Raw JSON**: Toggle to see the complete MCP response

## 🔮 Future Enhancements

- **AI-powered Analysis**: Use LLM for more accurate task classification
- **Learning System**: Improve matching based on successful executions
- **Custom Workflows**: Allow users to create and save custom workflows
- **Advanced Chaining**: Support conditional logic and branching
- **Integration APIs**: Connect with external tools and services
- **Collaborative Features**: Share workflows and prompts between users

## 📝 License

MIT License - see LICENSE file for details.


## Detected evidence (automated analysis)

Indexed codebase: 34 recognized source files, 172 KB.
- CSS (language) — detected in the code
- Google Gemini (technology) — detected in the code
- JavaScript (language) — detected in the code
- Next.js (technology) — detected in the code
- React (technology) — detected in the code
- Supabase (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code
- Vercel (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (40 of 40)

```
.gitignore
eslint.config.mjs
MCP_SETUP.md
next.config.ts
package.json
postcss.config.mjs
PRD.md
README.md
request.json
rule-next-coding-standards.md
src/app/(dashboard)/dashboard/page.tsx
src/app/(dashboard)/layout.tsx
src/app/(public)/login/page.tsx
src/app/(public)/signup/page.tsx
src/app/api/mcp-link/route.ts
src/app/api/optimize/route.ts
src/app/api/playground/route.ts
src/app/globals.css
src/app/layout.tsx
src/app/page.tsx
src/app/test-mcp/page.tsx
src/components/Navbar.tsx
src/components/PromptCard.tsx
src/components/Sidebar.tsx
src/components/ui/AuthForm.tsx
src/components/views/ExploreView.tsx
src/components/views/MCPConfigView.tsx
src/components/views/MCPView.tsx
src/components/views/PlaygroundView.tsx
src/components/views/VaultView.tsx
src/context/DashboardContext.tsx
src/lib/ai-judge-agent.ts
src/lib/database.types.ts
src/lib/prompts.ts
src/lib/supabase.ts
src/lib/supabase/client.ts
src/lib/supabase/server.ts
src/lib/workflows.ts
tailwind.config.js
tsconfig.json
```

### Dependencies

- package.json: @eslint/eslintrc@^3, @google/generative-ai@^0.24.1, @heroicons/react@^2.2.0, @supabase/auth-helpers-nextjs@^0.10.0, @supabase/ssr@^0.6.1, @supabase/supabase-js@^2.50.0, @tailwindcss/postcss@^4, @types/node@^20, @types/react@^19, @types/react-dom@^19, @wong2/mcp-cli@^1.10.0, clsx@^2.1.1, eslint@^9, eslint-config-next@15.3.4, fetchai-sdk@^1.11.0, fuse.js@^7.1.0, lucide-react@^0.522.0, next@15.3.4, react@^19.0.0, react-dom@^19.0.0, supabase@^2.26.9, tailwind-merge@^3.3.1, tailwindcss@^4, typescript@^5

### Recent commits (newest first)

- remove suitable
- updated lib
- updated mcp
- updated logo
- updated mcp
- updated mcp
- updated mcp
- updated mcp
- updated mcp
- updated mcp
- updated mcp
- updated mcp
- updated mcp
- Merge branch 'main' of https://github.com/DavidWangwjh/prompt-pilot
- added tools
- Merge branch 'main' of https://github.com/DavidWangwjh/prompt-pilot
- mcp fixed
- fixed linter errors
- Merge branch 'main' of https://github.com/DavidWangwjh/prompt-pilot
- mcp fix

## Key source files (fetched from GitHub, selected and truncated for size)

### PRD.md

```markdown
# 🎨 PromptPilot UI RPD (Rapid Product Development Plan)

Focus: Step-by-step UI implementation using Next.js + Tailwind CSS + TypeScript (App Router)

---

## 🔧 Phase 1: Core Layout & Boilerplate

### ✅ Step 1: Base Layout

* Create `src/app/layout.tsx`
* Add `<Sidebar />` and `<Navbar />` wrappers
* Use Tailwind's flex/grid for responsive layout

### ✅ Step 2: Global Styles

* Configure Tailwind `globals.css`
* Add font family, background, text colors, spacing standards

### ✅ Step 3: Dark Mode Support (Optional)

* Tailwind dark mode toggle via class strategy
* `useTheme()` hook or context wrapper

---

## 🏠 Phase 2: Public Pages

### 🚀 Step 4: Landing Page (`/`)

* Create hero section: logo, tagline, CTA
* Add feature grid with icons/text
* Use Tailwind spacing, font sizes, and animation utils

### 🔐 Step 5: Auth Pages (`/auth/signup`, `/auth/login`)

* Build `LoginForm.tsx` and `SignupForm.tsx`
* Add form input, labels, validation, submit button
* Toggle mode between login/signup
* Tailwind form components, button loading state

---

## 🗂️ Phase 3: Dashboard & Navigation

### 📁 Step 6: Dashboard Page (`/dashboard`)

* Use Google Drive UI as reference
* Sidebar (vertical): links to Vault, Explore, Playground, MCP, Trash
* Topbar (horizontal): search, profile avatar, settings
* Main panel:

  * Card grid for prompts
  * List/grid toggle button
  * "New Prompt" floating action button (FAB)

### 🧱 Step 7: Sidebar & Navbar Components

* `Sidebar.tsx`: active state, icons, hover
* `Navbar.tsx`: profile menu dropdown, responsive support

### 🧩 Step 8: Prompt Cards

* `PromptCard.tsx`: title, tag chips, like/share buttons
* Support list/grid layout
* Add hover animation + click handler

---

## ✍️ Phase 4: Prompt Editor

### 📝 Step 9: Prompt Editor Page (`/prompt/[id]`)

* Editor section: title input, text area for prompt
* Right panel:

  * Version history (with timestamps)
  * Save + rollback button
* Top action bar: optimize button

### 🔀 Step 10: Diff Viewer (Optional)

* `PromptDiffViewer.tsx`: show line-by-line diff
* Tailwind background colors for additions/removals

---

## 🧪 Phase 5: Prompt Playground

### 🧠 Step 11: Playground Page (`/playground`)

* Textarea for prompt input
* Input for optional context
* Dropdown to select model (GPT-4, Claude, etc)
* Run button + loading state
* Show AI response output

---

## 🔎 Phase 6: Explore Page

### 🌍 Step 12: Explore Public Prompts (`/explore`)
s
* Grid of `PromptCard`s
* Filter sidebar:

  * By model
  * By tag
  * By popularity
* Like, remix, share buttons

---

## ⚙️ Phase 7: MCP Config Interface

### ⚙️ Step 13: MCP Page (`/mcp`)

* Display example MCP JSON config
* Toggle view (raw/pretty)
* Copy-to-clipboard button

---

## ✅ Final Phase: Polish & Review

### 🎯 Step 14: Polish UI/UX

* Responsive behavior
* Hover and focus states
* Button animations + form feedback
* Tailwind transitions and spacing cleanup

### 🧪 Step 15: Manual Testing

* Check navigation between pages
* 
[truncated — 157 more characters]
```

### MCP_SETUP.md

```markdown
# MCP Setup Guide for Cursor

## Quick Fix for Loading Issues

If Cursor is stuck on "loading" when trying to connect to the PromptPilot MCP, follow these steps:

### 1. **Test the MCP First**
- Start your development server: `npm run dev`
- Visit: `http://localhost:3000/test-mcp`
- Click the "Test MCP" button to verify it's working
- If this works, the MCP is functioning correctly

### 2. **Cursor MCP Configuration**

Add this to your Cursor settings (Ctrl/Cmd + ,):

```json
{
  "mcpServers": {
    "promptpilot": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-nextjs", "http://localhost:3000/api/mcp-link"],
      "env": {}
    }
  }
}
```

### 3. **Alternative Configuration**

If the above doesn't work, try this simpler approach:

```json
{
  "mcpServers": {
    "promptpilot": {
      "command": "curl",
      "args": ["-X", "POST", "-H", "Content-Type: application/json", "-d", "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}", "http://localhost:3000/api/mcp-link"],
      "env": {}
    }
  }
}
```

### 4. **Troubleshooting Steps**

1. **Check if the server is running**:
   ```bash
   curl -X POST -H "Content-Type: application/json" \
     -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' \
     http://localhost:3000/api/mcp-link
   ```

2. **Test initialization**:
   ```bash
   curl -X POST -H "Content-Type: application/json" \
     -d '{"jsonrpc":"2.0","id":1,"method":"initialize"}' \
     http://localhost:3000/api/mcp-link
   ```

3. **Test tool execution**:
   ```bash
   curl -X POST -H "Content-Type: application/json" \
     -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"execute_task_workflow","arguments":{"task":"test"}}}' \
     http://localhost:3000/api/mcp-link
   ```

### 5. **Common Issues and Solutions**

**Issue**: Cursor shows "loading" indefinitely
- **Solution**: Check if the development server is running on port 3000
- **Solution**: Verify the MCP endpoint responds to basic requests

**Issue**: "Connection refused" error
- **Solution**: Make sure `npm run dev` is running
- **Solution**: Check if port 3000 is available

**Issue**: "Method not found" error
- **Solution**: The MCP is working but the method name is incorrect
- **Solution**: Use `execute_task_workflow` as the method name

### 6. **Using the MCP in Cursor**

Once configured, you can use the MCP in Cursor:

1. **Open a chat in Cursor**
2. **Type a task**: "research AI safety and create a summary"
3. **The MCP will**: Analyze the task, find relevant prompts from your vault, and return an execution plan
4. **Follow the plan**: Execute the prompts in order as specified

### 7. **Example Usage**

```
User: research AI safety and create a summary

MCP Response:
- Task Analysis: Research task, medium complexity, 3 steps
- Prompt Chain: 
  1. Background Research Prompt
  2. Deep Analysis Prompt  
  3. Summary Creation Prompt
- Execution Instructions: Step-by-step guidance
- Time Estimate: 6-9 minutes
```

### 8. **Res
[truncated — 650 more characters]
```

### package.json

```
{
  "name": "prompt-pilot",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev --turbopack",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@google/generative-ai": "^0.24.1",
    "@heroicons/react": "^2.2.0",
    "@supabase/auth-helpers-nextjs": "^0.10.0",
    "@supabase/ssr": "^0.6.1",
    "@supabase/supabase-js": "^2.50.0",
    "clsx": "^2.1.1",
    "fetchai-sdk": "^1.11.0",
    "fuse.js": "^7.1.0",
    "lucide-react": "^0.522.0",
    "next": "15.3.4",
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "tailwind-merge": "^3.3.1"
  },
  "devDependencies": {
    "@eslint/eslintrc": "^3",
    "@tailwindcss/postcss": "^4",
    "@types/node": "^20",
    "@types/react": "^19",
    "@types/react-dom": "^19",
    "@wong2/mcp-cli": "^1.10.0",
    "eslint": "^9",
    "eslint-config-next": "15.3.4",
    "supabase": "^2.26.9",
    "tailwindcss": "^4",
    "typescript": "^5"
  }
}

```

### src/app/layout.tsx

```typescript
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";

const geistSans = Geist({
  variable: "--font-geist-sans",
  subsets: ["latin"],
});

const geistMono = Geist_Mono({
  variable: "--font-geist-mono",
  subsets: ["latin"],
});

export const metadata: Metadata = {
  title: "PromptPilot",
  description: "Manage, create, and optimize your AI prompts with ease.",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={`${geistSans.variable} ${geistMono.variable}`}>
        {children}
      </body>
    </html>
  );
}
```

### src/app/page.tsx

```typescript
import Link from 'next/link';
import Image from 'next/image';
import { ArrowRight, Sparkles, Zap, Users, Shield } from 'lucide-react';

export default function LandingPage() {
  return (
    <div className="flex flex-col min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 items-center">
      {/* Header */}
      <header className="px-4 lg:px-6 h-16 flex items-center w-full backdrop-blur-sm bg-white/70 border-b border-gray-200/50">
        <Link href="/" className="flex items-center justify-center group">
          <div className="relative flex items-center">
            <span className="text-xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
              PromptPilot
            </span>
            <Image 
              src="/logo.png" 
              alt="PromptPilot Logo" 
              width={40} 
              height={40} 
              className="h-10 w-10"
            />
            <Sparkles className="absolute -top-1 -right-4 h-4 w-4 text-yellow-500 opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
          </div>
        </Link>
        <nav className="ml-auto flex items-center gap-4 sm:gap-6">
          <Link href="/login" className="text-sm font-medium hover:text-blue-600 transition-colors duration-200">
            Login
          </Link>
          <Link
            href="/signup"
            className="inline-flex h-9 items-center justify-center rounded-full bg-gradient-to-r from-blue-600 to-purple-600 px-6 py-2 text-sm font-medium text-white shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105"
          >
            Sign Up
          </Link>
        </nav>
      </header>

      {/* Hero Section */}
      <main className="flex-1 relative overflow-hidden">
        {/* Floating Elements */}
        <div className="absolute inset-0 overflow-hidden pointer-events-none">
          <div className="absolute top-20 left-10 w-20 h-20 bg-blue-200/30 rounded-full blur-xl animate-pulse"></div>
          <div className="absolute top-40 right-20 w-32 h-32 bg-purple-200/20 rounded-full blur-xl animate-pulse delay-1000"></div>
          <div className="absolute bottom-40 left-20 w-24 h-24 bg-indigo-200/25 rounded-full blur-xl animate-pulse delay-2000"></div>
          <div className="absolute bottom-20 right-10 w-16 h-16 bg-blue-200/30 rounded-full blur-xl animate-pulse delay-1500"></div>
        </div>

        <section className="relative w-full h-[calc(100vh-4rem)] flex items-center justify-center">
          <div className="container px-4 md:px-6">
            <div className="flex flex-col items-center space-y-8 text-center">
              {/* Badge */}
              <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-blue-100/80 backdrop-blur-sm border border-blue-200/50">
                <Zap className="h-4 w-4 text-blue-600" />
                <span className="text-sm font-medium text-blue-700">MCP-Powered Prompt Optimization</span>
              </div>

              <h1 className="text-4xl font-bold tracking-tight sm:text-5xl md:text-6xl lg:text-7xl/none bg-gradient-to-r from-gray-900 via-blue-800 to-purple-800 bg-clip-text text-transparent animate-in slide-in-from-bottom-4 duration-1000">
                Manage. Chain. Execute.
              </h1>
              
              <p className="mx-auto max-w-[700px] text-gray-600 md:text-xl leading-relaxed animate-in slide-in-from-bottom-4 duration-1000 delay-200">
                Optimize and manage AI workflows with intelligent prompt engineering and Model Context Protocol (MCP) to deliver exceptional results.
              </p>

              <div className="flex flex-col sm:flex-row gap-4 animate-in slide-in-from-bottom-4 duration-1000 delay-300">
                <Link
                  href="/login"
                  className="group inline-flex h-12 items-center justify-center rounded-full bg-gradient-to-r from-blue-600 to-purple-600 px-8 text-base font-semibold text-white shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105"
                >
                  Get Started
                  <ArrowRight className="ml-2 h-5 w-5 group-hover:translate-x-1 transition-transform duration-200" />
                </Link>
              </div>
            </div>
          </div>
        </section>

        {/* Features Section */}
        <section className="py-16 bg-white/50 backdrop-blur-sm mb-8 rounded-lg">
          <div className="container px-4 md:px-6">
            <div className="text-center mb-12">
              <h2 className="text-3xl font-bold text-gray-900 mb-4">
                Everything You Need to Master AI Workflows
              </h2>
              <p className="text-gray-600 max-w-2xl mx-auto">
                From beginners to experts, PromptPilot provides the tools and insights 
                to create workflows that consistently deliver amazing results.
              </p>
            </div>

            <div className="grid md:grid-cols-3 gap-8">
              <div className="text-center p-6 rounded-2xl bg-white/70 backdrop-blur-sm border border-gray-200/50 hover:shadow-lg transition-all duration-300 hover:scale-105">
                <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                  <Sparkles className="h-6 w-6 text-blue-600" />
                </div>
                <h3 className="text-xl font-semibold text-gray-900 mb-2">Smart Optimization</h3>
                <p className="text-gray-600">
                  AI-powered suggestions to improve your prompts and get better results.
                </p>
              </div>

              <div className="text-center p-6 rounded-2xl bg-white/70 backdrop-blur-sm border border-gray-200/50 hover:shadow-lg transition-all duration-300 hover:scale-105">
                <div className="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
          
[truncated — 1755 more characters]
```

### src/app/(dashboard)/layout.tsx

```typescript
'use client';

import Sidebar from "@/components/Sidebar";
import Navbar from "@/components/Navbar";
import "../globals.css";
import { DashboardProvider } from "@/context/DashboardContext";

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <DashboardProvider>
      <div className="flex h-screen bg-gray-50 overflow-hidden">
        <Sidebar />
        <div className="flex flex-1 flex-col overflow-hidden">
          <Navbar />
          <main className="flex-1 overflow-y-auto p-4 sm:p-6 transition-all duration-200">
            {children}
          </main>
        </div>
      </div>
    </DashboardProvider>
  );
}

```

### src/lib/supabase/server.ts

```typescript
import { type CookieOptions, createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'

import { Database } from '@/lib/database.types'

// Validate environment variables
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;

if (!supabaseUrl || !supabaseAnonKey) {
  throw new Error(
    'Missing Supabase environment variables. Please set NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY in your environment variables.'
  );
}

export const createSupabaseServerClient = async () => {
  const cookieStore = await cookies()

  return createServerClient<Database>(
    supabaseUrl,
    supabaseAnonKey,
    {
      cookies: {
        get(name: string) {
          return cookieStore.get(name)?.value
        },
        set(name: string, value: string, options: CookieOptions) {
          cookieStore.set(name, value, options)
        },
        remove(name: string, options: CookieOptions) {
          cookieStore.delete({ name, ...options })
        },
      },
    }
  )
} 
```

### src/app/test-mcp/page.tsx

```typescript
'use client';

import { useState } from 'react';
import { Loader2, Workflow, Send, Database, AlertTriangle } from 'lucide-react';

// --- Types ---
interface Prompt {
  id: number;
  title: string;
  content: string;
  order: number;
}

interface ExecutionPlan {
  task: string;
  analysis: {
    actions: string[];
    keywords: string[];
  };
  prompts: Prompt[];
}

// --- Components ---
const ExecutionPlanDisplay = ({ plan, finalAnswer, status }: { plan: ExecutionPlan, finalAnswer: string | null, status: 'executing' | 'done' }) => {
  return (
    <div className="space-y-8">
      {/* Final Answer */}
      {finalAnswer && status === 'done' && (
        <div className="bg-green-50 p-6 rounded-lg border-2 border-green-200 shadow-lg">
          <h2 className="text-xl font-bold text-green-900 mb-3">Final Result</h2>
          <div className="bg-white p-4 rounded-md text-gray-800 whitespace-pre-wrap">{finalAnswer}</div>
        </div>
      )}
      
      {/* Status Indicator */}
      {status === 'executing' && (
          <div className="flex items-center justify-center gap-3 text-blue-600 py-4">
            <Loader2 className="animate-spin" size={24} />
            <span className="text-lg">Executing prompts...</span>
          </div>
      )}

      {/* Execution Details */}
      <div>
        <h3 className="text-lg font-semibold text-gray-700">Execution Details</h3>
        <div className="mt-2 bg-gray-50 p-4 rounded-lg border">
            <p className="text-sm text-gray-600">
              <strong>Task:</strong> {plan.task} <br />
              <strong>Detected Actions:</strong> <span className="font-medium capitalize text-purple-600">{plan.analysis.actions.join(', ')}</span> | 
              <strong>Keywords:</strong> <span className="font-medium text-purple-600">{plan.analysis.keywords.join(', ')}</span>
            </p>
        </div>
      </div>

      <div className="space-y-4">
        <h3 className="text-lg font-semibold text-gray-700 flex items-center gap-2">
            <Database className="h-5 w-5 text-purple-600" />
            Prompts Retrieved from Vault
        </h3>
        {plan.prompts.map((prompt) => (
          <div key={prompt.id} className="bg-white border border-gray-200 rounded-lg p-4">
              <div className="flex items-center gap-3 mb-2">
                  <span className="bg-purple-600 text-white text-xs font-bold rounded-full h-6 w-6 flex items-center justify-center">{prompt.order}</span>
                  <h4 className="font-semibold text-gray-800">{prompt.title}</h4>
              </div>
              <p className="text-sm text-gray-600 font-mono bg-gray-50 p-3 rounded-md whitespace-pre-wrap">{prompt.content}</p>
          </div>
        ))}
      </div>
    </div>
  );
};

// --- Main Page ---
export default function McpTestPage() {
  const [task, setTask] = useState('deep research AI safety, and make summary');
  const [executionPlan, setExecutionPlan] = useState<ExecutionPlan | null>(null);
  const [finalAnswer, setFinalAnswer] = useState<string | null>(null);
  const [status, setStatus] = useState<'idle' | 'planning' | 'executing' | 'done' | 'error'>('idle');
  const [error, setError] = useState<string | null>(null);

  const runTask = async (taskQuery: string) => {
    // 1. Reset states and start planning
    setStatus('planning');
    setError(null);
    setExecutionPlan(null);
    setFinalAnswer(null);

    try {
      // 2. Create the execution plan
      const planResponse = await fetch('/api/mcp-link', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          jsonrpc: '2.0',
          id: Date.now(),
          method: 'tools/call',
          params: { name: 'create_execution_plan', arguments: { task: taskQuery } }
        }),
      });
      const planData = await planResponse.json();
      if (planData.error) throw new Error(planData.error.message);
      
      setExecutionPlan(planData.result);

      // 3. Execute the plan
      setStatus('executing');
      const execResponse = await fetch('/api/mcp-link', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          jsonrpc: '2.0',
          id: Date.now(),
          method: 'tools/call',
          params: { name: 'execute_prompt_chain', arguments: { prompts: planData.result.prompts } }
        }),
      });

      if (!execResponse.ok) {
        throw new Error(`HTTP error! status: ${execResponse.status}`);
      }

      const reader = execResponse.body?.getReader();
      if (!reader) {
        throw new Error('Failed to get response reader');
      }

      const decoder = new TextDecoder();
      let done = false;
      while (!done) {
        const { value, done: readerDone } = await reader.read();
        done = readerDone;
        const chunk = decoder.decode(value, { stream: true });
        
        // Process server-sent events
        const events = chunk.split('\n\n');
        for (const event of events) {
          if (event.startsWith('data:')) {
            const dataStr = event.substring(5);
            try {
              const data = JSON.parse(dataStr);
              if (data.type === 'result') {
                setFinalAnswer(data.data.finalAnswer);
                setStatus('done');
              }
              // You can add more event handlers here (e.g., for 'progress' or 'log')
            } catch (e) {
              console.error('Failed to parse stream data chunk', e);
            }
          }
        }
      }

    } catch (err) {
      const message = err instanceof Error ? err.message : 'An unknown error occurred.';
      console.error("MCP Execution Error:", message);
      setError(message);
      setStatus('error');
    }
  };

  const isLoading = status === 'planning' || status === 'executing';

  return (
    <div className="container mx-auto p-4 sm:p-6 md:p-8 max-w-4xl">
      <div className="text-center mb-8">
    
[truncated — 2402 more characters]
```

### src/app/(public)/login/page.tsx

```typescript
'use client';

import AuthForm from "@/components/ui/AuthForm";

export default function LoginPage() {
  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50">
      <AuthForm mode="login" />
    </div>
  );
} 
```

### src/app/(public)/signup/page.tsx

```typescript
'use client';

import AuthForm from "@/components/ui/AuthForm";

export default function SignupPage() {
  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50">
      <AuthForm mode="signup" />
    </div>
  );
} 
```

[24 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]