context_drop 0.1.4 → 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 (50) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +330 -116
  3. data/Rakefile +110 -1
  4. data/SPEC.md +74 -26
  5. data/app/assets/javascripts/context_drop/context_drop.js +6329 -682
  6. data/app/controllers/context_drop/agent_controller.rb +170 -0
  7. data/app/controllers/context_drop/application_controller.rb +52 -3
  8. data/app/controllers/context_drop/configs_controller.rb +12 -2
  9. data/app/controllers/context_drop/dashboard/feedbacks_controller.rb +15 -11
  10. data/app/controllers/context_drop/feedbacks_controller.rb +396 -20
  11. data/app/controllers/context_drop/mcp_controller.rb +2 -1
  12. data/app/helpers/context_drop/widget_helper.rb +11 -1
  13. data/app/javascript/context_drop/__tests__/api-client.test.ts +255 -0
  14. data/app/javascript/context_drop/__tests__/widget.test.ts +1015 -89
  15. data/app/javascript/context_drop/api-client.ts +422 -19
  16. data/app/javascript/context_drop/element-picker.ts +186 -34
  17. data/app/javascript/context_drop/icons.ts +28 -0
  18. data/app/javascript/context_drop/markdown.ts +146 -0
  19. data/app/javascript/context_drop/sanitizer.ts +413 -2
  20. data/app/javascript/context_drop/screenshot.ts +103 -9
  21. data/app/javascript/context_drop/styles.ts +1705 -248
  22. data/app/javascript/context_drop/types.ts +243 -6
  23. data/app/javascript/context_drop/widget.ts +3318 -294
  24. data/app/models/context_drop/feedback.rb +88 -8
  25. data/app/services/context_drop/ownership_token.rb +114 -0
  26. data/app/views/context_drop/dashboard/feedbacks/index.html.erb +13 -0
  27. data/app/views/context_drop/dashboard/feedbacks/show.html.erb +19 -0
  28. data/app/views/layouts/context_drop/application.html.erb +6 -0
  29. data/config/routes.rb +22 -0
  30. data/db/migrate/20261112000004_add_environment_to_context_drop_feedbacks.rb +10 -0
  31. data/db/migrate/20261113000005_add_deleted_at_to_context_drop_feedbacks.rb +11 -0
  32. data/lib/context_drop/agent/key_store.rb +290 -0
  33. data/lib/context_drop/agent/llm_client.rb +413 -0
  34. data/lib/context_drop/agent/orchestrator.rb +314 -0
  35. data/lib/context_drop/agent/workspace_sandbox.rb +499 -0
  36. data/lib/context_drop/configuration.rb +242 -3
  37. data/lib/context_drop/mcp/dispatcher.rb +71 -29
  38. data/lib/context_drop/mcp/environment_router.rb +115 -0
  39. data/lib/context_drop/mcp/prompts/investigate_feedback.rb +90 -9
  40. data/lib/context_drop/mcp/remote_client.rb +120 -0
  41. data/lib/context_drop/mcp/server.rb +9 -2
  42. data/lib/context_drop/mcp/tools/get_feedback.rb +62 -5
  43. data/lib/context_drop/mcp/tools/get_feedback_attachment.rb +29 -4
  44. data/lib/context_drop/mcp/tools/list_environments.rb +60 -0
  45. data/lib/context_drop/mcp/tools/list_feedbacks.rb +195 -23
  46. data/lib/context_drop/mcp/tools/update_feedback_status.rb +48 -5
  47. data/lib/context_drop/version.rb +1 -1
  48. data/lib/context_drop.rb +8 -2
  49. data/lib/generators/context_drop/install/templates/initializer.rb.tt +29 -2
  50. metadata +14 -2
data/README.md CHANGED
@@ -1,26 +1,28 @@
1
1
  <p align="center">
2
- <img src="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%" />
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
3
  </p>
4
4
 
