diff --git a/README.md b/README.md index f20b115..6720761 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ This is a significantly enhanced fork of [hanzili/comet-mcp](https://github.com/ | Capability | Original | Enhanced | |------------|----------|----------| | Platform Support | macOS | Windows, WSL, macOS | -| Available Tools | 6 | 8 (+comet_tabs, +comet_upload) | +| Available Tools | 6 | 9 (+comet_tabs, +comet_upload, +youcom_search) | | Completion Detection | Fixed timeout | Stability-based | | Connection Recovery | None | Auto-reconnect with backoff | | Tab Management | None | Full registry and control | @@ -305,6 +305,25 @@ File uploaded successfully: /home/user/doc.pdf --- +### youcom_search + +Optional You.com web search results for live external context. Set `YDC_API_KEY` to enable it. + +``` +Parameters: + - query (required): Search query + - count (optional): Number of results to return + - freshness (optional): day, week, month, or year +``` + +**Example:** + +``` +> youcom_search {"query":"playwright locator best practices","count":5} +``` + +--- + ## Architecture ``` @@ -346,6 +365,7 @@ File uploaded successfully: /home/user/doc.pdf |----------|-------------|---------| | `COMET_PATH` | Custom path to Comet executable | Auto-detected | | `COMET_PORT` | CDP debugging port | 9223 | +| `YDC_API_KEY` | Enables the optional `youcom_search` tool | unset | ### Custom Comet Path diff --git a/package-lock.json b/package-lock.json index 9245bda..4949af8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -463,9 +463,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -483,9 +480,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -503,9 +497,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -523,9 +514,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -543,9 +531,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -563,9 +548,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -729,21 +711,12 @@ "version": "22.19.5", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.5.tgz", "integrity": "sha512-HfF8+mYcHPcPypui3w3mvzuIErlNOh2OAG+BCeBZCEwyiD5ls2SiCwEyT47OELtf7M3nHxBdu0FsmzdKxkN52Q==", + "dev": true, "license": "MIT", "dependencies": { "undici-types": "~6.21.0" } }, - "node_modules/@types/node-fetch": { - "version": "2.6.13", - "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz", - "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==", - "license": "MIT", - "dependencies": { - "@types/node": "*", - "form-data": "^4.0.4" - } - }, "node_modules/@types/tough-cookie": { "version": "4.0.5", "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz", @@ -864,18 +837,6 @@ "url": "https://opencollective.com/vitest" } }, - "node_modules/abort-controller": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", - "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", - "license": "MIT", - "dependencies": { - "event-target-shim": "^5.0.0" - }, - "engines": { - "node": ">=6.5" - } - }, "node_modules/accepts": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", @@ -889,18 +850,6 @@ "node": ">= 0.6" } }, - "node_modules/agentkeepalive": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", - "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==", - "license": "MIT", - "dependencies": { - "humanize-ms": "^1.2.1" - }, - "engines": { - "node": ">= 8.0.0" - } - }, "node_modules/ajv": { "version": "8.17.1", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", @@ -944,12 +893,6 @@ "node": ">=12" } }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "license": "MIT" - }, "node_modules/bidi-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz", @@ -1045,18 +988,6 @@ "chrome-remote-interface": "bin/client.js" } }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "license": "MIT", - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/commander": { "version": "2.11.0", "resolved": "https://registry.npmjs.org/commander/-/commander-2.11.0.tgz", @@ -1227,15 +1158,6 @@ "dev": true, "license": "MIT" }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -1341,21 +1263,6 @@ "node": ">= 0.4" } }, - "node_modules/es-set-tostringtag": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", - "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, "node_modules/escape-html": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", @@ -1381,15 +1288,6 @@ "node": ">= 0.6" } }, - "node_modules/event-target-shim": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", - "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/eventsource": { "version": "3.0.7", "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", @@ -1540,62 +1438,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/form-data": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", - "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", - "license": "MIT", - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/form-data-encoder": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz", - "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==", - "license": "MIT" - }, - "node_modules/form-data/node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/form-data/node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/formdata-node": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz", - "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==", - "license": "MIT", - "dependencies": { - "node-domexception": "1.0.0", - "web-streams-polyfill": "4.0.0-beta.3" - }, - "engines": { - "node": ">= 12.20" - } - }, "node_modules/forwarded": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", @@ -1699,21 +1541,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/has-tostringtag": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", - "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", - "license": "MIT", - "dependencies": { - "has-symbols": "^1.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/hasown": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", @@ -1769,15 +1596,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/humanize-ms": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", - "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", - "license": "MIT", - "dependencies": { - "ms": "^2.0.0" - } - }, "node_modules/iconv-lite": { "version": "0.7.2", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", @@ -2097,9 +1915,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -2121,9 +1936,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -2145,9 +1957,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -2169,9 +1978,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -2343,46 +2149,6 @@ "node": ">= 0.6" } }, - "node_modules/node-domexception": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", - "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", - "deprecated": "Use your platform's native DOMException instead", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/jimmywarting" - }, - { - "type": "github", - "url": "https://paypal.me/jimmywarting" - } - ], - "license": "MIT", - "engines": { - "node": ">=10.5.0" - } - }, - "node_modules/node-fetch": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", - "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", - "license": "MIT", - "dependencies": { - "whatwg-url": "^5.0.0" - }, - "engines": { - "node": "4.x || >=6.0.0" - }, - "peerDependencies": { - "encoding": "^0.1.0" - }, - "peerDependenciesMeta": { - "encoding": { - "optional": true - } - } - }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -2959,12 +2725,6 @@ "node": ">=16" } }, - "node_modules/tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "license": "MIT" - }, "node_modules/tslib": { "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", @@ -3015,6 +2775,7 @@ "version": "6.21.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, "license": "MIT" }, "node_modules/unpipe": { @@ -3216,21 +2977,6 @@ "node": ">=18" } }, - "node_modules/web-streams-polyfill": { - "version": "4.0.0-beta.3", - "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", - "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==", - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, - "node_modules/webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "license": "BSD-2-Clause" - }, "node_modules/whatwg-mimetype": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", @@ -3241,16 +2987,6 @@ "node": ">=20" } }, - "node_modules/whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "license": "MIT", - "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/src/http-bridge.ts b/src/http-bridge.ts index e2b0eba..42b0b3a 100644 --- a/src/http-bridge.ts +++ b/src/http-bridge.ts @@ -25,6 +25,7 @@ import { timingSafeEqual } from "crypto"; import { URL } from "url"; import { cometClient } from "./cdp-client.js"; import { cometAI } from "./comet-ai.js"; +import { searchYoucom } from "./youcom.js"; import { validateUploadPath, validateTabId, @@ -897,6 +898,10 @@ const server = http.createServer(async (req, res) => { name: "comet_upload", description: "Upload a file to a file input on the current page", }, + { + name: "youcom_search", + description: "Optional You.com web search tool", + }, ], }); return; @@ -976,11 +981,40 @@ async function executeToolByName( return handleUpload( args as { filePath?: string; selector?: string; checkOnly?: boolean }, ); + case "youcom_search": + return handleYoucomSearch(args as { query?: string; count?: number; freshness?: string }); default: return { success: false, content: "", error: `Unknown tool: ${name}` }; } } +async function handleYoucomSearch(args: { + query?: string; + count?: number; + freshness?: string; +}): Promise { + const result = await searchYoucom({ + query: String(args.query ?? ""), + count: typeof args.count === "number" ? args.count : undefined, + freshness: typeof args.freshness === "string" ? args.freshness : undefined, + }); + + if (!result.ok) { + return { success: false, content: "", error: result.error.message }; + } + + const content = result.results.length + ? result.results + .map( + (item, index) => + `${index + 1}. ${item.title}\n${item.url}${item.description ? `\n${item.description}` : ""}`, + ) + .join("\n\n") + : "No results found."; + + return { success: true, content: `Query: ${result.query}\n\n${content}` }; +} + // ============================================================================ // Start Server // ============================================================================ diff --git a/src/index.ts b/src/index.ts index ad0136e..0dea6f8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -23,6 +23,7 @@ import { } from "@modelcontextprotocol/sdk/types.js"; import { cometClient, DEFAULT_PORT } from "./cdp-client.js"; import { cometAI } from "./comet-ai.js"; +import { searchYoucom } from "./youcom.js"; import { sessionState, startNewTask, @@ -209,6 +210,26 @@ const TOOLS: Tool[] = [ required: ["filePath"], }, }, + { + name: "youcom_search", + description: + "Run an optional You.com search request for live web results. Set YDC_API_KEY to enable it.", + inputSchema: { + type: "object", + properties: { + query: { type: "string", description: "Search query" }, + count: { + type: "number", + description: "Number of results to return (default: 10)", + }, + freshness: { + type: "string", + description: "Optional freshness filter (day, week, month, year)", + }, + }, + required: ["query"], + }, + }, ]; const server = new Server( @@ -1185,6 +1206,48 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => { } } + case "youcom_search": { + const result = await searchYoucom({ + query: String(args?.query ?? ""), + count: + typeof args?.count === "number" ? args.count : undefined, + freshness: + typeof args?.freshness === "string" + ? args.freshness + : undefined, + }); + + if (!result.ok) { + return { + content: [ + { + type: "text", + text: `Error: ${result.error.message}`, + }, + ], + isError: true, + }; + } + + const lines = result.results.length + ? result.results + .map( + (item, index) => + `${index + 1}. ${item.title}\n${item.url}${item.description ? `\n${item.description}` : ""}`, + ) + .join("\n\n") + : "No results found."; + + return { + content: [ + { + type: "text", + text: `Query: ${result.query}\n\n${lines}`, + }, + ], + }; + } + default: throw new Error(`Unknown tool: ${name}`); } diff --git a/src/youcom.ts b/src/youcom.ts new file mode 100644 index 0000000..25edbbd --- /dev/null +++ b/src/youcom.ts @@ -0,0 +1,92 @@ +export type YoucomSearchInput = { + query: string; + count?: number; + freshness?: string; + country?: string; + language?: string; + safesearch?: "off" | "moderate" | "strict"; + livecrawl?: "web" | "news" | "all"; + livecrawl_formats?: "html" | "markdown"; + crawl_timeout?: number; +}; + +export type YoucomSearchResult = { + ok: true; + query: string; + metadata?: { search_uuid?: string; latency?: number }; + results: Array<{ title: string; url: string; description?: string }>; +} | { + ok: false; + error: { code: "missing_api_key" | "upstream_error"; message: string; status?: number }; +}; + +export async function searchYoucom( + input: YoucomSearchInput, + apiKey = process.env.YDC_API_KEY, +): Promise { + if (!apiKey) { + return { + ok: false, + error: { + code: "missing_api_key", + message: "Set YDC_API_KEY to enable You.com search", + }, + }; + } + + const query = input.query.trim(); + if (!query) { + return { + ok: false, + error: { code: "upstream_error", message: "query cannot be empty" }, + }; + } + + const url = new URL("https://ydc-index.io/v1/search"); + url.searchParams.set("query", query); + if (input.count !== undefined) url.searchParams.set("count", String(input.count)); + if (input.freshness) url.searchParams.set("freshness", input.freshness); + if (input.country) url.searchParams.set("country", input.country); + if (input.language) url.searchParams.set("language", input.language); + if (input.safesearch) url.searchParams.set("safesearch", input.safesearch); + if (input.livecrawl) url.searchParams.set("livecrawl", input.livecrawl); + if (input.livecrawl_formats) url.searchParams.set("livecrawl_formats", input.livecrawl_formats); + if (input.crawl_timeout !== undefined) url.searchParams.set("crawl_timeout", String(input.crawl_timeout)); + + const response = await fetch(url, { + headers: { "X-API-Key": apiKey }, + }); + + const parsed = (await response.json().catch(async () => await response.text())) as unknown; + if (!response.ok) { + return { + ok: false, + error: { + code: "upstream_error", + status: response.status, + message: + typeof parsed === "string" + ? parsed + : parsed && typeof parsed === "object" && "message" in parsed && typeof (parsed as { message?: unknown }).message === "string" + ? (parsed as { message: string }).message + : "You.com search request failed", + }, + }; + } + + const web = parsed && typeof parsed === "object" && "results" in parsed + ? (parsed as { results?: { web?: Array<{ title?: string; url?: string; description?: string }> } }).results?.web ?? [] + : []; + const metadata = parsed && typeof parsed === "object" && "metadata" in parsed + ? (parsed as { metadata?: { search_uuid?: string; latency?: number } }).metadata + : undefined; + + return { + ok: true, + query, + metadata, + results: web + .filter((r): r is { title: string; url: string; description?: string } => !!r?.title && !!r?.url) + .map((r) => ({ title: r.title, url: r.url, description: r.description })), + }; +} diff --git a/tests/unit/youcom.test.ts b/tests/unit/youcom.test.ts new file mode 100644 index 0000000..d8c2f9d --- /dev/null +++ b/tests/unit/youcom.test.ts @@ -0,0 +1,79 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { searchYoucom } from "../../src/youcom.js"; + +afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); +}); + +describe("searchYoucom", () => { + it("returns a missing_key error when YDC_API_KEY is absent", async () => { + vi.stubEnv("YDC_API_KEY", ""); + + const result = await searchYoucom({ query: "playwright locators" }, ""); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.code).toBe("missing_api_key"); + } + }); + + it("maps web results from the You.com search API", async () => { + vi.stubEnv("YDC_API_KEY", "test-key"); + vi.stubGlobal( + "fetch", + vi.fn(async () => + new Response( + JSON.stringify({ + results: { + web: [ + { + title: "Playwright locators", + url: "https://playwright.dev/docs/locators", + description: "Best practices for finding elements.", + }, + ], + }, + metadata: { search_uuid: "uuid-1", latency: 0.12 }, + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ), + ), + ); + + const result = await searchYoucom({ query: "playwright locators" }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.query).toBe("playwright locators"); + expect(result.results).toEqual([ + { + title: "Playwright locators", + url: "https://playwright.dev/docs/locators", + description: "Best practices for finding elements.", + }, + ]); + } + }); + + it("surfaces upstream error text when the API fails", async () => { + vi.stubEnv("YDC_API_KEY", "test-key"); + vi.stubGlobal( + "fetch", + vi.fn(async () => + new Response( + JSON.stringify({ message: "quota exceeded" }), + { status: 429, headers: { "Content-Type": "application/json" } }, + ), + ), + ); + + const result = await searchYoucom({ query: "playwright locators" }); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.status).toBe(429); + expect(result.error.message).toBe("quota exceeded"); + } + }); +});