context-drop 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/MIT-LICENSE +21 -0
  2. package/README.md +710 -2
  3. package/app/assets/javascripts/context_drop/context_drop.js +9949 -0
  4. package/dist/app/javascript/context_drop/api-client.d.ts +53 -0
  5. package/dist/app/javascript/context_drop/api-client.js +470 -0
  6. package/dist/app/javascript/context_drop/element-picker.d.ts +111 -0
  7. package/dist/app/javascript/context_drop/element-picker.js +1428 -0
  8. package/dist/app/javascript/context_drop/icons.d.ts +34 -0
  9. package/dist/app/javascript/context_drop/icons.js +34 -0
  10. package/dist/app/javascript/context_drop/index.d.ts +7 -0
  11. package/dist/app/javascript/context_drop/index.js +9 -0
  12. package/dist/app/javascript/context_drop/markdown.d.ts +7 -0
  13. package/dist/app/javascript/context_drop/markdown.js +129 -0
  14. package/dist/app/javascript/context_drop/sanitizer.d.ts +38 -0
  15. package/dist/app/javascript/context_drop/sanitizer.js +769 -0
  16. package/dist/app/javascript/context_drop/screenshot.d.ts +21 -0
  17. package/dist/app/javascript/context_drop/screenshot.js +245 -0
  18. package/dist/app/javascript/context_drop/styles.d.ts +1 -0
  19. package/dist/app/javascript/context_drop/styles.js +2196 -0
  20. package/dist/app/javascript/context_drop/types.d.ts +316 -0
  21. package/dist/app/javascript/context_drop/types.js +1 -0
  22. package/dist/app/javascript/context_drop/widget.d.ts +206 -0
  23. package/dist/app/javascript/context_drop/widget.js +3752 -0
  24. package/dist/src/cli.d.ts +3 -0
  25. package/dist/src/cli.js +207 -0
  26. package/dist/src/index.d.ts +5 -0
  27. package/dist/src/index.js +5 -0
  28. package/dist/src/mcp/dispatcher.d.ts +42 -0
  29. package/dist/src/mcp/dispatcher.js +895 -0
  30. package/dist/src/mcp/environment-router.d.ts +38 -0
  31. package/dist/src/mcp/environment-router.js +174 -0
  32. package/dist/src/mcp/index.d.ts +24 -0
  33. package/dist/src/mcp/index.js +75 -0
  34. package/dist/src/mcp/remote-client.d.ts +25 -0
  35. package/dist/src/mcp/remote-client.js +98 -0
  36. package/dist/src/next/index.d.ts +13 -0
  37. package/dist/src/next/index.js +25 -0
  38. package/dist/src/next/server.d.ts +1 -0
  39. package/dist/src/next/server.js +1 -0
  40. package/dist/src/react/index.d.ts +104 -0
  41. package/dist/src/react/index.js +144 -0
  42. package/dist/src/server/handler.d.ts +48 -0
  43. package/dist/src/server/handler.js +1180 -0
  44. package/dist/src/server/index.d.ts +8 -0
  45. package/dist/src/server/index.js +8 -0
  46. package/dist/src/server/sanitizer.d.ts +15 -0
  47. package/dist/src/server/sanitizer.js +201 -0
  48. package/dist/src/server/storage/local.d.ts +22 -0
  49. package/dist/src/server/storage/local.js +827 -0
  50. package/dist/src/server/storage/memory.d.ts +8 -0
  51. package/dist/src/server/storage/memory.js +387 -0
  52. package/dist/src/server/storage/postgres.d.ts +27 -0
  53. package/dist/src/server/storage/postgres.js +629 -0
  54. package/dist/src/server/types.d.ts +227 -0
  55. package/dist/src/server/types.js +7 -0
  56. package/dist/src/server/upload-validator.d.ts +16 -0
  57. package/dist/src/server/upload-validator.js +196 -0
  58. package/dist/src/widget/index.d.ts +1 -0
  59. package/dist/src/widget/index.js +1 -0
  60. package/package.json +99 -4