5
5
  <p align="center">
6
- <strong>Stop decoding vague bug reports! Let users pin the problem with your Rails app</strong><br />
7
- Mountable Rails Engine · Shadow DOM Widget · Overlapping Layer Picker · Active Storage · MCP Server
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
8
  </p>
9
9
 
10
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>
11
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>
12
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>
13
- <img src="https://img.shields.io/badge/Ruby-%3E%3D%203.1-CC342D?logo=ruby&logoColor=white" alt="Ruby >= 3.1" />
14
- <img src="https://img.shields.io/badge/Rails-%3E%3D%207.1-D30001?logo=rubyonrails&logoColor=white" alt="Rails >= 7.1" />
15
14
  <a href="MIT-LICENSE"><img src="https://img.shields.io/badge/License-MIT-16a34a" alt="MIT License" /></a>
16
15
  </p>
17
16
 
18
17
  <p align="center">
18
+ <a href="https://www.npmjs.com/package/context-drop">NPM</a> ·
19
19
  <a href="https://rubygems.org/gems/context_drop">RubyGems</a> ·
20
- <a href="#quickstart">Quickstart</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> ·
21
23
  <a href="#interactive-playground">Live Demo</a> ·
22
- <a href="#dom-pinning--layer-disambiguation">Layer Picker</a> ·
23
- <a href="#mcp">MCP Server</a> ·
24
+ <a href="#smart--verbose-element-selection">Smart &amp; Verbose Selectors</a> ·
25
+ <a href="#mcp">Unified MCP Hub</a> ·
24
26
  <a href="#zero-trust-privacy--redaction">Privacy &amp; Redaction</a> ·
25
27
  <a href="#configuration">Configuration</a>
26
28
  </p>
@@ -29,12 +31,56 @@
29
31
 
30
32
  ## Why
31
33
 
32
- 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.
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.
33
35
 
34
- **ContextDrop** (`context_drop`) embeds a tactile, zero-bleed **Shadow DOM feedback composer and DOM pin selector** directly into your Ruby on Rails application (`Rails >= 7.1`, including `Rails 8+`). Reporters click **Pin Element**, point at any UI component (even underneath floating badges or cascading overlays) attach a privacy-redacted screenshot, and send.
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`.
35
81
 
36
82
  <p align="center">
37
- <img src="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%" />
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%" />
38
84
  </p>
39
85
 
40
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.
@@ -42,20 +88,20 @@
42
88
  <table>
43
89
  <thead>
44
90
  <tr>
45
- <th width="50%" align="left">1. Open the Floating Composer or Pin Dock</th>
91
+ <th width="50%" align="left">1. Click or Peel the Book-Corner Launcher</th>
46
92
  <th width="50%" align="left">2. Pin DOM Layers &amp; Capture Element Screenshots</th>
47
93
  </tr>
48
94
  </thead>
49
95
  <tbody>
50
96
  <tr>
51
97
  <td valign="top">
52
- <img src="docs/images/demo-chatbox-composer.jpg" alt="ContextDrop floating chatbox composer with top-left Pin Element trigger and toolbar" width="100%" />
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%" />
53
99
  <p>
54
- Drop <code>&lt;%= context_drop_widget %&gt;</code> into your layout to render a draggable, Shadow DOM-isolated feedback composer. Click the top-left <strong>Pin Element</strong> button (or the freely floating pin dock) to start selecting elements on the page.
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.
55
101
  </p>
56
102
  </td>
57
103
  <td valign="top">
58
- <img src="docs/images/demo-pinned-element-chip.png" alt="ContextDrop chatbox with a pinned DOM element chip, camera screenshot button, and confirmation banner" width="100%" />
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%" />
59
105
  <p>
60
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>.
61
107
  </p>
@@ -75,7 +121,7 @@
75
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 |
76
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) |
77
123
  | **Authentication Model** | Separate vendor accounts & seats | Manual identity lookup | **Host-agnostic polymorphic `submitter`** (Devise, Rails 8 Auth, Sorcery, custom, or anonymous) |
78
- | **Developer Resolution Flow** | Copy-paste from external vendor dashboard | Back-and-forth reproduction questions | **Built-in Rails Triage Dashboard** + **Native MCP Server** (`stdio` & HTTP) for Cursor / Claude Code / Antigravity |
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** |
79
125
 
80
126
  > [!IMPORTANT]
81
127
  > **Core Architectural Principle: ContextDrop owns its domain. Your Rails app owns its identity and infrastructure.**
@@ -83,7 +129,140 @@
83
129
 
84
130
  ---
85
131
 
86
- ## Quickstart
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)
87
266
 
88
267
  ### Requirements
89
268
 
@@ -104,7 +283,7 @@ bin/rails db:migrate
104
283
  What `bin/rails generate context_drop:install` sets up for you:
105
284
  1. Creates [`config/initializers/context_drop.rb`](lib/generators/context_drop/install/templates/initializer.rb.tt).
106
285
  2. Mounts `mount ContextDrop::Engine => "/context_drop"` in `config/routes.rb`.
107
- 3. Copies three engine-owned migrations (`context_drop_feedbacks`, `context_drop_element_references`, `context_drop_attachments`) into `db/migrate/`.
286
+ 3. Copies four engine-owned migrations (`context_drop_feedbacks` with `environment` attribution, `context_drop_element_references`, `context_drop_attachments`) into `db/migrate/`.
108
287
  4. Verifies that Active Storage migrations are present.
109
288
 
110
289
  ### 2. Render the Widget in Your Layout
@@ -138,7 +317,7 @@ Visit any page in your Rails app to use the floating widget, or open `/context_d
138
317
 
