context-drop 0.0.0-stage → 0.2.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 +709 -2
  3. package/app/assets/javascripts/context_drop/context_drop.js +8936 -0
  4. package/dist/app/javascript/context_drop/api-client.d.ts +41 -0
  5. package/dist/app/javascript/context_drop/api-client.js +279 -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 +32 -0
  9. package/dist/app/javascript/context_drop/icons.js +32 -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 +2015 -0
  20. package/dist/app/javascript/context_drop/types.d.ts +239 -0
  21. package/dist/app/javascript/context_drop/types.js +1 -0
  22. package/dist/app/javascript/context_drop/widget.d.ts +188 -0
  23. package/dist/app/javascript/context_drop/widget.js +3227 -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 +869 -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 +90 -0
  41. package/dist/src/react/index.js +124 -0
  42. package/dist/src/server/handler.d.ts +42 -0
  43. package/dist/src/server/handler.js +677 -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 +574 -0
  50. package/dist/src/server/storage/memory.d.ts +5 -0
  51. package/dist/src/server/storage/memory.js +221 -0
  52. package/dist/src/server/storage/postgres.d.ts +27 -0
  53. package/dist/src/server/storage/postgres.js +446 -0
  54. package/dist/src/server/types.d.ts +190 -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
@@ -0,0 +1,869 @@
1
+ import { FEEDBACK_STATUSES, VERSION } from "../server/types.js";
2
+ import { formatSubmitterLabel } from "../server/storage/memory.js";
3
+ import { EnvironmentRouter } from "./environment-router.js";
4
+ import { RemoteMcpClient, RemoteMcpError } from "./remote-client.js";
5
+ export const MCP_PROTOCOL_VERSION = "2025-03-26";
6
+ const MAX_INLINE_IMAGE_BYTES = 5 * 1024 * 1024; // 5 MB
7
+ const TOOL_DEFINITIONS = [
8
+ {
9
+ name: "list_environments",
10
+ description: "List the active host environment and all federated remote ContextDrop environments connected through this unified MCP server.",
11
+ inputSchema: {
12
+ type: "object",
13
+ properties: {
14
+ ping_remotes: {
15
+ type: "boolean",
16
+ description: "When true, performs a lightweight JSON-RPC ping against each configured remote environment to verify connectivity."
17
+ }
18
+ }
19
+ }
20
+ },
21
+ {
22
+ name: "list_feedbacks",
23
+ description: "List and search ContextDrop feedback submissions across all connected environments (or filtered to a specific environment, status, page_url, or query).",
24
+ inputSchema: {
25
+ type: "object",
26
+ properties: {
27
+ environment: {
28
+ type: "string",
29
+ description: "Target environment ('all', 'local', 'development', 'staging', 'production', etc.). Defaults to 'all' across local and configured remote environments."
30
+ },
31
+ status: {
32
+ type: "string",
33
+ enum: [...FEEDBACK_STATUSES],
34
+ description: "Filter feedback by workflow status."
35
+ },
36
+ page_url: {
37
+ type: "string",
38
+ description: "Filter feedback by originating page URL substring (e.g. '/checkout')."
39
+ },
40
+ query: {
41
+ type: "string",
42
+ description: "Free-text search matching feedback message or attached DOM element selectors, paths, or text."
43
+ },
44
+ limit: {
45
+ type: "integer",
46
+ description: "Maximum records to return (default 20, max 100)."
47
+ },
48
+ offset: {
49
+ type: "integer",
50
+ description: "Pagination offset (default 0)."
51
+ }
52
+ }
53
+ }
54
+ },
55
+ {
56
+ name: "get_feedback",
57
+ description: "Retrieve a complete ContextDrop feedback record, all DOM ElementReference snapshots, and screenshots/images as multimodal MCP image blocks across local or remote environments.",
58
+ inputSchema: {
59
+ type: "object",
60
+ required: ["id"],
61
+ properties: {
62
+ id: {
63
+ type: ["integer", "string"],
64
+ description: "The ID of the ContextDrop feedback record, or a qualified '<environment>:<id>' string (e.g. 'staging:42')."
65
+ },
66
+ environment: {
67
+ type: "string",
68
+ description: "Optional environment name ('local', 'development', 'staging', 'production', etc.). Defaults to the local host environment unless specified or prefixed on `id`."
69
+ },
70
+ include_images: {
71
+ type: "boolean",
72
+ description: "When true (default), includes attached screenshots and images as base64 MCP image content blocks."
73
+ }
74
+ }
75
+ }
76
+ },
77
+ {
78
+ name: "get_feedback_attachment",
79
+ description: "Retrieve a specific ContextDrop attachment record and its binary image/screenshot as an MCP image content block from local or remote environments.",
80
+ inputSchema: {
81
+ type: "object",
82
+ required: ["attachment_id"],
83
+ properties: {
84
+ attachment_id: {
85
+ type: ["integer", "string"],
86
+ description: "The ID of the ContextDrop attachment record, or a qualified '<environment>:<attachment_id>' string (e.g. 'staging:201')."
87
+ },
88
+ environment: {
89
+ type: "string",
90
+ description: "Optional environment name ('local', 'staging', 'production', etc.)."
91
+ }
92
+ }
93
+ }
94
+ },
95
+ {
96
+ name: "update_feedback_status",
97
+ description: "Transition a ContextDrop feedback record's status ('new', 'reviewed', 'resolved', 'dismissed') in local or remote environments.",
98
+ inputSchema: {
99
+ type: "object",
100
+ required: ["id", "status"],
101
+ properties: {
102
+ id: {
103
+ type: ["integer", "string"],
104
+ description: "The ID of the ContextDrop feedback record, or a qualified '<environment>:<id>' string (e.g. 'staging:42')."
105
+ },
106
+ environment: {
107
+ type: "string",
108
+ description: "Optional environment name ('local', 'staging', 'production', etc.)."
109
+ },
110
+ status: {
111
+ type: "string",
112
+ enum: [...FEEDBACK_STATUSES],
113
+ description: "Target workflow status."
114
+ }
115
+ }
116
+ }
117
+ }
118
+ ];
119
+ const PROMPT_DEFINITIONS = [
120
+ {
121
+ name: "investigate_feedback",
122
+ description: "Generate a structured investigation brief for a ContextDrop feedback record (local or remote), including its originating environment, URL, DOM element selectors/paths, and visual screenshots.",
123
+ arguments: [
124
+ {
125
+ name: "feedback_id",
126
+ description: "ID of the ContextDrop feedback record to investigate, or '<environment>:<id>' (e.g. 'staging:42').",
127
+ required: true
128
+ },
129
+ {
130
+ name: "environment",
131
+ description: "Optional environment name ('local', 'staging', 'production', etc.).",
132
+ required: false
133
+ }
134
+ ]
135
+ }
136
+ ];
137
+ const RESOURCES = [
138
+ {
139
+ uri: "contextdrop://environments",
140
+ name: "Connected ContextDrop Environments",
141
+ description: "Host environment and all federated remote ContextDrop environments.",
142
+ mimeType: "application/json"
143
+ },
144
+ {
145
+ uri: "contextdrop://feedbacks/new",
146
+ name: "Unresolved New Feedbacks (All Connected Environments)",
147
+ description: "List of unresolved ContextDrop feedback records currently in 'new' status across local and federated environments.",
148
+ mimeType: "application/json"
149
+ }
150
+ ];
151
+ const RESOURCE_TEMPLATES = [
152
+ {
153
+ uriTemplate: "contextdrop://feedbacks/{id}",
154
+ name: "Feedback Record by ID",
155
+ description: "Full ContextDrop feedback submission, DOM element snapshots, and attachment metadata for a local ID or '<env>:<id>'.",
156
+ mimeType: "application/json"
157
+ },
158
+ {
159
+ uriTemplate: "contextdrop://{environment}/feedbacks/new",
160
+ name: "Unresolved New Feedbacks by Environment",
161
+ description: "Unresolved 'new' feedback records scoped to a specific environment ('local', 'staging', 'production', 'all').",
162
+ mimeType: "application/json"
163
+ },
164
+ {
165
+ uriTemplate: "contextdrop://{environment}/feedbacks/{id}",
166
+ name: "Feedback Record by Environment and ID",
167
+ description: "Full ContextDrop feedback submission for a specific environment and ID.",
168
+ mimeType: "application/json"
169
+ }
170
+ ];
171
+ function asRecord(val) {
172
+ if (val && typeof val === "object" && !Array.isArray(val)) {
173
+ return val;
174
+ }
175
+ return {};
176
+ }
177
+ function successJsonTool(payload) {
178
+ return {
179
+ content: [{ type: "text", text: JSON.stringify(payload, null, 2) }],
180
+ isError: false
181
+ };
182
+ }
183
+ function errorTool(message) {
184
+ return {
185
+ content: [{ type: "text", text: JSON.stringify({ error: message }) }],
186
+ isError: true
187
+ };
188
+ }
189
+ function serializeFullFeedback(record, router) {
190
+ const envName = record.environment || router.hostEnvironment;
191
+ return {
192
+ id: record.id,
193
+ qualified_id: router.qualifyId(envName, record.id),
194
+ environment: envName,
195
+ status: record.status,
196
+ message: record.message,
197
+ page_url: record.page_url,
198
+ user_agent: record.user_agent,
199
+ submitter: {
200
+ type: record.submitter?.type ?? null,
201
+ id: record.submitter?.id ?? null,
202
+ label: formatSubmitterLabel(record.submitter)
203
+ },
204
+ metadata: record.metadata ?? {},
205
+ created_at: record.created_at,
206
+ updated_at: record.updated_at,
207
+ element_references: record.element_references.map((el) => ({
208
+ id: el.id,
209
+ client_ref: el.client_ref,
210
+ tag_name: el.tag_name,
211
+ selector: el.selector,
212
+ dom_path: el.dom_path,
213
+ text_content: el.text_content,
214
+ attributes_snapshot: el.attributes_snapshot ?? {},
215
+ bounding_rect: el.bounding_rect ?? {},
216
+ viewport: el.viewport ?? {},
217
+ metadata: el.metadata ?? {},
218
+ captured_at: el.captured_at
219
+ })),
220
+ attachments: record.attachments.map((att) => ({
221
+ id: att.id,
222
+ qualified_id: router.qualifyId(envName, att.id),
223
+ attachment_type: att.attachment_type,
224
+ element_reference_id: att.element_reference_id,
225
+ metadata: att.metadata ?? {},
226
+ filename: att.filename,
227
+ content_type: att.content_type,
228
+ byte_size: att.byte_size,
229
+ created_at: att.created_at
230
+ }))
231
+ };
232
+ }
233
+ export class ContextDropMcpDispatcher {
234
+ storage;
235
+ router;
236
+ remoteClient;
237
+ constructor(options) {
238
+ this.storage = options.storage;
239
+ this.router = new EnvironmentRouter({
240
+ hostEnvironment: options.hostEnvironment,
241
+ environments: options.environments,
242
+ localOnly: options.localOnly,
243
+ envVars: options.envVars
244
+ });
245
+ this.remoteClient = new RemoteMcpClient({
246
+ transport: options.remoteTransport
247
+ });
248
+ }
249
+ async dispatch(rawMessage) {
250
+ if (Array.isArray(rawMessage)) {
251
+ const results = [];
252
+ for (const item of rawMessage) {
253
+ const res = await this.dispatchSingle(item);
254
+ if (res)
255
+ results.push(res);
256
+ }
257
+ return results.length > 0 ? results : null;
258
+ }
259
+ return this.dispatchSingle(rawMessage);
260
+ }
261
+ async dispatchSingle(msg) {
262
+ if (!msg || typeof msg !== "object" || Array.isArray(msg)) {
263
+ return this.jsonrpcError(null, -32600, "Invalid Request: expected JSON object");
264
+ }
265
+ const req = msg;
266
+ const hasId = Object.prototype.hasOwnProperty.call(req, "id");
267
+ const id = req["id"] ?? null;
268
+ const method = String(req["method"] ?? "");
269
+ const params = asRecord(req["params"]);
270
+ if (method.startsWith("notifications/") || (!hasId && id === null)) {
271
+ return null;
272
+ }
273
+ try {
274
+ switch (method) {
275
+ case "initialize": {
276
+ const clientVersion = String(params["protocolVersion"] ?? "").trim();
277
+ const negotiatedVersion = clientVersion || MCP_PROTOCOL_VERSION;
278
+ return this.jsonrpcResult(id, {
279
+ protocolVersion: negotiatedVersion,
280
+ capabilities: {
281
+ tools: { listChanged: false },
282
+ resources: { subscribe: false, listChanged: false },
283
+ prompts: { listChanged: false }
284
+ },
285
+ serverInfo: {
286
+ name: "context_drop",
287
+ version: VERSION,
288
+ environment: this.router.hostEnvironment,
289
+ connectedEnvironments: this.router.getAvailableEnvironments().map((e) => e.name)
290
+ }
291
+ });
292
+ }
293
+ case "ping":
294
+ return this.jsonrpcResult(id, {});
295
+ case "tools/list":
296
+ return this.jsonrpcResult(id, { tools: TOOL_DEFINITIONS });
297
+ case "tools/call":
298
+ return await this.handleToolCall(id, params);
299
+ case "resources/list":
300
+ return this.jsonrpcResult(id, { resources: RESOURCES });
301
+ case "resources/templates/list":
302
+ return this.jsonrpcResult(id, { resourceTemplates: RESOURCE_TEMPLATES });
303
+ case "resources/read":
304
+ return await this.handleResourceRead(id, params);
305
+ case "prompts/list":
306
+ return this.jsonrpcResult(id, { prompts: PROMPT_DEFINITIONS });
307
+ case "prompts/get":
308
+ return await this.handlePromptGet(id, params);
309
+ default:
310
+ return this.jsonrpcError(id, -32601, `Method not found: ${method}`);
311
+ }
312
+ }
313
+ catch (err) {
314
+ return this.jsonrpcError(id, -32603, `Internal error: ${err.message}`);
315
+ }
316
+ }
317
+ async handleToolCall(id, params) {
318
+ const toolName = String(params["name"] ?? "");
319
+ const args = asRecord(params["arguments"]);
320
+ switch (toolName) {
321
+ case "list_environments":
322
+ return this.jsonrpcResult(id, await this.toolListEnvironments(args));
323
+ case "list_feedbacks":
324
+ return this.jsonrpcResult(id, await this.toolListFeedbacks(args));
325
+ case "get_feedback":
326
+ return this.jsonrpcResult(id, await this.toolGetFeedback(args));
327
+ case "get_feedback_attachment":
328
+ return this.jsonrpcResult(id, await this.toolGetFeedbackAttachment(args));
329
+ case "update_feedback_status":
330
+ return this.jsonrpcResult(id, await this.toolUpdateFeedbackStatus(args));
331
+ default:
332
+ return this.jsonrpcError(id, -32602, `Unknown tool: ${toolName}`);
333
+ }
334
+ }
335
+ async toolListEnvironments(args) {
336
+ const pingRemotes = Boolean(args["ping_remotes"]);
337
+ const environments = this.router.getAvailableEnvironments().map((e) => ({ ...e }));
338
+ if (pingRemotes) {
339
+ const remotes = this.router.getRemoteEnvironments();
340
+ await Promise.all(environments.map(async (entry) => {
341
+ if (entry.mode !== "remote_http")
342
+ return;
343
+ const cfg = remotes[entry.name];
344
+ if (!cfg)
345
+ return;
346
+ try {
347
+ await this.remoteClient.callRpc(entry.name, cfg, "ping", {});
348
+ entry.reachable = true;
349
+ }
350
+ catch (err) {
351
+ entry.reachable = false;
352
+ entry.error = err.message;
353
+ }
354
+ }));
355
+ }
356
+ return successJsonTool({
357
+ host_environment: this.router.hostEnvironment,
358
+ federation_enabled: !this.router.localOnly,
359
+ environments
360
+ });
361
+ }
362
+ async toolListFeedbacks(args) {
363
+ const statusRaw = String(args["status"] ?? "").trim();
364
+ if (statusRaw && !FEEDBACK_STATUSES.includes(statusRaw)) {
365
+ return errorTool(`Invalid status '${statusRaw}'. Must be one of: ${FEEDBACK_STATUSES.join(", ")}`);
366
+ }
367
+ const status = (statusRaw || null);
368
+ const rawLimit = args["limit"] !== undefined ? Number(args["limit"]) : 20;
369
+ const limit = Math.max(1, Math.min(100, Number.isFinite(rawLimit) ? Math.trunc(rawLimit) : 20));
370
+ const rawOffset = args["offset"] !== undefined ? Number(args["offset"]) : 0;
371
+ const offset = Math.max(0, Number.isFinite(rawOffset) ? Math.trunc(rawOffset) : 0);
372
+ const pageUrl = String(args["page_url"] ?? "").trim() || null;
373
+ const query = String(args["query"] ?? "").trim() || null;
374
+ const requestedEnv = (String(args["environment"] ?? "").trim().toLowerCase()) || "all";
375
+ const remotes = this.router.getRemoteEnvironments();
376
+ const hostEnv = this.router.hostEnvironment;
377
+ if (requestedEnv === "all") {
378
+ const fetchWindow = Math.max(1, Math.min(100, offset + limit));
379
+ const localRes = await this.storage.listFeedbacks({
380
+ status,
381
+ page_url: pageUrl,
382
+ query,
383
+ limit: fetchWindow,
384
+ offset: 0
385
+ });
386
+ const remoteEntries = Object.entries(remotes);
387
+ if (remoteEntries.length === 0) {
388
+ return successJsonTool({
389
+ environment: hostEnv,
390
+ total: localRes.total,
391
+ limit,
392
+ offset,
393
+ feedbacks: localRes.records.slice(offset, offset + limit)
394
+ });
395
+ }
396
+ const warnings = [];
397
+ const remoteLists = await Promise.all(remoteEntries.map(async ([envName, cfg]) => {
398
+ try {
399
+ return await this.fetchRemoteList(envName, cfg, {
400
+ status,
401
+ page_url: pageUrl,
402
+ query,
403
+ limit: fetchWindow,
404
+ offset: 0
405
+ });
406
+ }
407
+ catch (err) {
408
+ warnings.push({ environment: envName, error: err.message });
409
+ return null;
410
+ }
411
+ }));
412
+ const combined = [...localRes.records];
413
+ let totalCount = localRes.total;
414
+ for (const r of remoteLists) {
415
+ if (!r)
416
+ continue;
417
+ combined.push(...r.records);
418
+ totalCount += r.total;
419
+ }
420
+ combined.sort((a, b) => {
421
+ const dt = (Date.parse(b.created_at) || 0) - (Date.parse(a.created_at) || 0);
422
+ return dt !== 0 ? dt : Number(b.id) - Number(a.id);
423
+ });
424
+ const payload = {
425
+ environment: "all",
426
+ connected_environments: [hostEnv, ...Object.keys(remotes)],
427
+ total: totalCount,
428
+ limit,
429
+ offset,
430
+ feedbacks: combined.slice(offset, offset + limit)
431
+ };
432
+ if (warnings.length > 0) {
433
+ payload["warnings"] = warnings;
434
+ }
435
+ return successJsonTool(payload);
436
+ }
437
+ if (requestedEnv === "local" || requestedEnv === hostEnv) {
438
+ const localRes = await this.storage.listFeedbacks({
439
+ environment: requestedEnv === "local" ? null : hostEnv,
440
+ status,
441
+ page_url: pageUrl,
442
+ query,
443
+ limit,
444
+ offset
445
+ });
446
+ return successJsonTool({
447
+ environment: hostEnv,
448
+ total: localRes.total,
449
+ limit,
450
+ offset,
451
+ feedbacks: localRes.records
452
+ });
453
+ }
454
+ const remoteCfg = remotes[requestedEnv];
455
+ if (remoteCfg) {
456
+ try {
457
+ const remoteRes = await this.fetchRemoteList(requestedEnv, remoteCfg, {
458
+ status,
459
+ page_url: pageUrl,
460
+ query,
461
+ limit,
462
+ offset
463
+ });
464
+ return successJsonTool({
465
+ environment: requestedEnv,
466
+ total: remoteRes.total,
467
+ limit,
468
+ offset,
469
+ feedbacks: remoteRes.records
470
+ });
471
+ }
472
+ catch (err) {
473
+ return errorTool(err.message);
474
+ }
475
+ }
476
+ // Shared DB fallback
477
+ const fallbackRes = await this.storage.listFeedbacks({
478
+ environment: requestedEnv,
479
+ status,
480
+ page_url: pageUrl,
481
+ query,
482
+ limit,
483
+ offset
484
+ });
485
+ if (fallbackRes.total > 0) {
486
+ return successJsonTool({
487
+ environment: requestedEnv,
488
+ total: fallbackRes.total,
489
+ limit,
490
+ offset,
491
+ feedbacks: fallbackRes.records
492
+ });
493
+ }
494
+ const known = Array.from(new Set([hostEnv, "local", "all", ...Object.keys(remotes)]));
495
+ return errorTool(`Unknown environment '${requestedEnv}'. Available environments: ${known.join(", ")}`);
496
+ }
497
+ async fetchRemoteList(envName, cfg, filter) {
498
+ const remoteArgs = {
499
+ limit: filter.limit,
500
+ offset: filter.offset
501
+ };
502
+ if (filter.status)
503
+ remoteArgs["status"] = filter.status;
504
+ if (filter.page_url)
505
+ remoteArgs["page_url"] = filter.page_url;
506
+ if (filter.query)
507
+ remoteArgs["query"] = filter.query;
508
+ const toolRes = await this.remoteClient.callTool(envName, cfg, "list_feedbacks", remoteArgs);
509
+ const textBlock = toolRes.content.find((b) => b.type === "text");
510
+ const parsed = textBlock?.text ? JSON.parse(textBlock.text) : {};
511
+ if (toolRes.isError) {
512
+ throw new RemoteMcpError(String(parsed["error"] ?? `Remote list_feedbacks failed on '${envName}'`));
513
+ }
514
+ const items = Array.isArray(parsed["feedbacks"]) ? parsed["feedbacks"] : [];
515
+ const records = items.map((raw) => {
516
+ const rec = asRecord(raw);
517
+ const id = rec["id"] ?? "";
518
+ return {
519
+ ...rec,
520
+ id,
521
+ environment: envName,
522
+ qualified_id: this.router.qualifyId(envName, id)
523
+ };
524
+ });
525
+ return {
526
+ total: Number(parsed["total"] ?? records.length),
527
+ records
528
+ };
529
+ }
530
+ async toolGetFeedback(args) {
531
+ const rawId = args["id"] ?? args["feedback_id"];
532
+ if (rawId === undefined || rawId === null || String(rawId).trim() === "") {
533
+ return errorTool("Missing required parameter: id");
534
+ }
535
+ const includeImages = args["include_images"] !== undefined ? Boolean(args["include_images"]) : true;
536
+ const [targetEnv, feedbackId] = this.router.parseTarget(rawId, args["environment"]);
537
+ if (!this.router.isLocalTarget(targetEnv)) {
538
+ const remoteCfg = this.router.getRemoteConfig(targetEnv);
539
+ if (!remoteCfg || !targetEnv) {
540
+ return errorTool(`Unknown remote environment '${targetEnv}'`);
541
+ }
542
+ return this.fetchRemoteFeedback(targetEnv, remoteCfg, feedbackId, includeImages);
543
+ }
544
+ const feedback = await this.storage.getFeedback(feedbackId);
545
+ if (!feedback) {
546
+ return errorTool(`Feedback #${feedbackId} not found`);
547
+ }
548
+ const payload = serializeFullFeedback(feedback, this.router);
549
+ const contentBlocks = [
550
+ {
551
+ type: "text",
552
+ text: JSON.stringify(payload, null, 2)
553
+ }
554
+ ];
555
+ if (includeImages) {
556
+ for (const att of feedback.attachments) {
557
+ if ((att.byte_size ?? 0) > MAX_INLINE_IMAGE_BYTES)
558
+ continue;
559
+ const bytes = await this.storage.getAttachmentBytes(att.id);
560
+ if (bytes && bytes.byteLength > 0 && bytes.byteLength <= MAX_INLINE_IMAGE_BYTES) {
561
+ contentBlocks.push({
562
+ type: "image",
563
+ data: Buffer.from(bytes).toString("base64"),
564
+ mimeType: att.content_type || "image/png"
565
+ });
566
+ }
567
+ }
568
+ }
569
+ return {
570
+ content: contentBlocks,
571
+ isError: false
572
+ };
573
+ }
574
+ async fetchRemoteFeedback(envName, remoteCfg, feedbackId, includeImages) {
575
+ try {
576
+ const res = await this.remoteClient.callTool(envName, remoteCfg, "get_feedback", {
577
+ id: feedbackId,
578
+ include_images: includeImages
579
+ });
580
+ if (res.isError)
581
+ return res;
582
+ const updatedBlocks = res.content.map((block) => {
583
+ if (block.type === "text" && typeof block.text === "string") {
584
+ try {
585
+ const parsed = JSON.parse(block.text);
586
+ parsed["environment"] = envName;
587
+ parsed["qualified_id"] = this.router.qualifyId(envName, parsed["id"] ?? feedbackId);
588
+ return { ...block, text: JSON.stringify(parsed, null, 2) };
589
+ }
590
+ catch {
591
+ return block;
592
+ }
593
+ }
594
+ return block;
595
+ });
596
+ return { content: updatedBlocks, isError: false };
597
+ }
598
+ catch (err) {
599
+ return errorTool(err.message);
600
+ }
601
+ }
602
+ async toolGetFeedbackAttachment(args) {
603
+ const rawAttId = args["attachment_id"] ?? args["id"];
604
+ if (rawAttId === undefined || rawAttId === null || String(rawAttId).trim() === "") {
605
+ return errorTool("Missing required parameter: attachment_id");
606
+ }
607
+ const [targetEnv, attId] = this.router.parseTarget(rawAttId, args["environment"]);
608
+ if (!this.router.isLocalTarget(targetEnv)) {
609
+ const remoteCfg = this.router.getRemoteConfig(targetEnv);
610
+ if (!remoteCfg || !targetEnv) {
611
+ return errorTool(`Unknown remote environment '${targetEnv}'`);
612
+ }
613
+ try {
614
+ return await this.remoteClient.callTool(targetEnv, remoteCfg, "get_feedback_attachment", {
615
+ attachment_id: attId
616
+ });
617
+ }
618
+ catch (err) {
619
+ return errorTool(err.message);
620
+ }
621
+ }
622
+ const found = await this.storage.getAttachment(attId);
623
+ if (!found) {
624
+ return errorTool(`Attachment #${attId} not found`);
625
+ }
626
+ const envName = this.router.hostEnvironment;
627
+ const { attachment, element_selector, data } = found;
628
+ const metaPayload = {
629
+ id: attachment.id,
630
+ qualified_id: this.router.qualifyId(envName, attachment.id),
631
+ environment: envName,
632
+ feedback_id: attachment.feedback_id,
633
+ element_reference_id: attachment.element_reference_id,
634
+ element_selector,
635
+ attachment_type: attachment.attachment_type,
636
+ metadata: attachment.metadata ?? {},
637
+ filename: attachment.filename,
638
+ content_type: attachment.content_type,
639
+ byte_size: attachment.byte_size
640
+ };
641
+ const blocks = [{ type: "text", text: JSON.stringify(metaPayload, null, 2) }];
642
+ if (data && data.byteLength > 0) {
643
+ blocks.push({
644
+ type: "image",
645
+ data: Buffer.from(data).toString("base64"),
646
+ mimeType: attachment.content_type || "image/png"
647
+ });
648
+ }
649
+ return {
650
+ content: blocks,
651
+ isError: false
652
+ };
653
+ }
654
+ async toolUpdateFeedbackStatus(args) {
655
+ const rawId = args["id"] ?? args["feedback_id"];
656
+ const nextStatus = String(args["status"] ?? "").trim();
657
+ if (rawId === undefined || rawId === null || String(rawId).trim() === "") {
658
+ return errorTool("Missing required parameter: id");
659
+ }
660
+ if (!FEEDBACK_STATUSES.includes(nextStatus)) {
661
+ return errorTool(`Invalid status '${nextStatus}'. Must be one of: ${FEEDBACK_STATUSES.join(", ")}`);
662
+ }
663
+ const [targetEnv, feedbackId] = this.router.parseTarget(rawId, args["environment"]);
664
+ if (!this.router.isLocalTarget(targetEnv)) {
665
+ const remoteCfg = this.router.getRemoteConfig(targetEnv);
666
+ if (!remoteCfg || !targetEnv) {
667
+ return errorTool(`Unknown remote environment '${targetEnv}'`);
668
+ }
669
+ try {
670
+ const res = await this.remoteClient.callTool(targetEnv, remoteCfg, "update_feedback_status", {
671
+ id: feedbackId,
672
+ status: nextStatus
673
+ });
674
+ if (res.isError)
675
+ return res;
676
+ const updatedBlocks = res.content.map((block) => {
677
+ if (block.type === "text" && typeof block.text === "string") {
678
+ try {
679
+ const parsed = JSON.parse(block.text);
680
+ parsed["environment"] = targetEnv;
681
+ parsed["qualified_id"] = this.router.qualifyId(targetEnv, parsed["id"] ?? feedbackId);
682
+ return { ...block, text: JSON.stringify(parsed, null, 2) };
683
+ }
684
+ catch {
685
+ return block;
686
+ }
687
+ }
688
+ return block;
689
+ });
690
+ return { content: updatedBlocks, isError: false };
691
+ }
692
+ catch (err) {
693
+ return errorTool(err.message);
694
+ }
695
+ }
696
+ const updated = await this.storage.updateFeedbackStatus(feedbackId, nextStatus);
697
+ if (!updated) {
698
+ return errorTool(`Feedback #${feedbackId} not found`);
699
+ }
700
+ const envName = updated.feedback.environment || this.router.hostEnvironment;
701
+ return successJsonTool({
702
+ id: updated.feedback.id,
703
+ qualified_id: this.router.qualifyId(envName, updated.feedback.id),
704
+ environment: envName,
705
+ previous_status: updated.previous_status,
706
+ status: updated.feedback.status,
707
+ page_url: updated.feedback.page_url,
708
+ updated_at: updated.feedback.updated_at
709
+ });
710
+ }
711
+ async handleResourceRead(id, params) {
712
+ const uri = String(params["uri"] ?? "").trim();
713
+ if (uri === "contextdrop://environments") {
714
+ return this.jsonrpcResult(id, {
715
+ contents: [
716
+ {
717
+ uri,
718
+ mimeType: "application/json",
719
+ text: JSON.stringify({
720
+ host_environment: this.router.hostEnvironment,
721
+ environments: this.router.getAvailableEnvironments()
722
+ }, null, 2)
723
+ }
724
+ ]
725
+ });
726
+ }
727
+ if (uri === "contextdrop://feedbacks/new") {
728
+ const res = await this.toolListFeedbacks({ status: "new", limit: 50, environment: "all" });
729
+ return this.jsonrpcResult(id, {
730
+ contents: [{ uri, mimeType: "application/json", text: res.content[0]?.text ?? "{}" }]
731
+ });
732
+ }
733
+ const envNewMatch = /^contextdrop:\/\/([a-z0-9_-]+)\/feedbacks\/new$/i.exec(uri);
734
+ if (envNewMatch) {
735
+ const envName = envNewMatch[1].toLowerCase();
736
+ const res = await this.toolListFeedbacks({ status: "new", limit: 50, environment: envName });
737
+ if (res.isError) {
738
+ return this.jsonrpcError(id, -32602, this.extractToolErrorMessage(res));
739
+ }
740
+ return this.jsonrpcResult(id, {
741
+ contents: [{ uri, mimeType: "application/json", text: res.content[0]?.text ?? "{}" }]
742
+ });
743
+ }
744
+ const fbByIdMatch = /^contextdrop:\/\/feedbacks\/([a-z0-9_:-]+)$/i.exec(uri);
745
+ if (fbByIdMatch) {
746
+ const rawId = fbByIdMatch[1];
747
+ const res = await this.toolGetFeedback({ id: rawId, include_images: false });
748
+ if (res.isError) {
749
+ return this.jsonrpcError(id, -32602, this.extractToolErrorMessage(res));
750
+ }
751
+ return this.jsonrpcResult(id, {
752
+ contents: [{ uri, mimeType: "application/json", text: res.content[0]?.text ?? "{}" }]
753
+ });
754
+ }
755
+ const envFbMatch = /^contextdrop:\/\/([a-z0-9_-]+)\/feedbacks\/([a-z0-9_-]+)$/i.exec(uri);
756
+ if (envFbMatch) {
757
+ const envName = envFbMatch[1].toLowerCase();
758
+ const fbId = envFbMatch[2];
759
+ const res = await this.toolGetFeedback({
760
+ id: fbId,
761
+ environment: envName,
762
+ include_images: false
763
+ });
764
+ if (res.isError) {
765
+ return this.jsonrpcError(id, -32602, this.extractToolErrorMessage(res));
766
+ }
767
+ return this.jsonrpcResult(id, {
768
+ contents: [{ uri, mimeType: "application/json", text: res.content[0]?.text ?? "{}" }]
769
+ });
770
+ }
771
+ return this.jsonrpcError(id, -32602, `Unknown resource URI: ${uri}`);
772
+ }
773
+ async handlePromptGet(id, params) {
774
+ const promptName = String(params["name"] ?? "");
775
+ if (promptName !== "investigate_feedback") {
776
+ return this.jsonrpcError(id, -32602, `Unknown prompt: ${promptName}`);
777
+ }
778
+ const args = asRecord(params["arguments"]);
779
+ const rawId = args["feedback_id"] ?? args["id"];
780
+ if (rawId === undefined || rawId === null || String(rawId).trim() === "") {
781
+ return this.jsonrpcError(id, -32602, "Missing required argument: feedback_id");
782
+ }
783
+ const res = await this.toolGetFeedback({
784
+ id: rawId,
785
+ environment: args["environment"],
786
+ include_images: true
787
+ });
788
+ if (res.isError) {
789
+ return this.jsonrpcError(id, -32602, this.extractToolErrorMessage(res));
790
+ }
791
+ const textBlock = res.content.find((b) => b.type === "text");
792
+ const fb = textBlock?.text ? JSON.parse(textBlock.text) : {};
793
+ const envName = String(fb["environment"] ?? this.router.hostEnvironment);
794
+ const qualified = String(fb["qualified_id"] ?? this.router.qualifyId(envName, String(fb["id"] ?? rawId)));
795
+ const els = Array.isArray(fb["element_references"])
796
+ ? fb["element_references"]
797
+ : [];
798
+ const elementLines = els.length > 0
799
+ ? els
800
+ .map((el, idx) => `${idx + 1}. \`<${el["tag_name"]}>\` — Selector: \`${el["selector"]}\`\n` +
801
+ ` - DOM Path: \`${el["dom_path"] ?? "N/A"}\`\n` +
802
+ ` - Visible Text: ${JSON.stringify(el["text_content"] ?? null)}\n` +
803
+ ` - Bounding Box: \`${JSON.stringify(el["bounding_rect"] ?? {})}\`\n` +
804
+ ` - Attributes: \`${JSON.stringify(el["attributes_snapshot"] ?? {})}\``)
805
+ .join("\n")
806
+ : "None selected.";
807
+ const selectorsList = els.map((e) => String(e["selector"] ?? "")).filter(Boolean).join(", ");
808
+ const pageUrl = String(fb["page_url"] ?? "");
809
+ const submitterObj = asRecord(fb["submitter"]);
810
+ const instructions = [
811
+ `Investigate and resolve ContextDrop Feedback #${fb["id"] ?? rawId} (\`${qualified}\`, environment: \`${envName}\`, status: ${fb["status"]}).`,
812
+ "",
813
+ "## Reported Feedback",
814
+ `- **Environment:** \`${envName}\``,
815
+ `- **Message:** ${fb["message"] || "(No text message provided)"}`,
816
+ `- **Originating Page URL:** \`${pageUrl}\``,
817
+ `- **Submitter:** ${submitterObj["label"] || "Anonymous"}`,
818
+ `- **Submitted At:** ${fb["created_at"]}`,
819
+ `- **Viewport / Metadata:** \`${JSON.stringify(fb["metadata"] ?? {})}\``,
820
+ "",
821
+ "## Attached DOM Element References",
822
+ elementLines,
823
+ "",
824
+ "## Recommended Investigation Steps",
825
+ `1. Locate the page route corresponding to \`${pageUrl}\` (in Next.js \`app/**/page.tsx\` / \`pages/**\`, React router, or Rails \`config/routes.rb\` & \`app/views/\`).`,
826
+ `2. Search components and templates for the attached DOM selectors (\`${selectorsList || "N/A"}\`) and data-testid / class / text landmarks.`,
827
+ `3. Inspect any attached screenshots (\`get_feedback\` with \`id: "${qualified}"\`) to verify the visual layout or behavior issue.`,
828
+ `4. Implement and verify the fix locally, then call \`update_feedback_status\` (\`id: "${qualified}"\`, \`status: "resolved"\`) once complete.`
829
+ ].join("\n");
830
+ const imageBlocks = res.content.filter((b) => b.type === "image");
831
+ const messageContent = [{ type: "text", text: instructions }, ...imageBlocks];
832
+ return this.jsonrpcResult(id, {
833
+ description: `Investigation brief for ContextDrop Feedback ${qualified} on ${pageUrl}`,
834
+ messages: [
835
+ {
836
+ role: "user",
837
+ content: messageContent.length === 1 ? messageContent[0] : messageContent
838
+ }
839
+ ]
840
+ });
841
+ }
842
+ extractToolErrorMessage(res) {
843
+ const raw = res.content[0]?.text ?? "";
844
+ try {
845
+ const parsed = JSON.parse(raw);
846
+ return parsed.error || raw;
847
+ }
848
+ catch {
849
+ return raw;
850
+ }
851
+ }
852
+ jsonrpcResult(id, result) {
853
+ return {
854
+ jsonrpc: "2.0",
855
+ id,
856
+ result
857
+ };
858
+ }
859
+ jsonrpcError(id, code, message) {
860
+ return {
861
+ jsonrpc: "2.0",
862
+ id,
863
+ error: {
864
+ code,
865
+ message
866
+ }
867
+ };
868
+ }
869
+ }