screenpipe-mcp 0.20.2 → 0.20.4

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.
@@ -30,7 +30,11 @@ import {
30
30
  flushMcpTelemetry,
31
31
  initMcpTelemetry,
32
32
  } from "./telemetry";
33
+ import { createCallObserver, currentMcpRequestId, observeSearchResult } from "./call-observation";
34
+ import { formatSearchHit, searchContentCap, searchResultHeader } from "./search-result";
35
+ import { CHAT_SEARCH_TOOL, searchChats } from "./chat-search";
33
36
  import { PKG_VERSION } from "./version";
37
+ import { BUNDLED_SKILLS_TOOL, readBundledSkills } from "./bundled-skills";
34
38
  import { normalizeTimeFields } from "./time-normalization";
35
39
  import { createMcpQualifiedValueReporter, resolveMcpClient, type McpClient } from "./qualified-value";
36
40
 
@@ -123,22 +127,37 @@ export function isLoopbackRequest(req: { socket: { remoteAddress?: string } }):
123
127
  }
124
128
 
125
129
  /**
126
- * Authorization decision. Loopback is always allowed; non-loopback requires
130
+ * Authorization decision. Literal loopback hosts with no foreign Origin are allowed; other requests require
127
131
  * a matching bearer token when one is configured. If no api key is set
128
132
  * (loopback-only deployment), non-loopback shouldn't even be reachable —
129
133
  * but we still 401 it as belt-and-suspenders.
130
134
  */
131
135
  export function isAuthorized(
132
- req: { socket: { remoteAddress?: string }; headers: { authorization?: string } },
136
+ req: { socket: { remoteAddress?: string }; headers: { authorization?: string; host?: string; origin?: string } },
133
137
  apiKey: string | undefined
134
138
  ): boolean {
135
- if (isLoopbackRequest(req)) return true;
139
+ // The socket alone is insufficient: a browser can resolve an attacker-owned
140
+ // hostname to loopback, or call localhost with a foreign Origin.
141
+ if (isLoopbackRequest(req) && isTrustedLocalHost(req.headers.host)
142
+ && (req.headers.origin === undefined || isTrustedLocalOrigin(req.headers.origin))) return true;
136
143
  if (!apiKey) return false;
137
144
  const expected = `Bearer ${apiKey}`;
138
145
  const got = req.headers.authorization ?? "";
139
146
  return constantTimeEq(got, expected);
140
147
  }
141
148
 