139
318
  ## Interactive Playground
140
319
 
141
- Want to test the floating Pin selector, overlapping-layer disambiguation, draggable chatbox, and live payload inspector before installing the gem into a Rails app? Run the standalone playground in this repository:
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:
142
321
 
143
322
  ```bash
144
323
  # Start the local interactive demo server at http://127.0.0.1:4173
@@ -148,6 +327,8 @@ npm run demo
148
327
  open demo/index.html
149
328
  ```
150
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
+
151
332
  ---
152
333
 
153
334
  ## Feedback-to-Fix Loop
@@ -155,47 +336,84 @@ open demo/index.html
155
336
  ```mermaid
156
337
  flowchart LR
157
338
  subgraph Browser["Host Rails App (Browser)"]
158
- Widget["<context-drop-widget>\n(Shadow DOM + Layer Picker)"]
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"]
159
346
  end
160
347
 
161
- subgraph Engine["ContextDrop::Engine (Self-Hosted in Your Rails App)"]
162
- Controller["FeedbacksController\n+ MetadataSanitizer"]
163
- DB[("context_drop_feedbacks\ncontext_drop_element_references\ncontext_drop_attachments")]
164
- Storage[("Host Active Storage\n(Redacted Screenshots)")]
165
- Dashboard["Triage Dashboard\n/context_drop/dashboard/feedbacks"]
166
- MCP["ContextDrop::MCP::Server\n(stdio & Streamable HTTP)"]
348
+ subgraph Remote["Staging & Production Rails Apps"]
349
+ RemoteMCP["Streamable HTTP /context_drop/mcp\n(environment = staging | production)"]
167
350
  end
168
351
 
169
352
  subgraph IDE["Developer IDE / Coding Agent"]
170
353
  Agent["Cursor · Claude Code · Antigravity\nWindsurf · VS Code"]
171
354
  end
172
355
 
173
- Widget -->|"POST /context_drop/feedback\n(CSRF + Rate Limit)"| Controller
356
+ Widget -->|"POST /context_drop/feedback"| Controller
357
+ Widget <-->|"BYOK Chat + Diff Approval\n(development + 127.0.0.1 only)"| Controller
174
358
  Controller --> DB
175
- Controller --> Storage
176
- DB --> Dashboard
177
- Storage --> Dashboard
178
359
  DB --> MCP
179
- Storage --> MCP
180
- MCP -->|"list_feedbacks / get_feedback\n(Selectors + Multimodal Images)"| Agent
360
+ RemoteMCP <-->|"Bearer HTTPS Federation\n(EnvironmentRouter)"| MCP
361
+ MCP -->|"Single MCP Server\n(environment: all | local | staging | prod)"| Agent
181
362
  ```
