YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(mcp): keyword-search arg mapping, time normalization, better errors, OCR truncation (#3504)
Louis Beaumont8c26a9350900
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-keyword-search-store.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-keyword-search-store.tsxindex 845bd285a..5f613ee64 100644--- a/apps/screenpipe-app-tauri/lib/hooks/use-keyword-search-store.tsx+++ b/apps/screenpipe-app-tauri/lib/hooks/use-keyword-search-store.tsx@@ -22,6 +22,10 @@ export interface SearchMatch {confidence: number;text: string;url: string;+ // "accessibility" (OS-native tree, primary) or "ocr" (fallback for+ // terminals/canvas/weak a11y). Null for legacy rows captured before+ // the field was tracked.+ text_source?: "accessibility" | "ocr" | null;}export interface SearchMatchGroup {diff --git a/apps/screenpipe-app-tauri/lib/utils.ts b/apps/screenpipe-app-tauri/lib/utils.tsindex 258288c0a..ae297bc02 100644--- a/apps/screenpipe-app-tauri/lib/utils.ts+++ b/apps/screenpipe-app-tauri/lib/utils.ts@@ -2,7 +2,7 @@ import { stat } from "@tauri-apps/plugin-fs";import { platform } from "@tauri-apps/plugin-os";import { twMerge } from "tailwind-merge";type ContentItem =- | { type: "OCR"; content: { text: string } }+ | { type: "OCR"; content: { text: string; text_source?: "accessibility" | "ocr" | null } }| { type: "Audio"; content: { transcription: string } }| { type: "UI"; content: { text: string } }| { type: "Input"; content: Record<string, unknown> };diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rsindex 9e208e8a7..dc1498e4e 100644--- a/crates/screenpipe-db/src/db.rs+++ b/crates/screenpipe-db/src/db.rs@@ -3613,7 +3613,8 @@ impl DatabaseManager {COALESCE(video_chunks.device_name, frames.device_name) as device_name,GROUP_CONCAT(tags.name, ',') as tags,frames.browser_url,- frames.focused+ frames.focused,+ frames.text_sourceFROM framesLEFT JOIN video_chunks ON frames.video_chunk_id = video_chunks.idLEFT JOIN ocr_text ON frames.id = ocr_text.frame_id@@ -3683,6 +3684,7 @@ impl DatabaseManager {.unwrap_or_default(),browser_url: raw.browser_url,focused: raw.focused,+ text_source: raw.text_source,}).collect())}@@ -7133,7 +7135,7 @@ impl DatabaseManager {// the entire result set, hiding results from other apps.format!(r#"-SELECT id, timestamp, url, app_name, window_name, ocr_text, text_json, accessibility_tree_json FROM (+SELECT id, timestamp, url, app_name, window_name, ocr_text, text_json, accessibility_tree_json, text_source FROM (SELECTf.id,f.timestamp,@@ -7143,6 +7145,7 @@ SELECT id, timestamp, url, app_name, window_name, ocr_text, text_json, accessibiCOALESCE(f.full_text, o.text, f.accessibility_text, '') as ocr_text,o.text_json,f.accessibility_tree_json,+ f.text_source,ROW_NUMBER() OVER (PARTITION BY COALESCE(f.app_name, o.app_name, '')ORDER BY f.timestamp {order_dir}, {relevance} DESC@@ -7171,7 +7174,8 @@ SELECTCOALESCE(f.window_name, o.window_name) as window_name,COALESCE(f.full_text, o.text, f.accessibility_text, '') as ocr_text,o.text_json,- f.accessibility_tree_json+ f.accessibility_tree_json,+ f.text_sourceFROM frames fLEFT JOIN ocr_text o ON f.id = o.frame_idWHERE {}@@ -7239,6 +7243,7 @@ LIMIT ? OFFSET ?confidence: calculate_confidence(&positions),text: row.ocr_text.clone(),url: row.url.clone(),+ text_source: row.text_source.clone(),}}).collect())@@ -7562,6 +7567,9 @@ LIMIT ? OFFSET ?confidence: 0.0,text: String::new(),url: row.url,+ // FrameRowLight skips text/text_source for speed; grouped+ // results don't surface text to clients, so None is fine.+ text_source: None,}).collect())}@@ -10253,6 +10261,7 @@ mod tests {confidence,text: String::new(),url: url.to_string(),+ text_source: None,}}diff --git a/crates/screenpipe-db/src/types.rs b/crates/screenpipe-db/src/types.rsindex 9fca9929b..1061f5949 100644--- a/crates/screenpipe-db/src/types.rs+++ b/crates/screenpipe-db/src/types.rs@@ -115,6 +115,10 @@ pub struct OCRResultRaw {pub browser_url: Option<String>,pub focused: Option<bool>,pub device_name: String,+ /// Origin of the row's text: `"accessibility"` (OS-native tree, primary)+ /// or `"ocr"` (fallback for terminals, canvas-rendered apps, weak a11y).+ /// `None` for legacy rows captured before text_source was tracked.+ pub text_source: Option<String>,}#[derive(OaSchema, Debug, Serialize, Deserialize)]@@ -133,6 +137,10 @@ pub struct OCRResult {pub browser_url: Option<String>,pub focused: Option<bool>,pub device_name: String,+ /// Origin of `ocr_text`: `"accessibility"` (OS-native tree, primary) or+ /// `"ocr"` (fallback). `None` for legacy rows. Despite the field name+ /// `ocr_text`, the content is accessibility-derived for most captures.+ pub text_source: Option<String>,}/// Content type for search queries.@@ -524,6 +532,8 @@ pub struct SearchMatch {// pub context: Option<String>,pub text: String,pub url: String,+ /// Origin of `text`: `"accessibility"` or `"ocr"`. `None` for legacy rows.+ pub text_source: Option<String>,}#[derive(OaSchema, Serialize)]@@ -546,6 +556,8 @@ pub struct FrameRow {pub text_json: String,/// Accessibility tree JSON — used as fallback for bounding boxes when OCR text_json is emptypub accessibility_tree_json: Option<String>,+ /// Origin of `ocr_text`: `"accessibility"` or `"ocr"`. `None` for legacy rows.+ pub text_source: Option<String>,}/// Lightweight frame row for grouped search — skips text/text_json columns.diff --git a/crates/screenpipe-engine/src/routes/content.rs b/crates/screenpipe-engine/src/routes/content.rsindex c1f0aded9..3e263514b 100644--- a/crates/screenpipe-engine/src/routes/content.rs+++ b/crates/screenpipe-engine/src/routes/content.rs@@ -69,6 +69,12 @@ pub struct OCRContent {pub browser_url: Option<String>,pub focused: Option<bool>,pub device_name: String,+ /// Origin of `text`. `"accessibility"` (OS-native tree, primary path) or+ /// `"ocr"` (fallback for terminals, canvas apps, weak a11y). `None` for+ /// legacy rows captured before the field was tracked. The variant is+ /// historically called OCR but most captures are accessibility-derived+ /// — read this field to know which path produced the text.+ pub text_source: Option<String>,}#[derive(OaSchema, Serialize, Deserialize, Debug, Clone)]diff --git a/crates/screenpipe-engine/src/routes/search.rs b/crates/screenpipe-engine/src/routes/search.rsindex 211dd6f51..59cb88e36 100644--- a/crates/screenpipe-engine/src/routes/search.rs+++ b/crates/screenpipe-engine/src/routes/search.rs@@ -352,6 +352,7 @@ pub(crate) async fn search(browser_url: ocr.browser_url.clone(),focused: ocr.focused,device_name: ocr.device_name.clone(),+ text_source: ocr.text_source.clone(),}),SearchResult::Audio(audio) => {let transcription = truncate(audio.transcription.clone());diff --git a/packages/screenpipe-mcp/src/index.ts b/packages/screenpipe-mcp/src/index.tsindex aff3c547a..314bf37e2 100644--- a/packages/screenpipe-mcp/src/index.ts+++ b/packages/screenpipe-mcp/src/index.ts@@ -262,11 +262,11 @@ const TOOLS: Tool[] = [{name: "search-content",description:- "Search screen text, audio transcriptions, input events, and memories. " +- "Returns timestamped results with app context. " +- "IMPORTANT: prefer activity-summary for broad questions ('what was I doing?'). " +- "Use search-content only when you need specific text/content. " +- "Start with limit=5, increase only if needed. Results can be large — use max_content_length=500 to truncate.",+ "Search screen text, audio transcriptions, input events, and memories. Returns timestamped results with app context. " ++ "USE WHEN: you need the actual text/content of a moment — quotes, OCR snippets, transcript lines — or want to filter by speaker/window. " ++ "DO NOT USE for: broad questions like 'what was I doing?' (use activity-summary, it pre-summarizes apps + windows + transcripts). " ++ "Also DO NOT USE for: targeted UI controls (use search-elements). " ++ "Start with limit=5, increase only if needed. Per-result text is auto-truncated to 1000 chars; pass max_content_length=0 to opt out, or a custom integer to override.",annotations: { title: "Search Content", readOnlyHint: true, openWorldHint: false, idempotentHint: true },inputSchema: {type: "object",@@ -278,14 +278,15 @@ const TOOLS: Tool[] = [content_type: {type: "string",enum: ["all", "ocr", "audio", "input", "accessibility", "memory"],- description: "Filter by content type. 'accessibility' is preferred for screen text (OS-native). 'ocr' is fallback for apps without accessibility support. Default: 'all'.",+ description:+ "Filter by content type. 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'.",default: "all",},limit: { type: "integer", description: "Max results (default 10, max 20). Start with 5 for exploration.", default: 10 },offset: { type: "integer", description: "Pagination offset. Use when results say 'use offset=N for more'.", default: 0 },start_time: {type: "string",- description: "ISO 8601 UTC or relative (e.g. '2h ago', '1d ago'). Always provide to avoid scanning entire history.",+ description: "Accepted: ISO 8601 ('2024-01-15T10:00:00Z'), 'Nh ago' / 'Nd ago' / 'Nw ago', 'now', 'yesterday', 'today', or bare 'YYYY-MM-DD'. Always provide to avoid scanning entire history.",},end_time: {type: "string",@@ -329,9 +330,9 @@ const TOOLS: Tool[] = [name: "activity-summary",description:"Rich activity overview: app usage, window/tab titles with URLs and time spent, key text per context, audio transcriptions. " +- "USE THIS FIRST for broad questions: 'what was I doing?', 'how long on X?', 'which apps?'. " +- "The 'windows' field shows exactly what the user worked on (e.g. 'Debug crash issue — 20 min', 'Stripe pricing page — 5 min'). " +- "Usually sufficient without further searches.",+ "USE WHEN: any broad question about what the user did — 'what was I doing?', 'how long on X?', 'which apps?', 'recap my morning'. " ++ "This is almost always the right first call for time-range questions — usually sufficient without follow-up searches. " ++ "DO NOT USE for: finding a specific keyword (use keyword-search) or a specific UI control (use search-elements).",annotations: { title: "Activity Summary", readOnlyHint: true, openWorldHint: false, idempotentHint: true },inputSchema: {type: "object",@@ -346,9 +347,9 @@ const TOOLS: Tool[] = [{name: "search-elements",description:- "Search UI elements (buttons, links, text fields) from the accessibility tree. " +- "Lighter than search-content for targeted UI lookups. " +- "Use when you need to find specific UI controls or page structure, not general content.",+ "Search UI elements (buttons, links, text fields) from the accessibility tree, filterable by role. " ++ "USE WHEN: you want a specific UI control or page-structure question — 'find every Submit button I saw', 'list the links in that page'. " ++ "DO NOT USE for: general text/content (use search-content) or fast keyword lookup (use keyword-search).",annotations: { title: "Search Elements", readOnlyHint: true, openWorldHint: false, idempotentHint: true },inputSchema: {type: "object",@@ -596,19 +597,21 @@ const TOOLS: Tool[] = [{name: "keyword-search",description:- "Fast keyword search using FTS index. Faster than search-content for exact keyword matching. " +- "Returns frame IDs and matched text.",+ "Fast FTS5 keyword search across OCR + audio combined. Returns matches with frame_id, app, timestamp, and text positions. " ++ "USE WHEN: you have a specific keyword/phrase and want the fastest hit-list (e.g. 'find every screen where I typed \"stripe\"'). " ++ "DO NOT USE for: structured filters by content_type / speaker / window — this endpoint ignores those (use search-content instead). " ++ "DO NOT USE for: broad questions like 'what was I doing' (use activity-summary).",annotations: { title: "Keyword Search", readOnlyHint: true, openWorldHint: false, idempotentHint: true },inputSchema: {type: "object",properties: {- q: { type: "string", description: "Keyword search query" },- content_type: { type: "string", enum: ["ocr", "audio", "all"], description: "Content type filter", default: "all" },- start_time: { type: "string", description: "ISO 8601 UTC or relative" },- end_time: { type: "string", description: "ISO 8601 UTC or relative" },- app_name: { type: "string", description: "Filter by app name" },+ q: { type: "string", description: "Keyword query (FTS5 syntax: quoted phrases, AND/OR, prefix*)" },+ start_time: { type: "string", description: "ISO 8601 UTC, 'Nh ago' / 'Nd ago' / 'Nw ago', 'now', 'yesterday', 'today', or 'YYYY-MM-DD'" },+ end_time: { type: "string", description: "Same formats as start_time" },+ app_name: { type: "string", description: "Filter by exact app name (case-sensitive, e.g. 'Google Chrome')" },limit: { type: "integer", description: "Max results (default 20)", default: 20 },offset: { type: "integer", description: "Pagination offset", default: 0 },+ fuzzy_match: { type: "boolean", description: "Enable typo-tolerant matching", default: false },},required: ["q"],},@@ -795,7 +798,7 @@ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {- **Use max_content_length=500** to keep responses compact- **Don't use q for audio** — transcriptions are noisy, q filters too aggressively. Search audio by time range and speaker instead- **app_name is case-sensitive** — use exact names: "Google Chrome" not "chrome"-- **content_type=accessibility is preferred** for screen text (OS-native). ocr is fallback for apps without accessibility support+- **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## Common Patterns@@ -821,21 +824,154 @@ Never fabricate IDs or timestamps — only use values from actual results.});// ----------------------------------------------------------------------------// Helper+// Helpers// ---------------------------------------------------------------------------++// Thrown by fetchAPI / callAPI when the backend is unreachable. Caught in the+// tool dispatcher to surface an actionable hint ("backend not running")+// instead of the opaque "fetch failed" the model used to see.+class BackendDownError extends Error {+ constructor(public readonly cause: unknown) {+ super(+ `screenpipe backend not running on ${SCREENPIPE_API}. ` ++ `Start it with \`screenpipe\` in a terminal, or open the screenpipe desktop app.`,+ );+ this.name = "BackendDownError";+ }+}++// Thrown when the backend returns a non-2xx. Carries the server's response+// body so the dispatcher can include it in the user-visible error message.+class BackendHttpError extends Error {+ constructor(+ public readonly status: number,+ public readonly bodyText: string,+ endpoint: string,+ ) {+ let hint = "";+ if (status === 401 || status === 403) {+ hint =+ " — API key not accepted. Set SCREENPIPE_LOCAL_API_KEY in your MCP " ++ "launcher env, or install the screenpipe desktop app so the MCP can " ++ "discover the key automatically.";+ } else if (status === 404) {+ hint =+ " — endpoint not found. The backend may be on a different version than this MCP.";+ } else if (status === 400) {+ hint = " — bad request. Check argument names and types against the tool schema.";+ } else if (status >= 500) {+ hint = " — backend error. Check screenpipe logs.";+ }+ const trimmed = bodyText.trim().slice(0, 300);+ const bodyPart = trimmed ? ` body: ${trimmed}` : "";+ super(`HTTP ${status} from ${endpoint}${hint}${bodyPart}`);+ this.name = "BackendHttpError";+ }+}+async function fetchAPI(endpoint: string,options: RequestInit = {}): Promise<Response> {const url = `${SCREENPIPE_API}${endpoint}`;- return fetch(url, {- ...options,- headers: {- "Content-Type": "application/json",- ...(API_KEY ? { Authorization: `Bearer ${API_KEY}` } : {}),- ...options.headers,- },- });+ try {+ return await fetch(url, {+ ...options,+ headers: {+ "Content-Type": "application/json",+ ...(API_KEY ? { Authorization: `Bearer ${API_KEY}` } : {}),+ ...options.headers,+ },+ });+ } catch (e) {+ throw new BackendDownError(e);+ }+}++// Wrap a fetchAPI call: throw BackendHttpError on non-2xx with body included.+// Use from handlers instead of `if (!response.ok) throw new Error(...)`.+async function callAPI(endpoint: string, options: RequestInit = {}): Promise<Response> {+ const response = await fetchAPI(endpoint, options);+ if (!response.ok) {+ let body = "";+ try {+ body = await response.text();+ } catch {+ // body may not be readable; that's fine+ }+ throw new BackendHttpError(response.status, body, endpoint);+ }+ return response;+}++// Server's deserialize_flexible_datetime accepts ISO 8601 + "Nh ago" / "Nd ago"+// / "Nw ago" / "now". Models also try "yesterday", "today", and bare dates+// ("2026-05-17") — normalize those here so the request doesn't 400.+function normalizeTime(input: string | undefined): string | undefined {+ if (!input) return input;+ const s = input.trim();+ if (!s) return input;+ const lower = s.toLowerCase();+ if (lower === "yesterday") return "1d ago";+ if (lower === "today") {+ return `${new Date().toISOString().split("T")[0]}T00:00:00Z`;+ }+ if (lower === "tomorrow") {+ const t = new Date();+ t.setUTCDate(t.getUTCDate() + 1);+ return `${t.toISOString().split("T")[0]}T00:00:00Z`;+ }+ // Bare YYYY-MM-DD → start of day UTC+ if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return `${s}T00:00:00Z`;+ return s;+}++// Apply normalizeTime to start_time/end_time fields in an args object.+// Returns a new object — does not mutate the input.+function normalizeTimeFields(+ args: Record<string, unknown>,+): Record<string, unknown> {+ const out = { ...args };+ for (const k of ["start_time", "end_time"] as const) {+ if (typeof out[k] === "string") {+ out[k] = normalizeTime(out[k] as string);+ }+ }+ return out;+}++// Middle-truncate long strings: keep head + tail, mark the gap with how much+// was cut. Used to cap OCR/transcription text in search-content responses+// so a single call doesn't blow past Claude Code's per-tool output limit+// (one logged call returned 131k chars from a limit:10 search).+function truncateMiddle(text: string | null | undefined, max: number): string {+ if (!text) return text ?? "";+ if (max <= 0 || text.length <= max) return text;+ const halfLeft = Math.floor(max / 2);+ const halfRight = max - halfLeft;+ const cut = text.length - max;+ return (+ text.slice(0, halfLeft) ++ `…[${cut} chars truncated — pass max_content_length=0 for full text]…` ++ text.slice(text.length - halfRight)+ );+}++// Default per-result text cap for search-content when the caller didn't+// specify one. Tuned to keep limit=10 responses well under tool-output limits+// while still giving the model enough text to reason over.+const DEFAULT_SEARCH_CONTENT_TRUNCATE = 1000;++// Format the screen-text tag for a result. The server's `text_source` is+// "accessibility" (OS-native tree, primary path) or "ocr" (fallback for+// terminals, canvas, weak a11y). Older rows have no text_source, so we+// fall back to a bare `[Screen]`. The result type is historically called+// OCR in the engine but most captures are accessibility-derived — surface+// the actual source so the model picks filters correctly.+function screenTag(textSource: unknown): string {+ if (textSource === "accessibility") return "[Screen·a11y]";+ if (textSource === "ocr") return "[Screen·ocr]";+ return "[Screen]";}// ---------------------------------------------------------------------------@@ -852,16 +988,24 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {switch (name) {case "search-content": {const includeFrames = args.include_frames === true;+ const normalized = normalizeTimeFields(args);+ // Default text cap if the caller didn't pass max_content_length.+ // Keeps single calls under Claude Code's per-tool output limit.+ const userCap = normalized.max_content_length;+ const effectiveCap =+ typeof userCap === "number"+ ? userCap+ : userCap === undefined+ ? DEFAULT_SEARCH_CONTENT_TRUNCATE+ : Number(userCap);const params = new URLSearchParams();- for (const [key, value] of Object.entries(args)) {+ for (const [key, value] of Object.entries(normalized)) {if (value !== null && value !== undefined) {params.append(key, String(value));}}- const response = await fetchAPI(`/search?${params.toString()}`);- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);-+ const response = await callAPI(`/search?${params.toString()}`);const data = await response.json();const results = data.data || [];const pagination = data.pagination || {};@@ -891,10 +1035,14 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {if (result.type === "OCR") {const tagsStr = content.tags?.length ? `\nTags: ${content.tags.join(", ")}` : "";+ // result.type is "OCR" by historical naming, but content.text_source+ // tells us if the text actually came from the accessibility tree+ // (primary path) or OCR (fallback). Use it to label honestly.+ const tag = screenTag(content.text_source);formattedResults.push(- `[OCR] ${content.app_name || "?"} | ${content.window_name || "?"}\n` ++ `${tag} ${content.app_name || "?"} | ${content.window_name || "?"}\n` +`${content.timestamp || ""}\n` +- `${content.text || ""}` ++ `${truncateMiddle(content.text || "", effectiveCap)}` +tagsStr);if (includeFrames && content.frame) {@@ -908,14 +1056,14 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {formattedResults.push(`[Audio] ${content.device_name || "?"}\n` +`${content.timestamp || ""}\n` +- `${content.transcription || ""}` ++ `${truncateMiddle(content.transcription || "", effectiveCap)}` +tagsStr);} else if (result.type === "UI" || result.type === "Accessibility") {formattedResults.push(`[Accessibility] ${content.app_name || "?"} | ${content.window_name || "?"}\n` +`${content.timestamp || ""}\n` +- `${content.text || ""}`+ `${truncateMiddle(content.text || "", effectiveCap)}`);} else if (result.type === "Memory") {const tagsStr = content.tags?.length ? ` [${content.tags.join(", ")}]` : "";@@ -924,7 +1072,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {formattedResults.push(`[Memory #${content.id}]${tagsStr}${importance}\n` +`${content.created_at || ""}\n` +- `${content.content || ""}`+ `${truncateMiddle(content.content || "", effectiveCap)}`);}}@@ -949,15 +1097,15 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {}case "list-meetings": {+ const normalized = normalizeTimeFields(args);const params = new URLSearchParams();- for (const [key, value] of Object.entries(args)) {+ for (const [key, value] of Object.entries(normalized)) {if (value !== null && value !== undefined) {params.append(key, String(value));}}- const response = await fetchAPI(`/meetings?${params.toString()}`);- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);+ const response = await callAPI(`/meetings?${params.toString()}`);const meetings = await response.json();@@ -984,15 +1132,15 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {}case "activity-summary": {+ const normalized = normalizeTimeFields(args);const params = new URLSearchParams();- for (const [key, value] of Object.entries(args)) {+ for (const [key, value] of Object.entries(normalized)) {if (value !== null && value !== undefined) {params.append(key, String(value));}}- const response = await fetchAPI(`/activity-summary?${params.toString()}`);- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);+ const response = await callAPI(`/activity-summary?${params.toString()}`);const data = await response.json();@@ -1067,15 +1215,15 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {}case "search-elements": {+ const normalized = normalizeTimeFields(args);const params = new URLSearchParams();- for (const [key, value] of Object.entries(args)) {+ for (const [key, value] of Object.entries(normalized)) {if (value !== null && value !== undefined) {params.append(key, String(value));}}- const response = await fetchAPI(`/elements?${params.toString()}`);- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);+ const response = await callAPI(`/elements?${params.toString()}`);const data = await response.json();const elements = data.data || [];@@ -1126,8 +1274,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {return { content: [{ type: "text", text: "Error: frame_id is required" }] };}- const response = await fetchAPI(`/frames/${frameId}/context`);- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);+ const response = await callAPI(`/frames/${frameId}/context`);const data = await response.json();const lines = [`Frame ${data.frame_id} (source: ${data.text_source})`];@@ -1157,8 +1304,8 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {}case "export-video": {- const startTime = args.start_time as string;- const endTime = args.end_time as string;+ const startTime = normalizeTime(args.start_time as string);+ const endTime = normalizeTime(args.end_time as string);const fps = (args.fps as number) || 1.0;if (!startTime || !endTime) {@@ -1175,11 +1322,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {limit: "10000",});- const searchResponse = await fetchAPI(`/search?${searchParams.toString()}`);- if (!searchResponse.ok) {- throw new Error(`Failed to search for frames: HTTP ${searchResponse.status}`);- }-+ const searchResponse = await callAPI(`/search?${searchParams.toString()}`);const searchData = await searchResponse.json();const results = searchData.data || [];@@ -1298,9 +1441,8 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {case "update-memory": {if (args.delete && args.id) {- const response = await fetchAPI(`/memories/${args.id}`, { method: "DELETE" });- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);- return { content: [{ type: "text", text: `Memory ${args.id} deleted.` }] };+ const response = await callAPI(`/memories/${args.id}`, { method: "DELETE" });+ return { content: [{ type: "text", text: `Memory ${args.id} deleted.` }] };}if (args.id) {const body: Record<string, unknown> = {};@@ -1308,12 +1450,11 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {if (args.tags !== undefined) body.tags = args.tags;if (args.importance !== undefined) body.importance = args.importance;if (args.source_context !== undefined) body.source_context = args.source_context;- const response = await fetchAPI(`/memories/${args.id}`, {+ const response = await callAPI(`/memories/${args.id}`, {method: "PUT",body: JSON.stringify(body),});- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);- const memory = await response.json();+ const memory = await response.json();return {content: [{ type: "text", text: `Memory ${memory.id} updated: "${memory.content}"` }],};@@ -1330,11 +1471,10 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {importance: args.importance ?? 0.5,};if (args.source_context) memoryBody.source_context = args.source_context;- const memoryResponse = await fetchAPI("/memories", {+ const memoryResponse = await callAPI("/memories", {method: "POST",body: JSON.stringify(memoryBody),});- if (!memoryResponse.ok) throw new Error(`HTTP error: ${memoryResponse.status}`);const newMemory = await memoryResponse.json();return {content: [@@ -1351,12 +1491,26 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {};if (args.timeout_secs) notifBody.timeout = Number(args.timeout_secs) * 1000;if (args.actions) notifBody.actions = args.actions;- const notifResponse = await fetch("http://localhost:11435/notify", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(notifBody),- });- if (!notifResponse.ok) throw new Error(`HTTP error: ${notifResponse.status}`);+ // send-notification hits the desktop notify daemon on a separate port+ // (11435), not the screenpipe API. Keep direct fetch with friendlier+ // error so the model sees an actionable message if the daemon's down.+ let notifResponse: Response;+ try {+ notifResponse = await fetch("http://localhost:11435/notify", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(notifBody),+ });+ } catch (e) {+ throw new Error(+ "notification daemon not reachable on localhost:11435 — is the screenpipe desktop app running?",+ );+ }+ if (!notifResponse.ok) {+ let body = "";+ try { body = await notifResponse.text(); } catch {}+ throw new Error(`notify daemon HTTP ${notifResponse.status}${body ? `: ${body.slice(0, 200)}` : ""}`);+ }const notifResult = await notifResponse.json();return {content: [{ type: "text", text: `Notification sent: ${notifResult.message}` }],@@ -1364,8 +1518,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {}case "health-check": {- const response = await fetchAPI("/health");- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);+ const response = await callAPI("/health");const data = await response.json();return {content: [{ type: "text", text: JSON.stringify(data, null, 2) }],@@ -1373,8 +1526,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {}case "list-audio-devices": {- const response = await fetchAPI("/audio/list");- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);+ const response = await callAPI("/audio/list");const devices = await response.json();if (!Array.isArray(devices) || devices.length === 0) {return { content: [{ type: "text", text: "No audio devices found." }] };@@ -1389,8 +1541,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {}case "list-monitors": {- const response = await fetchAPI("/vision/list");- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);+ const response = await callAPI("/vision/list");const monitors = await response.json();if (!Array.isArray(monitors) || monitors.length === 0) {return { content: [{ type: "text", text: "No monitors found." }] };@@ -1411,11 +1562,10 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {if (!contentType || !id || !tags) {return { content: [{ type: "text", text: "Error: content_type, id, and tags are required" }] };}- const response = await fetchAPI(`/tags/${contentType}/${id}`, {+ const response = await callAPI(`/tags/${contentType}/${id}`, {method: "POST",body: JSON.stringify({ tags }),});- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);return {content: [{ type: "text", text: `Tags added to ${contentType}/${id}: ${tags.join(", ")}` }],};@@ -1426,8 +1576,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {if (!nameQuery) {return { content: [{ type: "text", text: "Error: name is required" }] };}- const response = await fetchAPI(`/speakers/search?name=${encodeURIComponent(nameQuery)}`);- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);+ const response = await callAPI(`/speakers/search?name=${encodeURIComponent(nameQuery)}`);const speakers = await response.json();if (!Array.isArray(speakers) || speakers.length === 0) {return { content: [{ type: "text", text: "No speakers found." }] };@@ -1444,8 +1593,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {case "list-unnamed-speakers": {const limit = (args.limit as number) || 10;const offset = (args.offset as number) || 0;- const response = await fetchAPI(`/speakers/unnamed?limit=${limit}&offset=${offset}`);- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);+ const response = await callAPI(`/speakers/unnamed?limit=${limit}&offset=${offset}`);const speakers = await response.json();if (!Array.isArray(speakers) || speakers.length === 0) {return { content: [{ type: "text", text: "No unnamed speakers found." }] };@@ -1466,11 +1614,10 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {const body: Record<string, unknown> = { id: speakerId };if (args.name !== undefined) body.name = args.name;if (args.metadata !== undefined) body.metadata = args.metadata;- const response = await fetchAPI("/speakers/update", {+ const response = await callAPI("/speakers/update", {method: "POST",body: JSON.stringify(body),});- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);return {content: [{ type: "text", text: `Speaker ${speakerId} updated.` }],};@@ -1482,11 +1629,10 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {if (!keepId || !mergeId) {return { content: [{ type: "text", text: "Error: speaker_to_keep_id and speaker_to_merge_id are required" }] };}- const response = await fetchAPI("/speakers/merge", {+ const response = await callAPI("/speakers/merge", {method: "POST",body: JSON.stringify({ speaker_to_keep_id: keepId, speaker_to_merge_id: mergeId }),});- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);return {content: [{ type: "text", text: `Merged speaker ${mergeId} into ${keepId}.` }],};@@ -1497,11 +1643,10 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {if (args.app) body.app = args.app;if (args.title) body.title = args.title;if (args.attendees) body.attendees = args.attendees;- const response = await fetchAPI("/meetings/start", {+ const response = await callAPI("/meetings/start", {method: "POST",body: JSON.stringify(body),});- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);const meeting = await response.json();return {content: [{ type: "text", text: `Meeting started (id: ${meeting.id || "ok"}).` }],@@ -1509,8 +1654,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {}case "stop-meeting": {- const response = await fetchAPI("/meetings/stop", { method: "POST" });- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);+ const response = await callAPI("/meetings/stop", { method: "POST" });return {content: [{ type: "text", text: "Meeting stopped." }],};@@ -1521,8 +1665,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {if (!meetingId) {return { content: [{ type: "text", text: "Error: id is required" }] };}- const response = await fetchAPI(`/meetings/${meetingId}`);- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);+ const response = await callAPI(`/meetings/${meetingId}`);const meeting = await response.json();return {content: [{ type: "text", text: JSON.stringify(meeting, null, 2) }],@@ -1549,12 +1692,11 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {],};}- const response = await fetchAPI(`/meetings/${meetingId}`, {+ const response = await callAPI(`/meetings/${meetingId}`, {method: "PATCH",headers: { "Content-Type": "application/json" },body: JSON.stringify(body),});- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);const updated = await response.json();return {content: [{ type: "text", text: JSON.stringify(updated, null, 2) }],@@ -1562,22 +1704,52 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {}case "keyword-search": {- const params = new URLSearchParams();- for (const [key, value] of Object.entries(args)) {- if (value !== null && value !== undefined) {- params.append(key, String(value));- }+ // Translate model-facing arg names to what the engine actually+ // accepts (KeywordSearchRequest in routes/search.rs):+ // q -> query (mandatory; the field is literally named `query`)+ // app_name -> app_names (comma-separated; serde splits it)+ // content_type: dropped — the keyword endpoint doesn't filter by type.+ // It searches OCR + audio together via the FTS index.+ // Without these mappings every keyword-search request 400s (and used+ // to: in logs, 25/25 calls failed before this fix).+ const queryStr = (args.query as string) ?? (args.q as string);+ if (!queryStr) {+ return {+ content: [{ type: "text", text: "Error: 'q' (search query) is required" }],+ };}- const response = await fetchAPI(`/search/keyword?${params.toString()}`);- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);+ const normalized = normalizeTimeFields(args);+ const params = new URLSearchParams();+ params.append("query", queryStr);+ if (normalized.start_time) params.append("start_time", String(normalized.start_time));+ if (normalized.end_time) params.append("end_time", String(normalized.end_time));+ if (normalized.limit !== undefined) params.append("limit", String(normalized.limit));+ if (normalized.offset !== undefined) params.append("offset", String(normalized.offset));+ if (normalized.app_name) params.append("app_names", String(normalized.app_name));+ if (normalized.app_names) params.append("app_names", String(normalized.app_names));+ if (args.fuzzy_match !== undefined) params.append("fuzzy_match", String(args.fuzzy_match));+ const response = await callAPI(`/search/keyword?${params.toString()}`);const data = await response.json();- const results = data.data || [];+ // /search/keyword returns a bare array (Vec<KeywordSearchMatch> from+ // routes/search.rs), not the {data, pagination} shape /search uses.+ // The old `data.data || []` always lost results.+ const results: Array<Record<string, unknown>> = Array.isArray(data)+ ? data+ : (data.data ?? []);if (results.length === 0) {return { content: [{ type: "text", text: "No keyword search results found." }] };}- const formatted = results.map((r: Record<string, unknown>) => {- const content = r.content as Record<string, unknown> | undefined;- return `[${r.type}] ${content?.app_name || "?"} | ${content?.timestamp || ""}\n${content?.text || content?.transcription || ""}`;+ const formatted = results.map((r) => {+ // Flat shape from search_with_text_positions: { app_name, frame_id,+ // timestamp, text, text_source, ... }. Truncate to keep responses+ // under tool-output limits. text_source is "accessibility" (primary)+ // or "ocr" (fallback) — show it so the model knows which path hit.+ const text = (r.text as string) || (r.transcription as string) || "";+ const tag = screenTag(r.text_source);+ return (+ `${tag} [frame:${r.frame_id ?? "?"}] ${r.app_name ?? "?"} | ${r.timestamp ?? ""}\n` ++ truncateMiddle(text, DEFAULT_SEARCH_CONTENT_TRUNCATE)+ );});return {content: [{ type: "text", text: `Results: ${results.length}\n\n${formatted.join("\n---\n")}` }],@@ -1589,8 +1761,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {if (!frameId) {return { content: [{ type: "text", text: "Error: frame_id is required" }] };}- const response = await fetchAPI(`/frames/${frameId}/elements`);- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);+ const response = await callAPI(`/frames/${frameId}/elements`);const elements = await response.json();if (!Array.isArray(elements) || elements.length === 0) {return { content: [{ type: "text", text: `No elements found for frame ${frameId}.` }] };@@ -1617,8 +1788,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {else {return { content: [{ type: "text", text: `Error: unknown action '${action}'` }] };}- const response = await fetchAPI(endpoint, { method: "POST" });- if (!response.ok) throw new Error(`HTTP error: ${response.status}`);+ await callAPI(endpoint, { method: "POST" });return {content: [{ type: "text", text: `Recording action '${action}' executed.` }],};@@ -1677,7 +1847,10 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {}} catch (error) {const errorMessage = error instanceof Error ? error.message : "Unknown error";+ // isError flags the result as a failure so the model retries with a+ // different approach instead of treating the error text as data.return {+ isError: true,content: [{ type: "text", text: `Error executing ${name}: ${errorMessage}` }],};}