149
+ function isTrustedLocalHost(host: string | undefined): boolean {
150
+ if (!host) return false;
151
+ // Match the raw authority, not URL-normalized input (userinfo, paths and
152
+ // numeric aliases must not acquire localhost privileges).
153
+ return /^(?:localhost|127\.0\.0\.1|\[::1\])(?::[0-9]{1,5})?$/i.test(host);
154
+ }
155
+
156
+ function isTrustedLocalOrigin(origin: string): boolean {
157
+ const match = /^https?:\/\/([^/?#]+)$/.exec(origin);
158
+ return match !== null && isTrustedLocalHost(match[1]);
159
+ }
160
+
142
161
  /** Constant-time string compare to keep timing attacks off the table. */
143
162
  function constantTimeEq(a: string, b: string): boolean {
144
163
  if (a.length !== b.length) return false;
@@ -154,7 +173,7 @@ const TOOLS = [
154
173
  name: "search_content",
155
174
  description:
156
175
  "Search screenpipe's recorded content: screen text, audio transcriptions, input events, and parsed app data. " +
157
- "Returns timestamped results with app context. " +
176
+ "Returns timestamped results with app context and starred markers. For starred work, set starred_only=true and a time range. " +
158
177
  "Call with no parameters to get recent activity.",
159
178
  inputSchema: {
160
179
  type: "object" as const,
@@ -171,6 +190,7 @@ const TOOLS = [
171
190
  default: "all",
172
191
  },
173
192
  limit: { type: "integer", description: "Max results. Default: 10" },
193
+ max_content_length: { type: "integer", minimum: 0, description: "Text characters per result; default 1000. Use 0 only for an explicitly scoped full-text read." },
174
194
  offset: { type: "integer", description: "Skip N results for pagination. Default: 0" },
175
195
  start_time: {
176
196
  type: "string",
@@ -180,6 +200,8 @@ const TOOLS = [
180
200
  type: "string",
181
201
  description: "ISO 8601, relative, or local calendar ('today', 'yesterday', 'tomorrow', 'YYYY-MM-DD')",
182
202
  },
203
+ starred_only: { type: "boolean", description: "Only captures inside starred intervals; applied before pagination. Omit for unrelated searches." },
204
+ starred_session_id: { type: "string", description: "Optional known session ID to restrict the search." },
183
205
  app_name: {
184
206
  type: "string",
185
207
  description: "Filter by app (e.g., 'Google Chrome', 'Slack', 'zoom.us')",
@@ -208,6 +230,7 @@ function makeFetchAPI(screenpipePort: number, client: () => McpClient) {
208
230
  headers: {
209
231
  "Content-Type": "application/json",
210
232
  ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
233
+ ...(currentMcpRequestId() ? { "x-screenpipe-request-id": currentMcpRequestId()! } : {}),
211
234
  "x-screenpipe-client": "mcp",
212
235
  "x-screenpipe-agent": client(),
213
236
  ...options.headers,
@@ -229,12 +252,15 @@ async function handleSearchContent(
229
252
 
230
253
  const response = await fetchAPI(`/search?${params.toString()}`);
231
254
  if (!response.ok) {
232
- throw new Error(`HTTP error: ${response.status}`);
255
+ const body = await response.json().catch(() => ({}));
256
+ const detail = typeof body?.error === "string" ? `: ${body.error.slice(0, 500)}` : "";
257
+ throw Object.assign(new Error(`HTTP error: ${response.status}${detail}`), { status: response.status });
233
258
  }
234
259
 
235
260
  const data = await response.json();
236
261
  const results = data.data || [];
237
262
  const pagination = data.pagination || {};
263
+ observeSearchResult(results.length, false);
238
264
 
239
265
  if (results.length === 0) {
240
266
  return {
@@ -247,43 +273,12 @@ async function handleSearchContent(
247
273
  };
248
274
  }
249
275
 
250
- const formattedResults: string[] = [];
251
- for (const result of results) {
252
- const content = result.content;
253
- if (!content) continue;
254
-
255
- if (result.type === "OCR") {
256
- formattedResults.push(
257
- `[OCR] ${content.app_name || "?"} | ${content.window_name || "?"}\n` +
258
- `${content.timestamp || ""}\n` +
259
- `${content.text || ""}`
260
- );
261
- } else if (result.type === "Audio") {
262
- formattedResults.push(
263
- `[Audio] ${content.device_name || "?"}\n` +
264
- `${content.timestamp || ""}\n` +
265
- `${content.transcription || ""}`
266
- );
267
- } else if (result.type === "UI" || result.type === "Accessibility") {
268
- formattedResults.push(
269
- `[Accessibility] ${content.app_name || "?"} | ${content.window_name || "?"}\n` +
270
- `${content.timestamp || ""}\n` +
271
- `${content.text || ""}`
272
- );
273
- } else if (result.type === "Parsed") {
274
- formattedResults.push(
275
- `[Parsed] ${content.app_name || "?"} | ${content.window_name || "?"} | frame ${content.frame_id || "?"}\n` +
276
- `${content.timestamp || ""}\n` +
277
- `${content.text || ""}`
278
- );
279
- }
280
- }
281
-
282
- const header =
283
- `Results: ${results.length}/${pagination.total || "?"}` +
284
- (pagination.total > results.length
285
- ? ` (use offset=${(pagination.offset || 0) + results.length} for more)`
286
- : "");
276
+ const cap = searchContentCap(args.max_content_length);
277
+ const hits = results.map((result: unknown) => formatSearchHit(result, cap))
278
+ .filter((hit: ReturnType<typeof formatSearchHit>) => hit !== null);
279
+ observeSearchResult(results.length, hits.some((hit: NonNullable<ReturnType<typeof formatSearchHit>>) => hit.truncated));
280
+ const formattedResults = hits.map((hit: NonNullable<ReturnType<typeof formatSearchHit>>) => hit.text);
281
+ const header = searchResultHeader(results.length, pagination);
287
282
 
288
283
  if (formattedResults.length > 0) qualifiedValue.searchResult();
289
284
 
@@ -319,14 +314,24 @@ function createMcpServer(screenpipePort: number): Server {
319
314
  client,
320
315
  );
321
316
 
322
- s.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
317
+ s.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [...TOOLS, CHAT_SEARCH_TOOL, BUNDLED_SKILLS_TOOL] }));
323
318
 
324
- s.setRequestHandler(CallToolRequestSchema, async (request) => {
325
- const { name, arguments: args } = request.params;
326
- if (!args) throw new Error("Missing arguments");
327
- if (name === "search_content") return handleSearchContent(fetchAPI, args, qualifiedValue);
328
- throw new Error(`Unknown tool: ${name}`);
319
+ const observeCall = createCallObserver({
320
+ tools: [...TOOLS.map(tool => tool.name), CHAT_SEARCH_TOOL.name, BUNDLED_SKILLS_TOOL.name], transport: "http", client,
321
+ send: async (payload, signal) => {
322
+ const response = await fetchAPI("/internal/telemetry/mcp-call", { method: "POST", body: JSON.stringify(payload), signal });
323
+ if (!response.ok) throw new Error("Telemetry unavailable");
324
+ },
329
325
  });
326
+ s.setRequestHandler(CallToolRequestSchema, async (request) => observeCall(request.params.name, async () => {
327
+ const { name, arguments: suppliedArgs } = request.params;
328
+ const args = suppliedArgs ?? (name === CHAT_SEARCH_TOOL.name ? {} : undefined);
329
+ if (name === BUNDLED_SKILLS_TOOL.name) return readBundledSkills(args);
330
+ if (!args) throw Object.assign(new Error("Missing arguments"), { status: 400 });
331
+ if (name === CHAT_SEARCH_TOOL.name) return searchChats(args, fetchAPI);
332
+ if (name === "search_content") return handleSearchContent(fetchAPI, args, qualifiedValue);
333
+ throw Object.assign(new Error(`Unknown tool: ${name}`), { status: 400 });
334
+ }));
330
335
 
331
336
  return s;
332
337
  }
package/src/index.ts CHANGED
@@ -32,8 +32,10 @@ import {
32
32
  } from "./qualified-value";
33
33
  import { discoverTeamConfig } from "./team-config";
34
34
  import { teamFrameContent, teamFramePath } from "./team-frame";
35
- import { WORKFLOW_TOOLS, readWorkflowTool, frameAutomationContent, inputEventContent } from "./workflow-tools";
35
+ import { CHAT_SEARCH_TOOL, searchChats } from "./chat-search";
36
+ import { WORKFLOW_TOOLS, readWorkflowTool, frameAutomationContent } from "./workflow-tools";
36
37
  import { PKG_VERSION } from "./version";
38
+ import { BUNDLED_SKILLS_TOOL, readBundledSkills } from "./bundled-skills";
37
39
  import { formatForElementPurpose } from "./element-format";
38
40
  import { buildActivitySummaryResult } from "./activity-summary-tool";
39
41
  import {
@@ -41,6 +43,8 @@ import {
41
43
  normalizeTime,
42
44
  normalizeTimeFields,
43
45
  } from "./time-normalization";
46
+ import { createCallObserver, currentMcpRequestId, observeMcpError, observeSearchResult } from "./call-observation";
47
+ import { formatSearchHit, searchContentCap, searchResultHeader } from "./search-result";
44
48
  import { resolveScreenpipeApiBase } from "./api-base";
45
49
 
46
50
  initMcpTelemetry({ transport: "stdio" });
@@ -322,11 +326,13 @@ const server = new Server(
322
326
  // Tools
323
327
  // ---------------------------------------------------------------------------
324
328
  const TOOLS: Tool[] = [
329
+ CHAT_SEARCH_TOOL,
325
330
  ...WORKFLOW_TOOLS,
331
+ BUNDLED_SKILLS_TOOL,
326
332
  {
327
333
  name: "search-content",
328
334
  description:
329
- "Search screen text, audio transcriptions, input events, memories, and parsed app data. Returns timestamped results with app context. " +
335
+ "Search screen text, audio transcriptions, input events, memories, and parsed app data. Returns timestamped results with app context and starred markers. For starred work, set starred_only=true and a time range; no session lookup needed. " +
330
336
  "USE WHEN: you need the actual text/content of a moment — quotes, screen text, transcript lines, or compact parsed messages, emails, tasks, documents, and code review — or want to filter by speaker/window. " +
331
337
  "DO NOT USE for: broad questions like 'what was I doing?' (use activity-summary, it pre-summarizes apps + windows + transcripts). " +
332
338
  "Also DO NOT USE for: targeted UI controls (use search-elements). " +
@@ -341,9 +347,9 @@ const TOOLS: Tool[] = [
341
347
  },
342
348
  content_type: {
343
349
  type: "string",
344
- enum: ["all", "ocr", "audio", "input", "accessibility", "memory", "parsed"],
350
+ enum: ["all", "screen", "ocr", "audio", "input", "accessibility", "memory", "parsed"],
345
351
  description:
346
- "Filter by content type. Use 'parsed' for compact app-specific records such as messages, emails, tasks, documents, and code review; it is experimental and may be empty when parsing is disabled or unsupported. NOTE on screen text: 'ocr' is a legacy label — it returns ALL screen-text rows, which are accessibility-derived for most apps (the result tag [Screen·a11y] vs [Screen·ocr] tells you which). Use 'ocr' for screen text (covers both paths), 'audio' for transcriptions, 'input' for keyboard/mouse events, 'memory' for stored facts. Default: 'all'.",
352
+ "Filter by content type. Use 'screen' for screen text: accessibility is the primary capture path, with OCR fallback. Results identify the actual source as [Screen·a11y] or [Screen·ocr]; [Screen] means the source is unknown. 'ocr' is a legacy alias for 'screen', not an OCR-only filter. Use 'accessibility' only when you explicitly need accessibility-only results; it excludes OCR fallback. Use 'parsed' for compact app-specific messages, emails, tasks, documents, and code review (experimental; may be empty when parsing is disabled or unsupported), 'audio' for transcriptions, 'input' for keyboard/mouse events, 'memory' for stored facts. Default: 'all'.",
347
353
  default: "all",
348
354
  },
349
355
  limit: { type: "integer", description: "Max results (default 10, max 20). Start with 5 for exploration.", default: 10 },
@@ -356,6 +362,8 @@ const TOOLS: Tool[] = [
356
362
  type: "string",
357
363
  description: "ISO 8601, relative time, or local calendar ('today', 'yesterday', 'tomorrow', 'YYYY-MM-DD'). Defaults to now.",
358
364
  },
365
+ starred_only: { type: "boolean", description: "Only captures inside starred intervals. Use for starred work; omit for ordinary searches. Applied before pagination." },
366
+ starred_session_id: { type: "string", description: "Optional exact session ID already known from activity-summary. Usually use starred_only instead." },
359
367
  app_name: { type: "string", description: "Filter by app name (e.g. 'Google Chrome', 'Slack', 'zoom.us'). Case-sensitive." },
360
368
  window_name: { type: "string", description: "Filter by window title substring" },
361
369
  frame_id: { type: "integer", description: "With content_type='parsed', return parsed data attached to one frame." },
@@ -364,7 +372,7 @@ const TOOLS: Tool[] = [
364
372
  max_length: { type: "integer", description: "Max content length in characters" },
365
373
  include_frames: {
366
374
  type: "boolean",
367
- description: "Include base64 screenshots (OCR only). Warning: large response.",
375
+ description: "Include base64 screenshots for screen-text results, including accessibility-derived captures. Warning: large response.",
368
376
  default: false,
369
377
  },
370
378
  speaker_ids: { type: "string", description: "Comma-separated speaker IDs to filter audio" },
@@ -372,7 +380,7 @@ const TOOLS: Tool[] = [
372
380
  tags: {
373
381
  type: "string",
374
382
  description:
375
- "Comma-separated tags; returns only items carrying ALL of them (e.g. 'person:ada,project:atlas'). Works for screen + audio (content_type 'ocr'/'audio'/'all', tags written by add-tags) AND memories (content_type 'memory', tags written by update-memory). Same tag string links across all three, so two items sharing a tag are connected. Use namespaced tags (person:, project:, topic:) to link people/projects/topics. content_type 'input' and 'accessibility' have no tags and return nothing when this is set; 'parsed' does not support tags.",
383
+ "Comma-separated tags; returns only items carrying ALL of them (e.g. 'person:ada,project:atlas'). Works for screen + audio (content_type 'screen'/'ocr'/'audio'/'all', tags written by add-tags) AND memories (content_type 'memory', tags written by update-memory). Same tag string links across all three, so two items sharing a tag are connected. Use namespaced tags (person:, project:, topic:) to link people/projects/topics. content_type 'input' and 'accessibility' have no tags and return nothing when this is set; 'parsed' does not support tags.",
376
384
  },
377
385
  include_related: {
378
386
  type: "boolean",
@@ -441,6 +449,7 @@ const TOOLS: Tool[] = [
441
449
  {
442
450
  name: "activity-summary",
443
451
  description:
452
+ "Includes up to ten recent starred intervals for this time range, even without captured content. Stars indicate user intent, not duration or completion. " +
444
453
  "Rich activity overview: authoritative active minutes, app/window time, edited document paths, key text, and audio transcriptions, with optional parsed task context when available. " +
445
454
  "USE WHEN: any broad question about what the user did — 'what was I doing?', 'how long on X?', 'which apps?', 'recap my morning'. " +
446
455
  "This is almost always the right first call for time-range questions — usually sufficient without follow-up searches. " +
@@ -452,6 +461,7 @@ const TOOLS: Tool[] = [
452
461
  properties: {
453
462
  start_time: { type: "string", description: "ISO 8601, relative (e.g. '3h ago'), or local calendar ('today', 'yesterday', 'tomorrow', 'YYYY-MM-DD')" },
454
463
  end_time: { type: "string", description: "ISO 8601, relative (e.g. 'now'), or local calendar ('today', 'yesterday', 'tomorrow', 'YYYY-MM-DD')" },
464
+ include_starred: { type: "boolean", description: "Include bounded starred-session context (default true; omitted for app/data-restricted reads)." },
455
465
  app_name: { type: "string", description: "Optional app name filter to focus on one app" },
456
466
  include_parsed_context: {
457
467
  type: "boolean",
@@ -1162,7 +1172,7 @@ current machine. Synced results must be attributed with their device and timesta
1162
1172
  - **Use max_content_length=500** to keep responses compact
1163
1173
  - **Don't use q for audio** — transcriptions are noisy, q filters too aggressively. Search audio by time range and speaker instead
1164
1174
  - **app_name is case-sensitive** — use exact names: "Google Chrome" not "chrome"
1165
- - **Screen text is mostly accessibility-derived, not OCR.** Screenpipe walks the OS accessibility tree first; OCR is only a fallback (terminals, canvas-rendered apps, games). \`content_type=ocr\` returns both paths — the result label \`[Screen·a11y]\` vs \`[Screen·ocr]\` tells you which produced the row. Don't pre-filter to a11y/ocr unless you specifically need one or the other
1175
+ - **Use content_type=screen for screen text.** Screenpipe walks the OS accessibility tree first, with OCR fallback. The result label \`[Screen·a11y]\` or \`[Screen·ocr]\` identifies the actual capture source; \`[Screen]\` means unknown. \`content_type=ocr\` is a legacy alias for the same search, not an OCR-only filter. Use \`accessibility\` only for an explicit accessibility-only request, since it excludes OCR fallback.
1166
1176
 
1167
1177
  ## Common Patterns
1168
1178
 
@@ -1318,6 +1328,7 @@ async function fetchAPI(
1318
1328
  headers: {
1319
1329
  "Content-Type": "application/json",
1320
1330
  ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
1331
+ ...(currentMcpRequestId() ? { "x-screenpipe-request-id": currentMcpRequestId()! } : {}),
1321
1332
  "x-screenpipe-client": "mcp",
1322
1333
  "x-screenpipe-agent": currentMcpClient(),
1323
1334
  ...options.headers,
@@ -1399,11 +1410,19 @@ function screenTag(textSource: unknown): string {
1399
1410
  // ---------------------------------------------------------------------------
1400
1411
  // Tool handlers
1401
1412
  // ---------------------------------------------------------------------------
1402
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
1403
- const { name, arguments: args } = request.params;
1413
+ const observeCall = createCallObserver({
1414
+ tools: [...TOOLS.map(tool => tool.name), ...TEAM_TOOLS.map(tool => tool.name), ...WORKFLOW_TOOLS.map(tool => tool.name), BUNDLED_SKILLS_TOOL.name],
1415
+ transport: "stdio", client: currentMcpClient,
1416
+ send: (payload, signal) => callAPI("/internal/telemetry/mcp-call", { method: "POST", body: JSON.stringify(payload), signal }),
1417
+ });
1418
+ server.setRequestHandler(CallToolRequestSchema, async (request) => observeCall(request.params.name, async () => {
1419
+ const { name, arguments: suppliedArgs } = request.params;
1420
+ const args = suppliedArgs ?? (name === CHAT_SEARCH_TOOL.name ? {} : undefined);
1421
+
1422
+ if (name === BUNDLED_SKILLS_TOOL.name) return readBundledSkills(args);
1404
1423
 
1405
1424
  if (!args) {
1406
- throw new Error("Missing arguments");
1425
+ throw Object.assign(new Error("Missing arguments"), { status: 400 });
1407
1426
  }
1408
1427
 
1409
1428
  try {
@@ -1597,15 +1616,13 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1597
1616
  case "search-content": {
1598
1617
  const includeFrames = args.include_frames === true;
1599
1618
  const normalized = normalizeTimeFields(args);
1619
+ // Keep the clearer MCP name compatible with APIs that still call all
1620
+ // screen-text rows "ocr", including accessibility-derived captures.
1621
+ if (normalized.content_type === "screen") normalized.content_type = "ocr";
1600
1622
  // Default text cap if the caller didn't pass max_content_length.
1601
1623
  // Keeps single calls under Claude Code's per-tool output limit.
1602
1624
  const userCap = normalized.max_content_length;
1603
- const effectiveCap =
1604
- typeof userCap === "number"
1605
- ? userCap
1606
- : userCap === undefined
1607
- ? DEFAULT_SEARCH_CONTENT_TRUNCATE
1608
- : Number(userCap);
1625
+ const effectiveCap = searchContentCap(userCap);
1609
1626
  const params = new URLSearchParams();
1610
1627
  for (const [key, value] of Object.entries(normalized)) {
1611
1628
  if (value !== null && value !== undefined) {
@@ -1617,6 +1634,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1617
1634
  const data = await response.json();
1618
1635
  const results = data.data || [];
1619
1636
  const pagination = data.pagination || {};
1637
+ observeSearchResult(results.length, false);
1620
1638
 
1621
1639
  if (results.length === 0) {
1622
1640
  return {
@@ -1638,71 +1656,20 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1638
1656
 
1639
1657
  const formattedResults: string[] = [];
1640
1658
  const images: Array<{ data: string; context: string }> = [];
1659
+ let truncated = false;
1641
1660
 
1642
1661
  for (const result of results) {
1643
1662
  const content = result.content;
1644
1663
  if (!content) continue;
1645
-
1646
- if (result.type === "OCR") {
1647
- const tagsStr = content.tags?.length ? `\nTags: ${content.tags.join(", ")}` : "";
1648
- // result.type is "OCR" by historical naming, but content.text_source
1649
- // tells us if the text actually came from the accessibility tree
1650
- // (primary path) or OCR (fallback). Use it to label honestly.
1651
- const tag = screenTag(content.text_source);
1652
- formattedResults.push(
1653
- `${tag} ${content.app_name || "?"} | ${content.window_name || "?"}\n` +
1654
- `${content.timestamp || ""}\n` +
1655
- `${truncateMiddle(content.text || "", effectiveCap)}` +
1656
- tagsStr
1657
- );
1658
- if (includeFrames && content.frame) {
1659
- images.push({
1660
- data: content.frame,
1661
- context: `${content.app_name} at ${content.timestamp}`,
1662
- });
1663
- }
1664
- } else if (result.type === "Audio") {
1665
- const tagsStr = content.tags?.length ? `\nTags: ${content.tags.join(", ")}` : "";
1666
- formattedResults.push(
1667
- `[Audio] ${content.device_name || "?"}\n` +
1668
- `${content.timestamp || ""}\n` +
1669
- `${truncateMiddle(content.transcription || "", effectiveCap)}` +
1670
- tagsStr
1671
- );
1672
- } else if (result.type === "UI" || result.type === "Accessibility") {
1673
- formattedResults.push(
1674
- `[Accessibility] ${content.app_name || "?"} | ${content.window_name || "?"}\n` +
1675
- `${content.timestamp || ""}\n` +
1676
- `${truncateMiddle(content.text || "", effectiveCap)}`
1677
- );
1678
- } else if (result.type === "Input") {
1679
- formattedResults.push(inputEventContent(content, effectiveCap));
1680
- } else if (result.type === "Memory") {
1681
- const tagsStr = content.tags?.length ? ` [${content.tags.join(", ")}]` : "";
1682
- const importance =
1683
- content.importance != null ? ` (importance: ${content.importance})` : "";
1684
- // frame_id links a memory back to the exact moment — jump there with
1685
- // frame-context / get-frame-elements (frame_id=N).
1686
- const frameRef = content.frame_id != null ? ` frame:${content.frame_id}` : "";
1687
- formattedResults.push(
1688
- `[Memory #${content.id}]${tagsStr}${importance}${frameRef}\n` +
1689
- `${content.created_at || ""}\n` +
1690
- `${truncateMiddle(content.content || "", effectiveCap)}`
1691
- );
1692
- } else if (result.type === "Parsed") {
1693
- formattedResults.push(
1694
- `[Parsed] ${content.app_name || "?"} | ${content.window_name || "?"} | frame ${content.frame_id || "?"}\n` +
1695
- `${content.timestamp || ""}\n` +
1696
- `${truncateMiddle(content.text || "", effectiveCap)}`
1697
- );
1664
+ const hit = formatSearchHit(result, effectiveCap);
1665
+ if (hit) { formattedResults.push(hit.text); truncated ||= hit.truncated; }
1666
+ if (includeFrames && result.type === "OCR" && content.frame) {
1667
+ images.push({ data: content.frame, context: `${content.app_name} at ${content.timestamp}` });
1698
1668
  }
1699
1669
  }
1700
1670
 
1701
- const header =
1702
- `Results: ${results.length}/${pagination.total || "?"}` +
1703
- (pagination.total > results.length
1704
- ? ` (use offset=${(pagination.offset || 0) + results.length} for more)`
1705
- : "");
1671
+ observeSearchResult(results.length, truncated);
1672
+ const header = searchResultHeader(results.length, pagination);
1706
1673
 
1707
1674
  // Co-occurring tags (only present when include_related=true + tags set).
1708
1675
  // Compact one-liner per namespace so it's cheap to read.
@@ -2316,6 +2283,9 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
2316
2283
  };
2317
2284
  }
2318
2285
 
2286
+ case "search-chats":
2287
+ return await searchChats(args, callAPI);
2288
+
2319
2289
  case "list-workflows":
2320
2290
  case "get-workflow":
2321
2291
  return await readWorkflowTool(name, args, callAPI);
@@ -2432,6 +2402,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
2432
2402
  throw new Error(`Unknown tool: ${name}`);
2433
2403
  }
2434
2404
  } catch (error) {
2405
+ observeMcpError(error);
2435
2406
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
2436
2407
  if (!(error instanceof BackendDownError) && !(error instanceof BackendHttpError)) {
2437
2408
  captureMcpMessage("tool call failed", "error", { phase: "tool_call", tool: name });
@@ -2443,7 +2414,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
2443
2414
  content: [{ type: "text", text: `Error executing ${name}: ${errorMessage}` }],
2444
2415
  };
2445
2416
  }
2446
- });
2417
+ }));
2447
2418
 
2448
2419
  // Run the server
2449
2420
  async function main() {
@@ -2453,6 +2424,16 @@ async function main() {
2453
2424
  console.error(`[screenpipe-mcp] v${PKG_VERSION} phase=connect target=${SCREENPIPE_API}`);
2454
2425
  const transport = new StdioServerTransport();
2455
2426
  await server.connect(transport);
2427
+ // The SDK does not close its transport on stdin EOF. An outstanding fetch
2428
+ // can otherwise keep an abandoned helper alive indefinitely after its host
2429
+ // exits. This process belongs to this one stdio client only.
2430
+ process.stdin.once("end", () => {
2431
+ const deadline = setTimeout(() => process.exit(0), 500);
2432
+ void server.close()
2433
+ .then(() => flushMcpTelemetry(250))
2434
+ .catch(() => {})
2435
+ .finally(() => { clearTimeout(deadline); process.exit(0); });
2436
+ });
2456
2437
  console.error("[screenpipe-mcp] phase=connected transport=stdio");
2457
2438
  // Warm the API key in the background so the first tool call doesn't pay the
2458
2439
  // discovery latency. Never awaited here — key discovery must not gate attach.
@@ -56,6 +56,11 @@ describe("createMcpQualifiedValueReporter", () => {
56
56
  ["gemini", "gemini-cli", "gemini"],
57
57
  ["runner", "Runner", "runner"],
58
58
  ["vscode", "vscode", "vscode"],
59
+ ["opencode", "OpenCode", "opencode"],
60
+ ["antigravity", "Antigravity", "antigravity"],
61
+ ["cline", "Cline", "cline"],
62
+ ["kiro", "Kiro", "kiro"],
63
+ ["perplexity", "Perplexity", "perplexity"],
59
64
  ["grokbot", "Grok Bot", "grokbot"],
60
65
  ])("recognizes configured %s and its handshake name", (configured, protocol, expected) => {
61
66
  expect(resolveMcpClient(configured, "unrecognized-client")).toBe(expected);
@@ -4,7 +4,7 @@
4
4
 
5
5
  const CLIENTS = [
6
6
  "claude", "chatgpt", "codex", "cursor", "gemini", "openclaw",
7
- "hermes", "runner", "windsurf", "vscode", "grok", "grokbot",
7
+ "hermes", "runner", "windsurf", "vscode", "opencode", "antigravity", "cline", "kiro", "perplexity", "grok", "grokbot",
8
8
  ] as const;
9
9
  export type McpClient = (typeof CLIENTS)[number] | "unknown";
10
10
 
@@ -0,0 +1,80 @@
1
+ // screenpipe — AI that knows everything you've seen, said, or heard
2
+ // https://screenpipe.com
3
+ import { it, expect } from "vitest";
4
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
5
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
6
+ import { createServer } from "node:http";
7
+ import { execFileSync } from "node:child_process";
8
+ import path from "node:path";
9
+
10
+ it("advertises screen text and preserves legacy search behavior over the built MCP transport", async () => {
11
+ const root = path.resolve(__dirname, "..");
12
+ execFileSync("bun", ["run", "build"], { cwd: root, stdio: "pipe", timeout: 120000 });
13
+ const requests: URL[] = [];
14
+ const api = createServer((req, res) => {
15
+ const url = new URL(req.url || "/", "http://localhost");
16
+ requests.push(url);
17
+ res.setHeader("Content-Type", "application/json");
18
+ if (req.headers.authorization !== "Bearer fixture-key") {
19
+ res.writeHead(403).end("{}");
20
+ return;
21
+ }
22
+ // A backend that only accepts the legacy name proves MCP translates it.
23
+ const sources = url.searchParams.get("content_type") === "ocr"
24
+ ? ["accessibility", "ocr", undefined] : [];
25
+ res.end(JSON.stringify({
26
+ data: sources.map((source, index) => ({ type: "OCR", content: {
27
+ frame_id: index + 1, app_name: "Fixture", window_name: "Screen text",
28
+ timestamp: "2026-01-01T12:00:00Z", text: `Captured text ${index + 1}`,
29
+ text_source: source, tags: ["project:fixture"], frame: "c3ludGhldGlj",
30
+ } })),
31
+ pagination: { total: sources.length ? 10 : 0, limit: 3, offset: Number(url.searchParams.get("offset") || 0) },
32
+ }));
33
+ });
34
+ await new Promise<void>(resolve => api.listen(0, "127.0.0.1", resolve));
35
+ const address = api.address();
36
+ if (!address || typeof address === "string") throw new Error("No fixture API address");
37
+ const client = new Client({ name: "screen-search-contract", version: "1.0" });
38
+ const transport = new StdioClientTransport({
39
+ command: process.execPath, args: [path.join(root, "dist/cli.js")],
40
+ env: { PATH: process.env.PATH || "", SCREENPIPE_LOCAL_API_URL: `http://127.0.0.1:${address.port}`,
41
+ SCREENPIPE_LOCAL_API_KEY: "fixture-key", SCREENPIPE_DISABLE_TELEMETRY: "1" }, stderr: "pipe",
42
+ });
43
+ try {
44
+ await client.connect(transport);
45
+ const { tools } = await client.listTools();
46
+ const property = tools.find(tool => tool.name === "search-content")!.inputSchema.properties!.content_type as { enum: string[]; description: string };
47
+ expect(property.enum).toEqual(expect.arrayContaining(["screen", "ocr", "accessibility", "all", "audio", "parsed"]));
48
+ expect(property.description).toContain("Use 'screen' for screen text");
49
+ expect(property.description).toContain("legacy alias");
50
+ for (const contentType of ["screen", "ocr"]) {
51
+ const filters = { app_name: "Fixture", window_name: "Screen text", q: "Captured", tags: "project:fixture",
52
+ include_related: true, limit: 3, offset: 3, max_content_length: 100, include_frames: true };
53
+ const result = await client.callTool({ name: "search-content", arguments: {
54
+ content_type: contentType, start_time: "2026-01-01T00:00:00Z", end_time: "2026-01-02T00:00:00Z", ...filters,
55
+ } });
56
+ expect(result.isError).not.toBe(true);
57
+ const text = JSON.stringify(result.content);
58
+ expect(text).toContain("[Screen·a11y]");
59
+ expect(text).toContain("[Screen·ocr]");
60
+ expect(text).toContain("[Screen] Fixture");
61
+ expect(text).toContain("offset=6");
62
+ expect(result.content).toEqual(expect.arrayContaining([expect.objectContaining({ type: "image", data: "c3ludGhldGlj" })]));
63
+ const params = requests.at(-1)!.searchParams;
64
+ expect(params.get("content_type")).toBe("ocr");
65
+ for (const [key, value] of Object.entries(filters)) expect(params.get(key)).toBe(String(value));
66
+ expect(Date.parse(params.get("start_time")!)).toBe(Date.parse("2026-01-01T00:00:00Z"));
67
+ expect(Date.parse(params.get("end_time")!)).toBe(Date.parse("2026-01-02T00:00:00Z"));
68
+ }
69
+ for (const contentType of ["all", "accessibility", "audio", "input", "memory", "parsed", undefined]) {
70
+ await client.callTool({ name: "search-content", arguments: {
71
+ start_time: "2026-01-01", ...(contentType ? { content_type: contentType } : {}),
72
+ } });
73
+ expect(requests.at(-1)!.searchParams.get("content_type")).toBe(contentType ?? null);
74
+ }
75
+ } finally {
76
+ await client.close();
77
+ await transport.close();
78
+ await new Promise<void>(resolve => api.close(() => resolve()));
79
+ }
80
+ }, 15000);
@@ -0,0 +1,22 @@
1
+ // screenpipe — AI that knows everything you've seen, said, or heard
2
+ // https://screenpipe.com
3
+ import { expect, it } from "vitest";
4
+ import { formatSearchHit, searchContentCap, searchResultHeader } from "./search-result";
5
+ it("preserves real references through truncation, without inventing missing IDs", () => {
6
+ const hit = formatSearchHit({type:"OCR",content:{frame_id:72,text:"HEAD"+"x".repeat(3000)+"TAIL",text_source:"accessibility"}},10)!;
7
+ expect(hit.truncated).toBe(true); expect(hit.text).toContain("frame_id=72"); expect(hit.text).toContain("screenpipe://frame/72");
8
+ expect(hit.text).toContain("HEAD"); expect(hit.text).toContain("TAIL"); expect(hit.text.length).toBeLessThan(250);
9
+ expect(formatSearchHit({type:"OCR",content:{text:"no source"}},100)!.text).not.toContain("Source:");
10
+ });
11
+ it("keeps audio references and input text, including explicit unlimited reads", () => {
12
+ expect(formatSearchHit({type:"Audio",content:{chunk_id:31,timestamp:"2026-10-01T00:00:00Z",transcription:"speech"}},100)!.text).toContain("chunk_id=31");
13
+ const input={type:"Input",content:{frame_id:72,text_content:"long input"}};
14
+ expect(formatSearchHit(input,3)!.truncated).toBe(true);
15
+ expect(formatSearchHit(input,0)!.text).toContain("long input"); expect(formatSearchHit(input,0)!.truncated).toBe(false);
16
+ });
17
+ it("only suggests an offset when a next page exists", () => {
18
+ expect(searchResultHeader(5,{total:10,offset:5})).not.toContain("offset=");
19
+ expect(searchResultHeader(5,{total:10,offset:0})).toContain("offset=5");
20
+ expect(searchResultHeader(0,{total:10,offset:0})).not.toContain("offset=");
21
+ expect(searchContentCap(undefined)).toBe(1000); expect(searchContentCap(-1)).toBe(1000);
22
+ });