182
363
 
183
364
  Every submission captures a rich, sanitized engineering payload:
184
- - **`ContextDrop::Feedback` (`context_drop_feedbacks`):** Polymorphic `submitter` (`User`, `Employee`, `AdminUser`, or anonymous), `message`, `page_url`, `user_agent`, `viewport` & custom `metadata`, and workflow `status` (`new`, `reviewed`, `resolved`, `dismissed`).
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`).
185
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 }`).
186
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**.
187
368
 
188
369
  ---
189
370
 
190
- ## DOM Pinning & Layer Disambiguation
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.
191
374
 
192
- Real-world Rails interfaces have sticky navbars, floating promo ribbons, translucent toast notifications, and deeply nested Flexbox/Grid containers. ContextDrop makes selecting the exact underlying element effortless:
375
+ Once selecting, ContextDrop tailors precision and verbosity to the active environment (`config.selection_mode = :auto`):
193
376
 
194
- 1. **Top-Left Pin Selector & Freely Draggable Dock:** Click **Pin Element** in the top-left corner of the chatbox (or from the floating dock). The chatbox collapses into the **Compact Pinning Bar** so it never blocks the page.
195
- 2. **Scroll-Wheel & Keyboard Depth Cycling:** While hovering any coordinate, roll your mouse wheel (`wheel`) or press `ArrowUp` / `ArrowDown` (`[` / `]`) to cycle through overlapping sibling layers (`document.elementsFromPoint`), child nodes, and parent containers while keeping a dashed ghost outline on the original leaf node.
196
- 3. **Click-to-Pick Layer Stack Popover:** Clicking a multi-layer spot anchors the pin and opens a Figma-style **Layer & Hierarchy Picker** displaying every candidate layer (`Topmost`, `Overlap`, `Child`, `Parent` badges with pixel dimensions) with live hover preview on the page. Hold `Shift+Click` or press `Enter` to pin immediately.
197
- 4. **Interactive DOM Breadcrumb Bar:** Both the Compact Pinning Bar and the Layer Popover render an interactive ancestor trail (`main.demo-shell > section#scenario > button`) hover any segment to preview or click to pin it directly.
198
- 5. **Capture-Phase Host Protection:** All `pointerdown`, `mousedown`, `mouseup`, `click`, and `wheel` events are intercepted in the capture phase during Pin Mode so underlying links, forms, and buttons are never triggered by mistake.
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.
199
417
 
200
418
  ---
201
419
 
@@ -204,7 +422,7 @@ Real-world Rails interfaces have sticky navbars, floating promo ribbons, translu
204
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.
205
423
 
206
424
  <p align="center">
207
- <img src="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%" />
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%" />
208
426
  </p>
209
427
 
210
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`.
@@ -213,40 +431,36 @@ ContextDrop ships with a built-in **Model Context Protocol (MCP)** server (`Cont
213
431
 
214
432
  | Type | Name / URI | Description |
215
433
  |---|---|---|
