Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat: add websearch tool via DuckDuckGo HTML (free, no API key)

Rishabh Bajpaie2578aceba05
diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
index f01eafd..65facac 100644
--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt
@@ -682,6 +682,27 @@ object ToolDefinitions {
}
)
+ val webSearch = tool(
+ "websearch",
+ "Search the web for information using a text query. Returns up to 10 results with titles, URLs, and snippets. " +
+ "Use this to find current information, documentation, tutorials, or anything online. " +
+ "The results are from DuckDuckGo — no API key needed. " +
+ "If you need the full content of a specific result, use webfetch on its URL.",
+ schema {
+ putJsonObject("properties") {
+ putJsonObject("query") {
+ put("type", "string")
+ put("description", "Search query (natural language or keywords).")
+ }
+ putJsonObject("numResults") {
+ put("type", "integer")
+ put("description", "Number of results to return (1-10). Default 5.")
+ }
+ }
+ putJsonArray("required") { add("query") }
+ }
+ )
+
val webFetch = tool(
"webfetch",
"Fetch content from an HTTP or HTTPS URL and return it as text. " +
@@ -1004,8 +1025,8 @@ object ToolDefinitions {
edit,
// Content search and file discovery
glob, grep,
- // Web fetching
- webFetch,
+ // Web search + fetch
+ webSearch, webFetch,
// Image reading (available to both Monitor and Operator)
readImage,
// Tier 3 additions
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index 1fd3925..8ea17b3 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -35,6 +35,7 @@ class ToolExecutor(context: Context) {
private val clipboardTool = ClipboardTool(appContext)
private val mediaCaptureTool = MediaCaptureTool(appContext)
// Tier 3 tools
+ private val webSearchTool = WebSearchTool()
private val webFetchTool = WebFetchTool()
private val questionTool = QuestionTool()
private val todoTool = TodoTool()
@@ -148,6 +149,10 @@ class ToolExecutor(context: Context) {
options = args["options"]?.jsonArray?.mapNotNull { it.jsonPrimitive?.content },
allowCustom = args["allowCustom"]?.jsonPrimitive?.booleanOrNull ?: true
)
+ "websearch" -> webSearchTool.search(
+ query = args.requireString("query") ?: return missing("query"),
+ numResults = args.requireInt("numResults") ?: 5
+ )
"webfetch" -> webFetchTool.fetch(
url = args.requireString("url") ?: return missing("url"),
format = args.requireString("format")
diff --git a/app/src/main/java/com/gotcha/tools/WebSearchTool.kt b/app/src/main/java/com/gotcha/tools/WebSearchTool.kt
new file mode 100644
index 0000000..1e0f36d
--- /dev/null
+++ b/app/src/main/java/com/gotcha/tools/WebSearchTool.kt
@@ -0,0 +1,106 @@
+package com.gotcha.tools
+
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import org.jsoup.Jsoup
+import java.util.concurrent.TimeUnit
+
+/**
+ * Web search tool — performs a search via DuckDuckGo's HTML endpoint.
+ * No API key required. Returns clean numbered results with title, URL, and snippet.
+ */
+class WebSearchTool {
+
+ companion object {
+ private const val TIMEOUT_SECONDS = 15L
+ private const val DUCKDUCKGO_HTML = "https://html.duckduckgo.com/html/"
+ }
+
+ private val client = OkHttpClient.Builder()
+ .connectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
+ .readTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
+ .followRedirects(true)
+ .followSslRedirects(true)
+ .build()
+
+ fun search(query: String, numResults: Int): ToolResult {
+ val trimmed = query.trim()
+ if (trimmed.isEmpty()) return ToolResult.error("Search query cannot be empty.")
+ val count = numResults.coerceIn(1, 10)
+
+ return try {
+ val request = Request.Builder()
+ .url("$DUCKDUCKGO_HTML?q=${java.net.URLEncoder.encode(trimmed, "UTF-8")}")
+ .header("User-Agent", "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.6422.165 Mobile Safari/537.36")
+ .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
+ .header("Accept-Language", "en-US,en;q=0.9")
+ .build()
+
+ val response = client.newCall(request).execute()
+ val body = response.body ?: return ToolResult.error("Empty response (HTTP ${response.code}).")
+
+ if (!response.isSuccessful) {
+ return ToolResult.error("Search failed (HTTP ${response.code}).")
+ }
+
+ val html = body.string()
+ val doc = Jsoup.parse(html)
+ val resultRows = doc.select(".result")
+
+ if (resultRows.isEmpty()) {
+ // DDG sometimes puts ads-only on first page; check for "no results" indicator
+ return ToolResult.ok("No search results found for '$trimmed'. Try a different query.")
+ }
+
+ val results = mutableListOf<String>()
+ var rank = 0
+
+ for (row in resultRows) {
+ if (results.size >= count) break
+
+ val titleEl = row.selectFirst(".result__title a")
+ val snippetEl = row.selectFirst(".result__snippet")
+ val urlEl = row.selectFirst(".result__url")
+
+ val title = titleEl?.text()?.trim() ?: continue
+ val href = titleEl.attr("href")
+ // DDG wraps real URLs in redirect — extract from the 'uddg' parameter or use the href directly
+ val url = extractUrl(href, row)
+ val snippet = snippetEl?.text()?.trim() ?: ""
+
+ if (url.isNotEmpty()) {
+ rank++
+ results.add("$rank. $title\n $url")
+ if (snippet.isNotEmpty()) {
+ results.add(" $snippet")
+ }
+ }
+ }
+
+ if (results.isEmpty()) {
+ return ToolResult.ok("Found search results page but could not extract any results for '$trimmed'.")
+ }
+
+ ToolResult.ok("Search results for '$trimmed' (top ${results.size}):\n\n${results.joinToString("\n")}")
+ } catch (e: java.net.UnknownHostException) {
+ ToolResult.error("Could not reach the search engine: ${e.message}")
+ } catch (e: java.net.SocketTimeoutException) {
+ ToolResult.error("Search timed out after ${TIMEOUT_SECONDS}s.")
+ } catch (e: Exception) {
+ ToolResult.error("Search failed: ${e.message}")
+ }
+ }
+
+ /** Extract the real URL from a DDG result row. DDG wraps links in redirects. */
+ private fun extractUrl(href: String, row: org.jsoup.nodes.Element): String {
+ // DDG redirect links look like: //duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2F...
+ if (href.contains("uddg=")) {
+ val uddg = href.substringAfter("uddg=").substringBefore("&")
+ return java.net.URLDecoder.decode(uddg, "UTF-8")
+ }
+ // Some results have direct hrefs
+ if (href.startsWith("http://") || href.startsWith("https://")) return href
+ if (href.startsWith("//")) return "https:$href"
+ return ""
+ }
+}