package/README.md CHANGED
@@ -1,3 +1,711 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/kemalelmizan/context-drop/main/docs/images/context-drop-hero.svg" alt="ContextDrop, Self-hosted contextual feedback engine, tactile DOM pin-drop widget, and IDE MCP server for Ruby on Rails" width="100%" />
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ <p align="center">
6
+ <strong>Stop decoding vague bug reports! Let users pin the problem and fix it right beside your app</strong><br />
7
+ <a href="#nextjs--react-quickstart">Next.js</a> · <a href="#quickstart-ruby-on-rails">Rails</a> · <a href="#mcp">MCP</a>
8
+ </p>
9
+
10
+ <p align="center">
11
+ <a href="https://www.npmjs.com/package/context-drop"><img src="https://img.shields.io/npm/v/context-drop?label=NPM&color=cb3837&logo=npm" alt="NPM Version" /></a>
12
+ <a href="https://rubygems.org/gems/context_drop"><img src="https://img.shields.io/gem/v/context_drop?label=RubyGems&color=2563eb" alt="Gem Version" /></a>
13
+ <a href="https://rubygems.org/gems/context_drop"><img src="https://img.shields.io/gem/dt/context_drop?label=Downloads&color=0f172a" alt="Gem Downloads" /></a>
14
+ <a href="MIT-LICENSE"><img src="https://img.shields.io/badge/License-MIT-16a34a" alt="MIT License" /></a>
15
+ </p>
16
+
17
+ <p align="center">
18
+ <a href="https://www.npmjs.com/package/context-drop">NPM</a> ·
19
+ <a href="https://rubygems.org/gems/context_drop">RubyGems</a> ·
20
+ <a href="#nextjs--react-quickstart">Next.js Quickstart</a> ·
21
+ <a href="#quickstart">Rails Quickstart</a> ·
22
+ <a href="#environment-adaptive-workflow">3-Tier Workflow</a> ·
23
+ <a href="#interactive-playground">Live Demo</a> ·
24
+ <a href="#smart--verbose-element-selection">Smart &amp; Verbose Selectors</a> ·
25
+ <a href="#mcp">Unified MCP Hub</a> ·
26
+ <a href="#zero-trust-privacy--redaction">Privacy &amp; Redaction</a> ·
27
+ <a href="#configuration">Configuration</a>
28
+ </p>
29
+
30
+ ---
31
+
32
+ ## Why
33
+
34
+ When someone reports *"the button on the checkout card isn't working,"* engineers usually spend 20 minutes hunting down which view partial, feature flag, viewport width, or overlapping toast banner caused the problem.
35
+
36
+ **ContextDrop** (`context_drop`) embeds a tactile, zero-bleed **Shadow DOM book-corner launcher, environment-adaptive selector, and unified multi-environment MCP hub** directly into your Ruby on Rails application (`Rails >= 7.1`, including `Rails 8+`):
37
+ - **Minimal Book-Corner Launcher → Peel-to-Pin on Drag:** Rests quietly as a `38×38px` folded page corner. **Click** the book corner to open the feedback form (or, when opted-in locally, the docked Agentic Sidebar); **drag** the book corner to peel and animate it into a live pushpin over any part of the page—or snap it to another viewport corner.
38
+ - **3-Tier Environment-Adaptive UX (`production` · `staging` · `local`):** Automatically adapts to `Rails.env`—giving **production** end-users a compact, jargon-free **Smart Component Selector** with automatic surrounding-context screenshots, and giving **staging/QA** teams and **local** developers the verbose `v0.1.x` CSS/layer inspector.
39
+ - **MCP-First Workflow for Developers:** Keep your active coding in your preferred editor (**Antigravity**, **Cursor**, **Claude Code**, **VS Code**). Register **one** local MCP server (`bin/rails context_drop:mcp`) in your IDE to query and resolve feedback with multimodal screenshots across `local`, `staging`, and `production` simultaneously.
40
+ - **Opt-in Local BYOK Agentic Sidebar:** Want an agent right in the browser? Flip `config.enable_local_agent = true` in development to unlock the docked in-browser agent sidebar with human-approved file diffs.
41
+
42
+ ---
43
+
44
+ ## Environment-Adaptive Workflow
45
+
46
+ Different environments serve completely different people:
47
+ - **Production users** shouldn't be overwhelmed with `#css.selectors`, pixel dimensions (`681×350`), overlapping DOM layer counters, or `<kbd>⌥⇧P</kbd>` shortcuts just to report a bug. They need a rapid, clutter-free way to point at an issue.
48
+ - **Staging & QA teams** need surgical leaf/layer inspection, mouse-wheel layer scrubbing, and exact geometry coordinates.
49
+ - **Local developers** want two things:
50
+ 1. **In-browser testing:** The exact same verbose DOM inspector as staging to verify element pinning and capture payloads on `localhost`.
51
+ 2. **Active resolution in their IDE:** Powerful **MCP resources & tools** so their preferred AI coding agents (**Antigravity**, **Cursor**, **Claude Code**, **VS Code**) can query, analyze, and resolve bug reports without forcing development into a browser sidebar. For teams that do want an in-page browser agent, ContextDrop includes an experimental **BYOK Agentic Sidebar** enabled via `config.enable_local_agent = true`.
52
+
53
+ ContextDrop automatically adapts its UI, copy, and selector behavior from your host `Rails.env` (and loopback connection check) with **zero per-environment view templates**:
54
+
55
+ ```mermaid
56
+ flowchart TD
57
+ Boot["&lt;%= context_drop_widget %&gt;\nReads Host Rails.env + Request Loopback"] --> CheckEnv{"Host Environment?"}
58
+
59
+ CheckEnv -->|"Rails.env.production?\n(selection_mode = smart)"| Prod["1. Production · Quick User Feedback\n• Compact 356px 'Send Feedback' card\n• Smart Component Promotion (no raw spans/selectors)\n• Plain-language labels (“Complete Order” button)\n• Auto-captured redacted surrounding screenshot"]
60
+
61
+ CheckEnv -->|"staging / qa\n(selection_mode = verbose)"| Staging["2. Staging & QA · Verbose Inspector (v0.1.x)\n• Full 404px ContextDrop composer\n• Exact <tag#id.class> & pixel geometry HUD\n• Mouse-wheel overlapping layer scrubbing\n• ⌥⇧P Freeze & Pin + multi-element pinning"]
62
+
63
+ CheckEnv -->|"Rails.env.development?\non 127.0.0.1 / ::1"| LocalCheck{"config.enable_local_agent?"}
64
+
65
+ LocalCheck -->|"false (Default)\nIDE MCP Workflow"| LocalVerbose["3a. Local (Default) · Verbose Inspector + MCP\n• Full 404px floating feedback composer\n• Verbose DOM element picker & layer scrubbing\n• Developer uses their IDE agent via bin/rails context_drop:mcp\n• Full MCP resources across local + staging + production"]
66
+
67
+ LocalCheck -->|"true (Opt-in)\nExperimental"| LocalAgent["3b. Local (Opt-in) · BYOK Agentic Sidebar\n• Antigravity / VS Code-style docked sidebar\n• Agent | Feedback mode switcher (verbose pin)\n• Pulls local + staging + production MCP feedbacks\n• Read-only workspace tools + human diff approval"]
68
+ ```
69
+
70
+ ### How Each Environment Behaves
71
+
72
+ | Tier | Host Condition | Surface & Size | Selector Behavior (`selection_mode`) | Screenshot Behavior | Copy & Controls Shown to User |
73
+ |---|---|---|---|---|---|
74
+ | **1. Production** *(End-Users)* | `Rails.env.production?` | **Compact Quick-Feedback Card** (`356px`, clutter-free) | **`"smart"`** — Coarsely promotes hovered/dropped `<span>`/`<svg>` leaves to the nearest meaningful UI component (button, link, field, card, banner, dialog, row). Single click selects & reopens the form immediately. | **Automatic surrounding context** (`~84px` neighborhood, min `340×220px`, `[REDACTED]`-safe) merged into **one** clean preview card. | Plain human labels (`“Complete Order” button`, `“Enterprise Plan” card`), `Send Feedback`, `Select area`, `Add image`. **Zero CSS selectors, pixel metrics, wheel layer lists, or `<kbd>` badges.** |
75
+ | **2. Staging / QA** *(Technical Triage)* | `staging`, `qa`, or non-loopback `development` | **Verbose Inspector Chatbox** (`404px`, `v0.1.x` style) | **`"verbose"`** — Exact leaf/ancestor/overlap inspection with scroll-wheel layer scrubbing (`1/6 layers`), `ArrowUp`/`ArrowDown` stepping, `⌥⇧P` Freeze & Pin, and multi-pin mode. | Manual **Viewport Screenshot** button + per-pin **Element Crop** camera icon (`Shot` & `Pin` chips). | Technical HUD (`button#pay-btn · 180×42`), `Pin Element`, `<kbd>⌥⇧P</kbd>`, `<kbd>Space</kbd>`, `Dropped #42`. |
76
+ | **3. Local Development** *(Default · IDE MCP Focus)* | `Rails.env.development?` *(default: `enable_local_agent = false`)* | **Verbose Inspector Chatbox** (`404px`, identical to staging) | **`"verbose"`** — Exact leaf/ancestor inspection, layer scrubbing, and coordinate pinning to test feedback capture locally. | Manual Viewport Screenshot + per-pin Element Crop camera icon. | Technical HUD (`button#pay-btn · 180×42`), `Pin Element`, `<kbd>⌥⇧P</kbd>`, `<kbd>Space</kbd>`. Feedbacks feed directly into your IDE coding agents via `bin/rails context_drop:mcp`. |
77
+ | **4. Local Agentic Sidebar** *(Opt-in · Experimental)* | `Rails.env.development?` on loopback **and** `config.enable_local_agent = true` | **Docked BYOK Agentic Coding Sidebar** (`100dvh`, resizable `360–920px`, `Left`/`Right` + Push Layout) | **`"verbose"`** + live workspace file search (`Agent | Feedback` toggle lets you switch between agent and feedback modes). | Attaches live DOM pins & redacted screenshots directly to LLM prompts + pulls remote `staging`/`production` screenshots. | Provider/Model pill, encrypted **BYOK** vault, cross-env **Feedbacks** inbox, tool traces, and human-approved unified diffs (`Apply Change` / `Revert`). |
78
+
79
+ > [!TIP]
80
+ > **Zero Signal Lost in Production!** Even though production users only see friendly labels like `“Complete Order” button` and an automatic surrounding-context screenshot, ContextDrop still captures the full sanitized `selector` (`#checkout-btn`), `dom_path`, `bounding_rect`, `metadata.friendly_label`, and `metadata.original_target_selector` (`span.inner-label`) under the hood—so engineers triaging `production:108` in their IDE via MCP get 100% exact technical coordinates. Need verbose mode in an internal-only production tool (or smart mode in staging)? Override `config.selection_mode = :verbose` or `:smart` in `config/initializers/context_drop.rb`.
81
+
82
+ <p align="center">
83
+ <img src="https://raw.githubusercontent.com/kemalelmizan/context-drop/main/docs/images/demo-pinning-layers.jpg" alt="ContextDrop Pin Mode highlighting an overlapping DOM layer with live dimensions and the Compact Pinning Bar" width="100%" />
84
+ </p>
85
+
86
+ > **Above:** Active **Pin Mode** on the live demo page. While hovering over a stacked UI card (`section #scenario-overlapping-layers · 681×350 · 1/6 layers`), ContextDrop frames the target in Inspector Cobalt, displays layer depth for mouse-wheel cycling, and collapses the chatbox into the **Compact Pinning Bar** (`Pinning`, live DOM ancestor breadcrumbs, Up/Down layer controls, and `Chat` toggle) so the host page stays completely unobstructed.
87
+
88
+ <table>
89
+ <thead>
90
+ <tr>
91
+ <th width="50%" align="left">1. Click or Peel the Book-Corner Launcher</th>
92
+ <th width="50%" align="left">2. Pin DOM Layers &amp; Capture Element Screenshots</th>
93
+ </tr>
94
+ </thead>
95
+ <tbody>
96
+ <tr>
97
+ <td valign="top">
98
+ <img src="https://raw.githubusercontent.com/kemalelmizan/context-drop/main/docs/images/demo-chatbox-composer.jpg" alt="ContextDrop floating chatbox composer with top-left Pin Element trigger and toolbar" width="100%" />
99
+ <p>
100
+ Drop <code>&lt;%= context_drop_widget %&gt;</code> into your layout to render a flush <code>38×38px</code> folded <strong>Book Corner</strong>. Click the corner to open the normal feedback chatbox (or docked local Agentic Sidebar), or drag the corner to morph it into a pushpin and drop it straight onto an element.
101
+ </p>
102
+ </td>
103
+ <td valign="top">
104
+ <img src="https://raw.githubusercontent.com/kemalelmizan/context-drop/main/docs/images/demo-pinned-element-chip.png" alt="ContextDrop chatbox with a pinned DOM element chip, camera screenshot button, and confirmation banner" width="100%" />
105
+ <p>
106
+ Every pinned element is added to the context tray (`#scenario-overlapping-layers`) with a live count badge (`Pin Element 1`). Hover the chip to highlight the element on the page, click the camera icon to crop a screenshot of that exact node, and hit <strong>Send</strong>.
107
+ </p>
108
+ </td>
109
+ </tr>
110
+ </tbody>
111
+ </table>
112
+
113
+ ---
114
+
115
+ ## Why ContextDrop
116
+
117
+ | Capability | Typical SaaS Feedback Widgets | Manual Slack / Issue Reports | **ContextDrop (`context_drop`)** |
118
+ |---|---|---|---|
119
+ | **Data & Storage Ownership** | Exfiltrates DOM & screenshots to 3rd-party cloud servers | Scattered across chat threads | **100% self-hosted** in your Rails DB (`context_drop_*`) & **Active Storage** |
120
+ | **Overlapping DOM Layers** | Gets stuck on topmost wrapper, modal backdrop, or toast | Requires reporter to open DevTools | **Scroll-wheel depth cycling**, **Click-to-Pick Layer Popover**, & **DOM Breadcrumbs** |
121
+ | **Host Page Safety** | Injects global CSS; clicks can accidentally fire host buttons | N/A | **Strict Shadow DOM isolation** + capture-phase event suppression during Pin Mode |
122
+ | **Sensitive Data Protection** | Captures raw DOM or requires complex PII scrubbing rules | Risk of unredacted screenshots | **Zero-trust redaction** before rasterization (`[data-feedback-sensitive]`, passwords, cards) |
123
+ | **Authentication Model** | Separate vendor accounts & seats | Manual identity lookup | **Host-agnostic polymorphic `submitter`** (Devise, Rails 8 Auth, Sorcery, custom, or anonymous) |
124
+ | **Developer Resolution Flow** | Copy-paste from external vendor dashboard | Back-and-forth reproduction questions | **Local BYOK Agentic Sidebar** + **Single Unified Multi-Env MCP Server** (`local` + `staging` + `production`) + **Rails Triage Dashboard** |
125
+
126
+ > [!IMPORTANT]
127
+ > **Core Architectural Principle: ContextDrop owns its domain. Your Rails app owns its identity and infrastructure.**
128
+ > ContextDrop mounts cleanly as an isolated Rails Engine (`isolate_namespace ContextDrop`) with zero mandatory frontend framework dependencies (no React, Vue, or Tailwind required).
129
+
130
+ ---
131
+
132
+ ## Next.js & React Quickstart
133
+
134
+ ContextDrop ships as a **zero-dependency** NPM package ([`context-drop`](https://www.npmjs.com/package/context-drop)) supporting both **standalone full-stack Next.js** (App Router & Pages Router + pluggable storage + `npx context-drop mcp`) and **decoupled Next.js / React frontends** connected to a Ruby on Rails `context_drop` backend.
135
+
136
+ ### 1. Install & Scaffold Route Handler
137
+
138
+ ```bash
139
+ npm install context-drop
140
+ npx context-drop init
141
+ ```
142
+
143
+ `npx context-drop init` auto-detects **App Router** (`app/api/context-drop/[[...path]]/route.ts`) or **Pages Router** (`pages/api/context-drop/[[...path]].ts`) and adds `.context-drop/` to `.gitignore`:
144
+
145
+ ```ts
146
+ // app/api/context-drop/[[...path]]/route.ts
147
+ import { createContextDropNextHandler } from "context-drop/next/server";
148
+
149
+ export const { GET, POST, OPTIONS } = createContextDropNextHandler({
150
+ // Zero-config local default stores SQLite/JSON + redacted screenshots in .context-drop/
151
+ mcp: {
152
+ enabled: Boolean(process.env.CONTEXT_DROP_MCP_API_KEY),
153
+ apiKey: process.env.CONTEXT_DROP_MCP_API_KEY
154
+ }
155
+ });
156
+ ```
157
+
158
+ ### 2. Mount `<ContextDrop />` in Your Root Layout
159
+
160
+ `context-drop/next` includes `"use client"` out of the box—drop `<ContextDrop />` directly into your Server Component `app/layout.tsx` with zero wrapper boilerplate and zero hydration mismatches:
161
+
162
+ ```tsx
163
+ // app/layout.tsx
164
+ import { ContextDrop } from "context-drop/next";
165
+
166
+ export default function RootLayout({ children }: { children: React.ReactNode }) {
167
+ return (
168
+ <html lang="en">
169
+ <body>
170
+ {children}
171
+ <ContextDrop
172
+ position="bottom_right"
173
+ metadata={{ release: process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA }}
174
+ />
175
+ </body>
176
+ </html>
177
+ );
178
+ }
179
+ ```
180
+
181
+ Want to open ContextDrop from your own navbar or help menu? Call `useContextDrop()` from any client component:
182
+
183
+ ```tsx
184
+ "use client";
185
+ import { useContextDrop } from "context-drop/next";
186
+
187
+ export function ReportBugButton() {
188
+ const { open } = useContextDrop();
189
+ return <button onClick={open}>Report an issue</button>;
190
+ }
191
+ ```
192
+
193
+ ### 3. Connect Your IDE Coding Agent via MCP (`npx context-drop mcp`)
194
+
195
+ Register **one** unified `stdio` MCP server in `.mcp.json` (Claude Code), `~/.cursor/mcp.json` (Cursor), or `mcp_config.json` (Antigravity / Windsurf). It automatically loads `.env.local` / `.env` and federates `local` + remote `staging` & `production` Next.js (or Rails!) deployments:
196
+
197
+ ```json
198
+ {
199
+ "mcpServers": {
200
+ "context-drop": {
201
+ "command": "npx",
202
+ "args": ["context-drop", "mcp"],
203
+ "env": {
204
+ "CONTEXT_DROP_STAGING_MCP_URL": "https://staging.your-app.com/api/context-drop/mcp",
205
+ "CONTEXT_DROP_STAGING_MCP_API_KEY": "your-staging-mcp-bearer-token",
206
+ "CONTEXT_DROP_PRODUCTION_MCP_URL": "https://your-app.com/api/context-drop/mcp",
207
+ "CONTEXT_DROP_PRODUCTION_MCP_API_KEY": "your-production-mcp-bearer-token"
208
+ }
209
+ }
210
+ }
211
+ }
212
+ ```
213
+
214
+ ### 4. Production Storage Adapters (PostgreSQL, S3 / Vercel Blob, or Custom ORM)
215
+
216
+ Locally, ContextDrop works with zero configuration using Node's built-in SQLite (`node:sqlite`, or atomic JSON fallback) inside `.context-drop/`. For staging and production Next.js deployments (Vercel, Fly, AWS, Render, Railway), plug in `createPostgresStorageAdapter` (compatible with `pg.Pool`, `@vercel/postgres`, Neon, and Supabase) or implement the `StorageAdapter` interface for Prisma / Drizzle:
217
+
218
+ ```ts
219
+ // app/api/context-drop/[[...path]]/route.ts
220
+ import { Pool } from "pg";
221
+ import {
222
+ createContextDropNextHandler,
223
+ createPostgresStorageAdapter
224
+ } from "context-drop/next/server";
225
+
226
+ const pool = new Pool({ connectionString: process.env.DATABASE_URL });
227
+
228
+ export const { GET, POST, OPTIONS } = createContextDropNextHandler({
229
+ storage: createPostgresStorageAdapter({
230
+ pool,
231
+ autoMigrate: true // Creates context_drop_* tables automatically if missing
232
+ // Optional blobStore: { putBlob, getBlob, deleteBlob } for S3 / R2 / Vercel Blob
233
+ }),
234
+ resolveSubmitter: async (request) => {
235
+ // Optional: attach your NextAuth / Clerk / Supabase user identity
236
+ return null;
237
+ },
238
+ mcp: {
239
+ enabled: true,
240
+ apiKey: process.env.CONTEXT_DROP_MCP_API_KEY
241
+ }
242
+ });
243
+ ```
244
+
245
+ ### 5. Connecting Next.js to a Ruby on Rails Backend
246
+
247
+ Already running `ContextDrop::Engine` on Rails? Point `<ContextDrop />` at your Rails mount path:
248
+ - **Via Next.js Rewrites (Same-Origin, Recommended):** Proxy `/context_drop/:path*` to your Rails API in `next.config.ts` and render `<ContextDrop endpoint="/context_drop" />`.
249
+ - **Cross-Origin CORS:** Add `config.allowed_origins = ["http://localhost:3000", "https://app.example.com"]` in `config/initializers/context_drop.rb` and render `<ContextDrop endpoint="https://api.example.com/context_drop" credentials="include" />`.
250
+
251
+ ### NPM Package Exports Reference
252
+
253
+ | Import Path | Environment | Exports |
254
+ |---|---|---|
255
+ | `context-drop/next` | Client (`"use client"`) | Next.js `<ContextDrop />`, `<ContextDropWidget />`, `useContextDrop()` (defaults to `/api/context-drop`) |
256
+ | `context-drop/next/server` | Node / Server | `createContextDropNextHandler`, `createContextDropPagesHandler`, `createContextDropFetchHandler`, `createLocalStorageAdapter`, `createPostgresStorageAdapter`, `createMemoryStorageAdapter` |
257
+ | `context-drop/react` | Client (`"use client"`) | Framework-agnostic React `<ContextDrop />`, `useContextDrop()` (defaults to `/context_drop`) |
258
+ | `context-drop/mcp` | Node / Server | `createContextDropMcpServer`, `runContextDropMcpStdio`, `ContextDropMcpDispatcher`, `EnvironmentRouter` |
259
+ | `context-drop/widget` | Browser | Auto-registering `<context-drop-widget>` Web Component & `ContextDropApiClient` |
260
+ | `context-drop/bundle` | Browser IIFE | Self-contained `<script>` bundle (`context_drop.js`) |
261
+ | `npx context-drop` | CLI | `npx context-drop mcp` (stdio MCP server) & `npx context-drop init` (Next.js scaffolder) |
262
+
263
+ ---
264
+
265
+ ## Quickstart (Ruby on Rails)
266
+
267
+ ### Requirements
268
+
269
+ - **Ruby** `>= 3.1`
270
+ - **Ruby on Rails** `>= 7.1` (`7.1`, `7.2`, `8.0+`)
271
+ - **Active Storage** installed in the host application (`bin/rails active_storage:install`)
272
+
273
+ ### 1. Install the Gem & Run the Generator
274
+
275
+ Install [`context_drop` from RubyGems.org](https://rubygems.org/gems/context_drop) (or add `gem "context_drop"` to your `Gemfile`):
276
+
277
+ ```bash
278
+ bundle add context_drop
279
+ bin/rails generate context_drop:install
280
+ bin/rails db:migrate
281
+ ```
282
+
283
+ What `bin/rails generate context_drop:install` sets up for you:
284
+ 1. Creates [`config/initializers/context_drop.rb`](lib/generators/context_drop/install/templates/initializer.rb.tt).
285
+ 2. Mounts `mount ContextDrop::Engine => "/context_drop"` in `config/routes.rb`.
286
+ 3. Copies four engine-owned migrations (`context_drop_feedbacks` with `environment` attribution, `context_drop_element_references`, `context_drop_attachments`) into `db/migrate/`.
287
+ 4. Verifies that Active Storage migrations are present.
288
+
289
+ ### 2. Render the Widget in Your Layout
290
+
291
+ Add `<%= context_drop_widget %>` right before `</body>` in `app/views/layouts/application.html.erb`:
292
+
293
+ ```erb
294
+ <%= context_drop_widget %>
295
+ ```
296
+
297
+ Need page-specific copy or release metadata? Override options per view without mutating global configuration:
298
+
299
+ ```erb
300
+ <%= context_drop_widget(
301
+ position: :bottom_left,
302
+ placeholder: "Spot an issue with checkout? Pin the element and let us know...",
303
+ metadata: { release: ENV["GIT_COMMIT_SHA"], feature_flag: "checkout_v2" }
304
+ ) %>
305
+ ```
306
+
307
+ ### 3. Enable & Launch
308
+
309
+ ```bash
310
+ export CONTEXT_DROP_ENABLED=true
311
+ bin/rails server
312
+ ```
313
+
314
+ Visit any page in your Rails app to use the floating widget, or open `/context_drop/dashboard/feedbacks` to triage submissions.
315
+
316
+ ---
317
+
318
+ ## Interactive Playground
319
+
320
+ Want to test all three environment modes (`local (Agent)` · `staging (Verbose)` · `production (Smart)`), peel-to-pin corner dragging, smart component promotion with auto surrounding screenshots, overlapping-layer disambiguation, and the live payload inspector before installing the gem into a Rails app? Run the standalone playground in this repository:
321
+
322
+ ```bash
323
+ # Start the local interactive demo server at http://127.0.0.1:4173
324
+ npm run demo
325
+
326
+ # Or open demo/index.html directly in your browser (works offline via built-in payload interceptor)
327
+ open demo/index.html
328
+ ```
329
+
330
+ Use the top-bar switcher in the demo to flip live between **Local (Agent Sidebar)**, **Staging (Verbose Inspector)**, and **Production (Smart Quick-Feedback)**.
331
+
332
+ ---
333
+
334
+ ## Feedback-to-Fix Loop
335
+
336
+ ```mermaid
337
+ flowchart LR
338
+ subgraph Browser["Host Rails App (Browser)"]
339
+ Widget["<context-drop-widget>\n(Book-Corner + Layer Picker\n+ Local Agentic Sidebar)"]
340
+ end
341
+
342
+ subgraph Engine["ContextDrop::Engine (Local Development Rails App)"]
343
+ Controller["FeedbacksController\n+ AgentController (Loopback Only)"]
344
+ DB[("Local DB + Active Storage\n(environment = development)")]
345
+ MCP["Unified MCP Hub\nbin/rails context_drop:mcp"]
346
+ end
347
+
348
+ subgraph Remote["Staging & Production Rails Apps"]
349
+ RemoteMCP["Streamable HTTP /context_drop/mcp\n(environment = staging | production)"]
350
+ end
351
+
352
+ subgraph IDE["Developer IDE / Coding Agent"]
353
+ Agent["Cursor · Claude Code · Antigravity\nWindsurf · VS Code"]
354
+ end
355
+
356
+ Widget -->|"POST /context_drop/feedback"| Controller
357
+ Widget <-->|"BYOK Chat + Diff Approval\n(development + 127.0.0.1 only)"| Controller
358
+ Controller --> DB
359
+ DB --> MCP
360
+ RemoteMCP <-->|"Bearer HTTPS Federation\n(EnvironmentRouter)"| MCP
361
+ MCP -->|"Single MCP Server\n(environment: all | local | staging | prod)"| Agent
362
+ ```
363
+
364
+ Every submission captures a rich, sanitized engineering payload:
365
+ - **`ContextDrop::Feedback` (`context_drop_feedbacks`):** Automatic host `environment` (`Rails.env`—e.g. `development`, `staging`, `production`), polymorphic `submitter` (`User`, `Employee`, `AdminUser`, or anonymous), `message`, `page_url`, `user_agent`, `viewport` & custom `metadata`, and workflow `status` (`new`, `reviewed`, `resolved`, `dismissed`).
366
+ - **`ContextDrop::ElementReference` (`context_drop_element_references`):** Point-in-time DOM snapshot including `tag_name`, best-effort CSS `selector`, structural `dom_path`, truncated `text_content`, allowlisted `attributes_snapshot` (`id`, `class`, `role`, `aria-*`, `data-testid`), and CSS pixel `bounding_rect` (`{ x, y, width, height }`).
367
+ - **`ContextDrop::Attachment` (`context_drop_attachments`):** Viewport screenshots, element-cropped screenshots (linked via `element_reference_id`), and uploaded images stored in your app's **Active Storage**.
368
+
369
+ ---
370
+
371
+ ## Smart & Verbose Element Selection
372
+
373
+ ContextDrop stays tucked away as a `38×38px` folded **Book Corner** until needed—**click** the corner to open the feedback surface, or **drag** the corner to peel and morph it into a pushpin over any part of the page (or drop it into another viewport corner to re-dock). All `pointerdown`, `mousedown`, `mouseup`, and `click` events are intercepted in the capture phase while selecting so host links, buttons, and forms never fire by mistake.
374
+
375
+ Once selecting, ContextDrop tailors precision and verbosity to the active environment (`config.selection_mode = :auto`):
376
+
377
+ ### 1. Production: Smart Component Selector (`selection_mode = "smart"`)
378
+
379
+ Optimized for speed, compactness, and non-technical end-users—being slightly coarse on hover is intentional because ContextDrop pairs the component with a wide neighborhood screenshot:
380
+ - **Automatic Component Promotion:** Hovering or dropping on inner leaf nodes (`<span>`, `<svg>`, `<strong>`, icon wrappers) automatically promotes the highlight to the nearest meaningful UI unit—such as a `button`, `link`, `input` field, `card`, `banner`, `dialog`, `form`, `navigation` bar, `table row`, or bounded `section`.
381
+ - **Plain-Language Labels Only:** The hover pill and composer show human-friendly descriptions (`“Complete Order” button`, `“Enterprise Plan” card`)—never `#id.class` strings, `681×350` pixel readouts, layer counters, wheel-scrubbing interception, or `<kbd>` shortcut hints.
382
+ - **Automatic Surrounding-Context Screenshot:** A single click selects the component, automatically captures a privacy-redacted neighborhood screenshot (`smart_capture_padding = 84`, minimum `340×220px` clamped to viewport, framing the target component in Pin Vermilion), merges both into **one** clean preview card, and immediately reopens the compact `356px` **Send Feedback** form.
383
+ - **Full Technical Fidelity Preserved:** Under the hood, the submitted `ElementReference` still records the exact sanitized `selector`, `dom_path`, `bounding_rect`, `metadata.friendly_label`, `metadata.component_kind`, and `metadata.original_target_selector` alongside the linked `Attachment`.
384
+
385
+ ### 2. Staging, QA & Dev: Verbose Layer Inspector (`selection_mode = "verbose"`, `v0.1.x` Format)
386
+
387
+ Optimized for QA engineers, designers, and developers debugging dense, overlapping layouts (sticky navbars, floating ribbons, translucent toasts, nested Flexbox/Grid wrappers):
388
+ - **Exact `<tag#id.class>` & Geometry HUD:** Displays exact tag/selector identifiers, `tabular-nums` pixel dimensions (`681×350`), and overlapping candidate depth (`1/6 layers`).
389
+ - **Scroll-Wheel & Keyboard Depth Scrubbing:** Roll your mouse wheel (`wheel`) or press `ArrowUp` / `ArrowDown` (`[` / `]`) over any coordinate to cycle through `document.elementsFromPoint` overlapping layers, child nodes, and parent containers while keeping a dashed ghost outline on the original leaf node.
390
+ - **Freeze & Pin Transient Menus (`⌥⇧P`):** Press `Alt+Shift+P` (`⌥⇧P`) while a hover dropdown or tooltip is open to freeze the page coordinate and scrub/pin transient layers, or press `Space` / click to pin multiple elements in a single pass.
391
+
392
+ ---
393
+
394
+ ## Local BYOK Agentic Sidebar (`development` Opt-in)
395
+
396
+ > [!NOTE]
397
+ > **MCP-First Workflow by Default:** In v0.2.0, local development defaults to the **staging/verbose DOM inspector** (`config.enable_local_agent = false`) so you can test element pinning and feed bug reports directly to your preferred AI coding agent in your IDE (**Antigravity**, **Cursor**, **Claude Code**, **VS Code**) via the unified MCP server.
398
+ >
399
+ > If you prefer an integrated in-browser coding assistant, set `config.enable_local_agent = true` (or `CONTEXT_DROP_LOCAL_AGENT_ENABLED=true`) to enable the embedded sidebar.
400
+
401
+ When enabled (`config.enable_local_agent = true`) and running locally (`Rails.env.development?` on `localhost` / `127.0.0.1`), clicking or peeling the Book-Corner transforms ContextDrop into a full-height, resizable **Agentic Coding Sidebar**—similar to the coding sidebars in **Antigravity** and **VS Code**:
402
+
403
+ - **Dual `Agent | Feedback` Mode Switcher:** Triage bugs and edit local Rails code in **Agent** mode, or flip to **Feedback** mode at any time to preview and submit through the standard floating feedback chatbox.
404
+ - **Flexible Docked Layout:** Dock to the **Right** or **Left** edge, drag the resize handle (`360px–920px`, defaulting to `560px`), and toggle **Push Page Layout** so the sidebar sits side-by-side with your running app without covering content.
405
+ - **Dark & Light Theme Support:** Click the sun/moon switcher in the top bar to toggle between the crisp off-white light theme and the deep charcoal dark theme (`theme: :dark` or `data-theme="dark"`).
406
+ - **Cross-Environment Context Attachment:** Peel-and-drop live DOM elements and redacted screenshots from the current page, **and** attach bug reports directly from `local`, `staging`, or `production` via the built-in **Feedback Inbox** drawer.
407
+ - **Bring Your Own Key (BYOK):** Supports **Anthropic** (`Claude`), **Google Gemini**, **OpenAI**, and **Custom OpenAI-Compatible** endpoints (OpenRouter, Groq, Ollama, vLLM). Automatically detects local server environment variables (`ANTHROPIC_API_KEY`, `GEMINI_API_KEY` / `GOOGLE_API_KEY`, `OPENAI_API_KEY`, `CONTEXT_DROP_LLM_API_KEY`), or saves keys you enter in the sidebar's **BYOK Vault** drawer encrypted on disk (`AES-256-GCM`, mode `0600`) inside gitignored `tmp/context_drop_byok.enc`.
408
+
409
+ ### Defense-in-Depth Local Agent Safety
410
+
411
+ Because user-submitted feedback messages from `staging` or `production` are untrusted input, the Local Agentic Sidebar enforces five strict security walls:
412
+ 1. **Hard-Blocked Outside Local Development:** `/context_drop/agent/*` returns `404 Not Found` whenever `Rails.env.production?` is true, when `local_agent_enabled` is false, or when a request does not originate from strict loopback (`127.0.0.1` / `::1`) with a loopback `Host` header, same-origin headers, CSRF token, and `authorize_dashboard` permission.
413
+ 2. **Zero Browser Key Exposure:** API keys are **never** stored in `localStorage`, `sessionStorage`, cookies, or DOM attributes. Input fields are wiped immediately upon save, and `/agent/status` returns only masked tails (`••••••••7f9a`).
414
+ 3. **Workspace Root Jail & Secret Denylist:** File tools (`list_workspace_files`, `search_workspace`, `read_workspace_file`, `propose_file_edit`) enforce `File.realpath` containment inside `Rails.root` and block `.env*`, `config/master.key`, `config/credentials*`, `*.pem`, `*.key`, `tmp/context_drop_byok*`, `.git/config`, and `.git/hooks/*`.
415
+ 4. **No Arbitrary Shell Execution:** No `bash` / `sh` / `system` tool is exposed to LLM tool calls, eliminating prompt-injection command execution.
416
+ 5. **Human-Approved Inline Diffs + 1-Click Revert:** Proposed file edits are staged in memory and rendered as unified diff cards (`+N / -N`). Disk writes occur **only** when you click **Apply Change** (guarded by SHA-256 pre-image verification), with 1-click **Revert** afterward.
417
+
418
+ ---
419
+
420
+ ## MCP
421
+
422
+ ContextDrop ships with a built-in **Model Context Protocol (MCP)** server (`ContextDrop::MCP::Server`) so you or your AI coding agent can pull bug reports, inspect exact CSS selectors and DOM paths, view multimodal screenshots, and mark issues resolved without leaving your editor.
423
+
424
+ <p align="center">
425
+ <img src="https://raw.githubusercontent.com/kemalelmizan/context-drop/main/docs/images/demo-mcp-agent.png" alt="ContextDrop MCP server tool calls (list_feedbacks and get_feedback) and root-cause diagnosis inside an AI coding agent" width="100%" />
426
+ </p>
427
+
428
+ > **Above:** Triage flow inside an AI coding agent connected to the `context-drop` MCP server on the live playground. The agent invokes `list_feedbacks` (`{ status: "new" }`) and `get_feedback` (`{ id: 12, include_images: true }`), inspects both the structured `ElementReference` geometry (`button#upgrade-cluster-btn`, `169.1×33px`) and the redacted multimodal `image/png` screenshot block, and pinpoints the exact overlapping CSS rule in `demo/index.html`.
429
+
430
+ ### Exposed MCP Capabilities
431
+
432
+ | Type | Name / URI | Description |
433
+ |---|---|---|
434
+ | **Tool** | `list_environments` | List `local` (with current host `Rails.env`) plus all configured remote environments (`staging`, `production`, etc.) and connection status. |
435
+ | **Tool** | `list_feedbacks` | Filter & paginate submissions across `environment` (`"all"`, `"local"`, `"staging"`, `"production"`), `status` (`new`, `reviewed`, `resolved`, `dismissed`), `page_url`, or free-text `query`. Returns qualified IDs (`local:12`, `production:42`). |
436
+ | **Tool** | `get_feedback` | Fetch full `Feedback`, all `ElementReference` DOM snapshots, and inline base64 `image` blocks by `id` + `environment` or qualified ID (`"production:42"`). |
437
+ | **Tool** | `get_feedback_attachment` | Retrieve an individual local or remote `Attachment` record and its binary screenshot/image as an MCP `image` content block. |
438
+ | **Tool** | `update_feedback_status` | Transition a local or remote feedback record between `new`, `reviewed`, `resolved`, and `dismissed`. |
439
+ | **Resource** | `contextdrop://feedbacks/new` | Live JSON feed of unresolved `new` feedback records (up to 50 most recent). |
440
+ | **Resource** | `contextdrop://feedbacks/{id}` | Full JSON snapshot of a specific feedback submission, its pinned elements, and attachment metadata. |
441
+ | **Prompt** | `investigate_feedback` | Generates a structured root-cause investigation brief (with attached screenshots) for any local or remote `feedback_id` (`"staging:18"`). |
442
+
443
+ ---
444
+
445
+ ### Recommended Setup: One Unified MCP Server for All Environments (`local` + `staging` + `production`)
446
+
447
+ Instead of registering separate MCP servers per environment in your IDE, register **a single `context-drop` server** running `./bin/rails context_drop:mcp`. It automatically reads your local development database (`local`) **and** federates every remote environment configured in `config.mcp_environments` or `CONTEXT_DROP_<ENV>_MCP_URL` / `CONTEXT_DROP_<ENV>_MCP_API_KEY`:
448
+
449
+ ```json
450
+ {
451
+ "mcpServers": {
452
+ "context-drop": {
453
+ "command": "/bin/zsh",
454
+ "args": [
455
+ "-c",
456
+ "cd /absolute/path/to/your-rails-app && exec /Users/<you>/.rbenv/shims/bundle exec ./bin/rails context_drop:mcp"
457
+ ],
458
+ "env": {
459
+ "PATH": "/Users/<you>/.rbenv/shims:/Users/<you>/.rbenv/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
460
+ "CONTEXT_DROP_STAGING_MCP_URL": "https://staging.example.com/context_drop/mcp",
461
+ "CONTEXT_DROP_STAGING_MCP_API_KEY": "<staging-mcp-secret-token>",
462
+ "CONTEXT_DROP_PRODUCTION_MCP_URL": "https://app.example.com/context_drop/mcp",
463
+ "CONTEXT_DROP_PRODUCTION_MCP_API_KEY": "<production-mcp-secret-token>"
464
+ }
465
+ }
466
+ }
467
+ }
468
+ ```
469
+
470
+ > [!NOTE]
471
+ > **Prefer keeping URLs/tokens in Rails credentials or `.env.development.local`?** You can omit the `CONTEXT_DROP_*_MCP_*` entries from your IDE JSON entirely and configure `config.mcp_environments` inside `config/initializers/context_drop.rb`—both your IDE's `context-drop` MCP server and the in-browser Local Agentic Sidebar share the exact same `EnvironmentRouter`.
472
+
473
+ With one unified server registered in **Antigravity** (`mcp_config.json`), **Cursor** (`~/.cursor/mcp.json`), **Claude Code** (`.mcp.json`), **Windsurf**, or **VS Code**, you can ask naturally across environments:
474
+ - *"List new feedbacks across `all` environments on `context-drop`, inspect `production:42` with its screenshot, fix the CSS/ERB locally, and mark `production:42` resolved."*
475
+ - *"Check `local` feedbacks I just pinned and verify the layout fix."*
476
+
477
+ ---
478
+
479
+ ### Recommended Environment Matrix
480
+
481
+ | Environment | Host `Rails.env` Attribution | `CONTEXT_DROP_ENABLED` (Widget & Dashboard) | `CONTEXT_DROP_MCP_ENABLED` (HTTP `/mcp`) | Widget Surface, Selector Mode & MCP Role |
482
+ |---|---|---|---|---|
483
+ | **Local (`development`)** | `"development"` *(loopback `127.0.0.1` / `::1`)* | `true` | `false` *(not needed for `stdio` hub)* | **Book-Corner + Local BYOK Agentic Sidebar** (`Agent \| Feedback` toggle, `selection_mode: "verbose"`); runs the single unified `stdio` MCP hub (`context_drop:mcp`). |
484
+ | **Staging / QA** | `"staging"` | `true` | `true` | **Book-Corner + Verbose Inspector Chatbox** (`selection_mode: "verbose"`, `v0.1.x` CSS/layer HUD); federated into local MCP hub via dedicated `staging` Bearer token. |
485
+ | **Production** | `"production"` | `true` *(or scoped via `authorize_submission`)* | `true` | **Book-Corner + Compact Smart Quick-Feedback** (`selection_mode: "smart"`, plain-language component labels + auto surrounding screenshot; Agent endpoints hard-locked `404`); federated into local MCP hub via dedicated `production` Bearer token. |
486
+
487
+ #### Multi-Environment Best Practices
488
+
489
+ - **Automatic Host Environment Stamping:** Every `ContextDrop::Feedback` record automatically stamps `Rails.env` (customizable via `config.environment`)—no manual metadata boilerplate required, though you can still pass `metadata: { release: ENV["GIT_COMMIT_SHA"] }` to `<%= context_drop_widget(...) %>`.
490
+ - **Isolate secrets per environment:** Generate a distinct high-entropy `CONTEXT_DROP_MCP_API_KEY` (`bin/rails secret` or `openssl rand -hex 32`) in each deployed environment's Rails encrypted credentials or secret manager. Never share a single Bearer token between staging and production.
491
+ - **HTTPS Enforced for Remote Endpoints:** `ContextDrop::MCP::RemoteClient` enforces `https://` by default for all non-loopback remote MCP URLs and sets `allow_Cross_Origin` / redirect limits to zero so Bearer tokens are never leaked across redirects.
492
+ - **Independent Widget vs. MCP switches:** `config.enabled` and `config.mcp_enabled` are decoupled—`ContextDrop::McpController` remains reachable whenever `CONTEXT_DROP_MCP_ENABLED=true`, even if you temporarily set `CONTEXT_DROP_ENABLED=false` in production to pause new widget submissions while finishing triage.
493
+ - **Layer zero-trust proxy headers when needed:** If your remote MCP endpoints sit behind Cloudflare Access, Google IAP, or an internal MCP gateway, pass additional proxy `"headers"` inside `config.mcp_environments` alongside `api_key` (or validate custom JWT/header claims in `config.authorize_mcp`).
494
+
495
+ ---
496
+
497
+ ### Alternative Transport Options & Ruby Version Manager Reference
498
+
499
+ If you run a workspace-scoped config where your shell `PATH` is already inherited, or if you run inside Docker / remote-only environments, use the reference snippets below.
500
+
501
+ #### Option 1: Minimal Workspace-Scoped `stdio` (With `config.mcp_environments` in Rails)
502
+
503
+ When your IDE runs inside the Rails root, inherits your Ruby `PATH`, and remote environments are already configured in `config/initializers/context_drop.rb` or `.env.development.local`:
504
+
505
+ ```json
506
+ {
507
+ "mcpServers": {
508
+ "context-drop": {
509
+ "command": "bundle",
510
+ "args": ["exec", "./bin/rails", "context_drop:mcp"]
511
+ }
512
+ }
513
+ }
514
+ ```
515
+
516
+ #### Option 2: Strict Sandboxes, Global IDE Configs & Ruby Version Managers (`rbenv`, `mise`, `asdf`, `rvm`)
517
+
518
+ Strict sandboxed coding agents and GUI-launched desktop IDEs (such as **Antigravity** `mcp_config.json`, **Claude Desktop**, global `~/.cursor/mcp.json`, **Windsurf**, or VS Code launched from macOS Finder / Linux desktop) typically spawn MCP subprocesses with:
519
+ 1. **A non-project working directory** (often `/` or `$HOME`, causing relative `./bin/rails` or `Gemfile` lookup to fail), and
520
+ 2. **A stripped minimal `PATH`** (`/usr/bin:/bin:/usr/sbin:/sbin`) without sourcing `~/.zshrc` or `~/.bashrc`—causing `/usr/bin/env ruby` inside `bin/rails` to hit an outdated system Ruby (e.g., macOS Ruby `2.6`) or fail to locate `bundle` and Homebrew native libraries (`libpq`, `sqlite3`, `vips`).
521
+
522
+ Wrap the unified `context-drop` server command with `/bin/zsh -c` (or `/bin/bash -c` on Linux), `cd` into your Rails application root, `exec` your version manager's `bundle` binary directly, and declare an explicit absolute `PATH`:
523
+
524
+ ```json
525
+ {
526
+ "mcpServers": {
527
+ "context-drop": {
528
+ "command": "/bin/zsh",
529
+ "args": [
530
+ "-c",
531
+ "cd /absolute/path/to/your-rails-app && exec /Users/<you>/.rbenv/shims/bundle exec ./bin/rails context_drop:mcp"
532
+ ],
533
+ "env": {
534
+ "PATH": "/Users/<you>/.rbenv/shims:/Users/<you>/.rbenv/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
535
+ }
536
+ }
537
+ }
538
+ }
539
+ ```
540
+
541
+ > [!TIP]
542
+ > **Adapting Option 2 to any machine or Ruby version manager:**
543
+ > - **Use literal absolute paths (avoid `~` or `$HOME` inside JSON `env`):** MCP hosts pass `env` directly to `execve` without shell expansion. Run `pwd`, `which bundle`, and `echo $PATH` in your Rails app terminal to get your exact paths.
544
+ > - **Keep `exec` before `bundle`:** `exec` replaces the `zsh`/`bash` wrapper in-place so `stdin`/`stdout` JSON-RPC frames remain unbuffered and IDE shutdown signals (`SIGTERM`) cleanly terminate the Ruby process without leaving orphans.
545
+ > - **Debug `stdio` boot issues:** Set `"CONTEXT_DROP_MCP_DEBUG": "1"` inside `"env"` to stream verbose Rails/ActiveRecord boot diagnostics to `stderr` (MCP `stdout` always stays strictly reserved for JSON-RPC frames).
546
+
547
+ | Ruby Environment / OS | `<bundle-path>` for `exec` | Directories to Prepend to `env.PATH` |
548
+ |---|---|---|
549
+ | **`rbenv`** (macOS / Linux) | `/Users/<you>/.rbenv/shims/bundle` | `/Users/<you>/.rbenv/shims:/Users/<you>/.rbenv/bin` |
550
+ | **`mise`** (macOS / Linux) | `/Users/<you>/.local/share/mise/shims/bundle` | `/Users/<you>/.local/share/mise/shims` |
551
+ | **`asdf`** (macOS / Linux) | `/Users/<you>/.asdf/shims/bundle` | `/Users/<you>/.asdf/shims:/Users/<you>/.asdf/bin` |
552
+ | **`rvm`** (macOS / Linux) | `/Users/<you>/.rvm/wrappers/default/bundle` | `/Users/<you>/.rvm/gems/default/bin:/Users/<you>/.rvm/bin` |
553
+ | **Homebrew / Linux `/usr/local`** | `/opt/homebrew/opt/ruby/bin/bundle` or `/usr/local/bin/bundle` | `/opt/homebrew/opt/ruby/bin:/opt/homebrew/bin:/usr/local/bin` |
554
+
555
+ #### Option 3: Streamable HTTP Transport (Docker, Isolated Sandboxes, Staging & Production)
556
+
557
+ If your Rails app runs inside **Docker / Devcontainers**, if your agent sandbox blocks host binary execution outside the workspace, or if you want to triage feedback directly from **staging or production**, enable the HTTP endpoint with a bearer token (`CONTEXT_DROP_MCP_ENABLED=true` and `CONTEXT_DROP_MCP_API_KEY=<your-secret-token>`) and point your MCP client to `POST /context_drop/mcp`:
558
+
559
+ ```json
560
+ {
561
+ "mcpServers": {
562
+ "context-drop-remote": {
563
+ "url": "https://staging.example.com/context_drop/mcp",
564
+ "headers": {
565
+ "Authorization": "Bearer <your-secret-token>"
566
+ }
567
+ }
568
+ }
569
+ }
570
+ ```
571
+
572
+ *(For local Docker or strict-sandbox setups, use `"url": "http://localhost:3000/context_drop/mcp"` against your running `bin/rails server`.)*
573
+
574
+ ---
575
+
576
+ ## Zero-Trust Privacy & Redaction
577
+
578
+ ContextDrop is engineered for production environments where customer privacy and credential safety are non-negotiable:
579
+
580
+ - **Declarative Redaction Attributes:** Add `data-feedback-sensitive` or `data-feedback-ignore` to any HTML element. ContextDrop blocks the element (and **all of its descendants**) from being pinned and masks its bounding box with an opaque redaction block *before* any screenshot is rasterized:
581
+ ```html
582
+ <div data-feedback-sensitive>
583
+ <span>Account Balance: $42,100.00</span>
584
+ <span>Card ending in 4242</span>
585
+ </div>
586
+ ```
587
+ - **Automatic Credential & Card Exclusions:** `input[type="password"]`, `input[type="hidden"]`, and `[autocomplete^="cc-"]` are always excluded and redacted automatically.
588
+ - **No Raw DOM or Input Value Leaks:** Form control `value` properties and raw `outerHTML` are **never** serialized. Only allowlisted structural attributes (`id`, `class`, `role`, `aria-*`, `data-testid`, `name`, `type`, `href`) are stored.
589
+ - **Server-Side Upload Hardening:** Binary attachments are verified via magic-byte MIME detection (`Marcel`), extension matching, byte-size limits, image dimension bounds, CSRF protection, and configurable rate limiting.
590
+
591
+ ---
592
+
593
+ ## Triage Dashboard
594
+
595
+ ContextDrop includes a triage interface mounted inside your Rails application at `/context_drop/dashboard/feedbacks`:
596
+
597
+ - **Filter & Search:** Filter submissions by status (`new`, `reviewed`, `resolved`, `dismissed`), originating `page_url`, or free-text query across messages, CSS selectors, and DOM paths.
598
+ - **Inspect Context:** View submitter attribution, browser/viewport metadata, inline Active Storage screenshot galleries, and structured `ElementReference` cards (`selector`, `dom_path`, `bounding_rect`, `attributes_snapshot`).
599
+ - **Triage Actions:** Transition feedback status between `Mark Reviewed`, `Mark Resolved`, and `Dismiss`.
600
+
601
+ ---
602
+
603
+ ## Configuration
604
+
605
+ Customize every aspect of ContextDrop in `config/initializers/context_drop.rb`:
606
+
607
+ ```ruby
608
+ ContextDrop.configure do |config|
609
+ # Master switch (disables widget helper, dashboard, and HTTP ingestion endpoints when false)
610
+ config.enabled = ENV.fetch("CONTEXT_DROP_ENABLED", "false") == "true"
611
+
612
+ # Host environment attribution (defaults automatically to Rails.env)
613
+ # config.environment = Rails.env
614
+
615
+ # Initial book-corner launcher position: :bottom_right, :bottom_left, :top_right, :top_left
616
+ config.position = :bottom_right
617
+
618
+ # Element selection UX mode:
619
+ # - :auto (default) -> "smart" (jargon-free component promotion + auto surrounding screenshot) in production,
620
+ # "verbose" (v0.1.x CSS selector HUD, wheel layer scrubbing & ⌥⇧P shortcuts) in staging/dev
621
+ # - :smart -> force compact plain-language component selector + auto surrounding screenshot
622
+ # - :verbose -> force technical CSS selector HUD, wheel layer scrubbing, and multi-pin inspector
623
+ config.selection_mode = :auto
624
+ config.smart_capture_padding = 84
625
+
626
+ # Local development BYOK Agentic Sidebar (strictly active only in `development` on 127.0.0.1 / ::1)
627
+ # Disabled by default in v0.2.0; local development defaults to the verbose inspector modal
628
+ # so developers can test DOM pinning and use their preferred IDE coding agents (Antigravity, Cursor, etc.) via MCP.
629
+ # Enable if you want the experimental in-browser agent sidebar:
630
+ config.enable_local_agent = ENV.fetch("CONTEXT_DROP_LOCAL_AGENT_ENABLED", "false") == "true"
631
+
632
+ # Allow unauthenticated visitors to submit feedback
633
+ config.allow_anonymous = true
634
+
635
+ # Polymorphic submitter attribution, return any ActiveRecord model (User, Employee, AdminUser) or nil
636
+ config.current_submitter = ->(controller) { controller.try(:current_user) }
637
+
638
+ # Authorization hooks
639
+ config.authorize_submission = ->(_controller) { true }
640
+ config.authorize_dashboard = ->(controller) {
641
+ controller.try(:current_user)&.try(:admin?) || Rails.env.development?
642
+ }
643
+
644
+ # Limits & upload validation
645
+ config.max_attachments = 10
646
+ config.max_element_references = 10
647
+ config.max_attachment_size = 10.megabytes
648
+ config.allowed_content_types = %w[image/png image/jpeg image/webp image/gif]
649
+ config.max_image_dimensions = [4096, 4096]
650
+
651
+ # Additional CSS selectors to exclude from DOM selection and redact in screenshots
652
+ config.excluded_selectors = [
653
+ "[data-feedback-ignore]",
654
+ "[data-feedback-sensitive]",
655
+ "input[type='password']",
656
+ "input[type='hidden']",
657
+ "[autocomplete^='cc-']"
658
+ ]
659
+
660
+ # Lifecycle callback invoked after feedback persistence (ideal for Slack, Linear, or GitHub webhooks)
661
+ config.on_feedback_created = ->(feedback) {
662
+ Rails.logger.info("New ContextDrop Feedback ##{feedback.id} (#{feedback.environment}) on #{feedback.page_url}")
663
+ }
664
+
665
+ # Unified Model Context Protocol (MCP) Server settings
666
+ config.mcp_enabled = ENV.fetch("CONTEXT_DROP_MCP_ENABLED", "false") == "true"
667
+ config.mcp_api_key = ENV["CONTEXT_DROP_MCP_API_KEY"]
668
+ config.authorize_mcp = nil
669
+
670
+ # Federated remote environments queried by your single local `bin/rails context_drop:mcp` hub
671
+ # (also auto-discovers CONTEXT_DROP_<ENV>_MCP_URL + CONTEXT_DROP_<ENV>_MCP_API_KEY env variables):
672
+ config.mcp_environments = {
673
+ staging: {
674
+ url: ENV["CONTEXT_DROP_STAGING_MCP_URL"],
675
+ api_key: ENV["CONTEXT_DROP_STAGING_MCP_API_KEY"]
676
+ },
677
+ production: {
678
+ url: ENV["CONTEXT_DROP_PRODUCTION_MCP_URL"],
679
+ api_key: ENV["CONTEXT_DROP_PRODUCTION_MCP_API_KEY"]
680
+ }
681
+ }
682
+ end
683
+ ```
684
+
685
+ ---
686
+
687
+ ## Contributing & Development
688
+
689
+ ```bash
690
+ # Build the decoupled TypeScript widget into app/assets/javascripts/context_drop/context_drop.js
691
+ npm run build
692
+
693
+ # Run frontend TypeScript unit & interaction tests
694
+ npm test
695
+
696
+ # Run backend Ruby engine & MCP specs
697
+ ruby spec/run_all.rb
698
+
699
+ # Bump synchronized Gem + NPM version and cut a signed unified release (GitHub + RubyGems + NPM)
700
+ bundle exec rake "version:bump[0.2.1]"
701
+ bundle exec rake release
702
+ ```
703
+
704
+ Further architectural documentation:
705
+ - [Technical Specification (`SPEC.md`)](SPEC.md)
706
+ - [Design System (`DESIGN.md`)](DESIGN.md)
707
+ - [Product Brief (`PRODUCT.md`)](PRODUCT.md)
708
+
709
+ ## License
710
+
711
+ Released under the [MIT License](MIT-LICENSE).