216
- | **Tool** | `list_feedbacks` | Filter & paginate submissions by `status` (`new`, `reviewed`, `resolved`, `dismissed`), `page_url`, or free-text `query` across messages, selectors, and DOM paths. |
217
- | **Tool** | `get_feedback` | Fetch full `Feedback`, all `ElementReference` DOM snapshots, and inline base64 `image` blocks (`include_images: true` by default). |
218
- | **Tool** | `get_feedback_attachment` | Retrieve an individual `Attachment` record and its binary screenshot/image as an MCP `image` content block. |
219
- | **Tool** | `update_feedback_status` | Transition a feedback record between `new`, `reviewed`, `resolved`, and `dismissed`. |
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`. |
220
439
  | **Resource** | `contextdrop://feedbacks/new` | Live JSON feed of unresolved `new` feedback records (up to 50 most recent). |
221
440
  | **Resource** | `contextdrop://feedbacks/{id}` | Full JSON snapshot of a specific feedback submission, its pinned elements, and attachment metadata. |
222
- | **Prompt** | `investigate_feedback` | Generates a structured root-cause investigation brief (with attached screenshots) for a given `feedback_id`. |
441
+ | **Prompt** | `investigate_feedback` | Generates a structured root-cause investigation brief (with attached screenshots) for any local or remote `feedback_id` (`"staging:18"`). |
223
442
 
224
443
  ---
225
444
 
226
- ### Recommended Setup (Local + Remote)
227
-
228
- For day-to-day development, register **both** a local `stdio` server and a remote Streamable HTTP server side-by-side in your MCP configuration (`mcp_config.json` in **Antigravity**, `~/.cursor/mcp.json` in **Cursor**, **Claude Desktop** / `.mcp.json` in **Claude Code**, **Windsurf**, or **VS Code**):
445
+ ### Recommended Setup: One Unified MCP Server for All Environments (`local` + `staging` + `production`)
229
446
 
230
- - **`context-drop-local` (`stdio`):** Runs `./bin/rails context_drop:mcp` directly against your local development database and Active Storage (no running `bin/rails server` required). Wrapped with `/bin/zsh -c`, `cd`, `exec`, and an explicit `PATH` so it boots reliably inside strict agent sandboxes and GUI-launched IDEs.
231
- - **`context-drop-remote` (`Streamable HTTP`):** Connects to your deployed staging or production Rails app (`POST <mount_path>/mcp` with `CONTEXT_DROP_MCP_ENABLED=true` and `CONTEXT_DROP_MCP_API_KEY=<your-secret-token>` configured on the server) so your agent can pull real bug reports, pinned selectors, and screenshots submitted by QA or users, fix the code locally, and mark the remote feedback resolved.
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`:
232
448
 
233
449
  ```json
234
450
  {
235
451
  "mcpServers": {
236
- "context-drop-local": {
452
+ "context-drop": {
237
453
  "command": "/bin/zsh",
238
454
  "args": [
239
455
  "-c",
240
456
  "cd /absolute/path/to/your-rails-app && exec /Users/<you>/.rbenv/shims/bundle exec ./bin/rails context_drop:mcp"
241
457
  ],
242
458
  "env": {
243
- "PATH": "/Users/<you>/.rbenv/shims:/Users/<you>/.rbenv/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
244
- }
245
- },
246
- "context-drop-remote": {
247
- "url": "https://staging.example.com/context_drop/mcp",
248
- "headers": {
249
- "Authorization": "Bearer <your-secret-token>"
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>"
250
464
  }
251
465
  }
252
466
  }
@@ -254,78 +468,44 @@ For day-to-day development, register **both** a local `stdio` server and a remot
254
468
  ```
255
469
 
256
470
  > [!NOTE]
257
- > **Custom route prefixes:** Match the `context-drop-remote` URL to wherever `ContextDrop::Engine` is mounted in `config/routes.rb` plus `/mcp` (for example, `https://staging.example.com/rails/context_drop/mcp` when mounted under `/rails/context_drop`).
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`.
258
472
 
259
- Naming the servers `context-drop-local` and `context-drop-remote` lets you target either environment explicitly in your IDE prompts without toggling config files:
260
- - *"Check `context-drop-remote` for new feedbacks, inspect the pinned element selector and screenshot, diagnose the root cause in our local Rails views/CSS, and mark the feedback resolved."*
261
- - *"Inspect the latest feedback I just pinned on `context-drop-local` and verify the layout fix."*
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."*
262
476
 
263
477
  ---
264
478
 
265
- ### Multi-Environment & Multiple Remote Servers (`local` + `staging` + `production`)
479
+ ### Recommended Environment Matrix
266
480
 
267
- MCP clients support registering any number of ContextDrop servers simultaneously. If your team triages feedback across **Staging / QA** and **Production** (or across multiple Rails services), register each remote endpoint under an explicit environment-scoped key:
268
-
269
- ```json
270
- {
271
- "mcpServers": {
272
- "context-drop-local": {
273
- "command": "/bin/zsh",
274
- "args": [
275
- "-c",
276
- "cd /absolute/path/to/your-rails-app && exec /Users/<you>/.rbenv/shims/bundle exec ./bin/rails context_drop:mcp"
277
- ],
278
- "env": {
279
- "PATH": "/Users/<you>/.rbenv/shims:/Users/<you>/.rbenv/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
280
- }
281
- },
282
- "context-drop-staging": {
283
- "url": "https://staging.example.com/context_drop/mcp",
284
- "headers": {
285
- "Authorization": "Bearer <staging-mcp-secret-token>"
286
- }
287
- },
288
- "context-drop-production": {
289
- "url": "https://app.example.com/context_drop/mcp",
290
- "headers": {
291
- "Authorization": "Bearer <production-mcp-secret-token>"
292
- }
293
- }
294
- }
295
- }
296
- ```
297
-
298
- #### Recommended Environment Matrix
299
-
300
- | Environment | MCP Transport | `CONTEXT_DROP_ENABLED` (Widget & Dashboard) | `CONTEXT_DROP_MCP_ENABLED` (HTTP `/mcp`) | Token & Access Strategy |
481
+ | Environment | Host `Rails.env` Attribution | `CONTEXT_DROP_ENABLED` (Widget & Dashboard) | `CONTEXT_DROP_MCP_ENABLED` (HTTP `/mcp`) | Widget Surface, Selector Mode & MCP Role |
301
482
  |---|---|---|---|---|
302
- | **Local (`development`)** | `stdio` (`context_drop:mcp`) | `true` | `false` *(not needed for `stdio`)* | Direct local DB & Active Storage access; zero network exposure. |
303
- | **Staging / QA** | Streamable HTTP | `true` | `true` | Dedicated `staging` token (`bin/rails secret`); open to QA & preview testers. |
304
- | **Production** | Streamable HTTP | `true` *(or scoped via `authorize_submission`)* | `true` | Separate `production` token (rotated independently) + optional gateway headers / `authorize_mcp`. |
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. |
305
486
 
306
487
  #### Multi-Environment Best Practices
307
488
 
308
- - **Namespace server keys clearly (especially across multiple Rails apps):** In global IDE configs (`mcp_config.json` in Antigravity or `~/.cursor/mcp.json`), prefix keys by service and environment—such as `checkout-local`, `checkout-staging`, `checkout-prod`, and `admin-prod`—so your agent never confuses tools from different repositories or databases.
309
- - **Isolate secrets per environment:** Generate a distinct high-entropy `CONTEXT_DROP_MCP_API_KEY` (`bin/rails secret` or `openssl rand -hex 32`) in each environment's Rails encrypted credentials or secret manager. Never share a single Bearer token between staging and production.
310
- - **Keep live tokens out of version control:** Place configs containing live `Authorization` headers in user-level MCP files (e.g., Antigravity `mcp_config.json`, `~/.cursor/mcp.json`) or gitignore workspace `.mcp.json` overrides.
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.
311
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.
312
- - **Stamp environment & release SHA into widget metadata:** Pass `metadata: { env: Rails.env, release: ENV["GIT_COMMIT_SHA"] }` to `<%= context_drop_widget(...) %>` so every feedback record pulled by your agent explicitly carries the environment and commit SHA it came from.
313
- - **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 `"headers"` alongside `Authorization` (or validate custom JWT/header claims in `config.authorize_mcp`).
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`).
314
494
 
315
495
  ---
316
496
 
317
- ### Individual Transport Options & Environment Reference
497
+ ### Alternative Transport Options & Ruby Version Manager Reference
318
498
 
319
- If you only need a single transport or use a different Ruby version manager (`mise`, `asdf`, `rvm`, Homebrew) or Docker setup, see the reference configurations below.
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.
320
500
 
321
- #### Option 1: Project-Scoped Local `stdio` (Inherited Shell Environment)
501
+ #### Option 1: Minimal Workspace-Scoped `stdio` (With `config.mcp_environments` in Rails)
322
502
 
323
- When using a workspace-scoped MCP file (e.g., `.mcp.json` in Claude Code or `.cursor/mcp.json` launched from a terminal) where your IDE already runs inside the Rails root and inherits your Ruby shell `PATH`:
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`:
324
504
 
325
505
  ```json
326
506
  {
327
507
  "mcpServers": {
328
- "context-drop-local": {
508
+ "context-drop": {
329
509
  "command": "bundle",
330
510
  "args": ["exec", "./bin/rails", "context_drop:mcp"]
331
511
  }
@@ -339,12 +519,12 @@ Strict sandboxed coding agents and GUI-launched desktop IDEs (such as **Antigrav
339
519
  1. **A non-project working directory** (often `/` or `$HOME`, causing relative `./bin/rails` or `Gemfile` lookup to fail), and
340
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`).
341
521
 
342
- To make `stdio` work reliably in strict sandboxes, wrap the launch 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`:
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`:
343
523
 
344
524
  ```json
345
525
  {
346
526
  "mcpServers": {
347
- "context-drop-local": {
527
+ "context-drop": {
348
528
  "command": "/bin/zsh",
349
529
  "args": [
350
530
  "-c",
@@ -429,9 +609,26 @@ ContextDrop.configure do |config|
429
609
  # Master switch (disables widget helper, dashboard, and HTTP ingestion endpoints when false)
430
610
  config.enabled = ENV.fetch("CONTEXT_DROP_ENABLED", "false") == "true"
431
611
 
432
- # Initial widget corner position: :bottom_right, :bottom_left, :top_right, :top_left
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
433
616
  config.position = :bottom_right
434
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
+
435
632
  # Allow unauthenticated visitors to submit feedback
436
633
  config.allow_anonymous = true
437
634
 
@@ -462,13 +659,26 @@ ContextDrop.configure do |config|
462
659
 
463
660
  # Lifecycle callback invoked after feedback persistence (ideal for Slack, Linear, or GitHub webhooks)
464
661
  config.on_feedback_created = ->(feedback) {
465
- Rails.logger.info("New ContextDrop Feedback ##{feedback.id} on #{feedback.page_url}")
662
+ Rails.logger.info("New ContextDrop Feedback ##{feedback.id} (#{feedback.environment}) on #{feedback.page_url}")
466
663
  }
467
664
 
468
- # Model Context Protocol (MCP) Server settings
665
+ # Unified Model Context Protocol (MCP) Server settings
469
666
  config.mcp_enabled = ENV.fetch("CONTEXT_DROP_MCP_ENABLED", "false") == "true"
470
667
  config.mcp_api_key = ENV["CONTEXT_DROP_MCP_API_KEY"]
471
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
+ }
472
682
  end
473
683
  ```
474
684
 
@@ -485,6 +695,10 @@ npm test
485
695
 
486
696
  # Run backend Ruby engine & MCP specs
487
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
488
702
  ```
489
703
 
490
704
  Further architectural documentation: