Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,11 @@ The plugin's integrations depend on the OpenCode version:
the bundled skill path. It does not automatically register the hosted MCP
server or a native web-search provider.

Both direct tools call `https://serpapi.com/search.json` with the runtime's
built-in `fetch` and read `SERPAPI_API_KEY` from the OpenCode process. The
bundled `serpapi-web-search` skill provides engine selection, credential
safety, and response guidance.
Both direct tools call `https://serpapi.com/search` with the runtime's built-in
`fetch` and read `SERPAPI_API_KEY` from the OpenCode process. The direct tools
and OpenCode 2's SerpApi MCP search default to Markdown; set `params.output`
to `json` when structured fields are needed. The native web-search provider
still reads JSON internally and returns only normalized search results.

## Features

Expand Down
27 changes: 24 additions & 3 deletions index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,16 @@ describe("serpapi_search", () => {
expect(result).toBe('{"ok":true}')
expect(fetchMock).toHaveBeenCalledOnce()
const url = new URL(String(fetchMock.mock.calls[0][0]))
expect(url.origin + url.pathname).toBe("https://serpapi.com/search.json")
expect(url.origin + url.pathname).toBe("https://serpapi.com/search")
expect(Object.fromEntries(url.searchParams)).toEqual({
engine: "amazon",
output: "md",
page: "2",
k: "headphones",
api_key: "trusted-key",
})
await search.execute({ q: "headphones", params: { output: "json" } }, {} as never)
expect(new URL(String(fetchMock.mock.calls[1][0])).searchParams.get("output")).toBe("json")
})

it("returns HTTP failures as tool output", async () => {
Expand Down Expand Up @@ -87,6 +90,7 @@ describe("V1 configuration", () => {

describe("OpenCode V2 adapter", () => {
it("registers the native search tool and provider, remote MCP server, and bundled skill", async () => {
const hook = vi.fn<(name: string, callback: (event: { tool: string; input: unknown }) => void) => void>()
const tools: Array<{ name: string; execute: (input: unknown, context: { signal: AbortSignal }) => Promise<{ content: string }> }> = []
const servers: Record<string, unknown> = {}
const skills: Array<{ id: string; name: string; description?: string; content: string }> = []
Expand All @@ -108,6 +112,7 @@ describe("OpenCode V2 adapter", () => {
}),
},
tool: {
hook,
transform: async (transform: (editor: { add: (definition: typeof tools[number]) => void }) => void) =>
transform({ add: (definition) => tools.push(definition) }),
},
Expand All @@ -134,11 +139,26 @@ describe("OpenCode V2 adapter", () => {
const searchResponse = JSON.stringify({
organic_results: [{ title: "Headphones", link: "https://example.com/headphones", snippet: "Top result" }],
})
const fetchMock = vi.fn(async () => new Response(searchResponse, { status: 200 }))
const fetchMock = vi.fn(async (_url: URL) => new Response(searchResponse, { status: 200 }))
vi.stubGlobal("fetch", fetchMock)

await SerpApiV2Plugin.setup(context)

const [hookName, beforeSearch] = hook.mock.calls[0]
expect(hookName).toBe("execute.before")
const mcpSearch = { tool: "serpapi_search", input: { params: { q: "headphones" }, mode: "compact" } }
beforeSearch(mcpSearch)
expect(mcpSearch.input).toEqual({ params: { q: "headphones", output: "md" }, mode: "compact" })
for (const event of [
{ tool: "serpapi_search", input: { params: { output: "json" } } },
{ tool: "serpapi_search", input: { params: '{"q":"headphones"}' } },
{ tool: "another_search", input: { params: { q: "headphones" } } },
]) {
const input = event.input
beforeSearch(event)
expect(event.input).toBe(input)
}

expect(tools.map(({ name }) => name)).toContain("serpapi_rest_search")
expect(tools.map(({ name }) => name)).not.toContain("serpapi_search")
expect(providers.map(({ id }) => id)).toContain("serpapi")
Expand Down Expand Up @@ -168,9 +188,10 @@ describe("OpenCode V2 adapter", () => {
time: {},
}])
expect(fetchMock).toHaveBeenCalledTimes(2)
expect(fetchMock.mock.calls.map(([url]) => url.searchParams.get("output"))).toEqual(["md", "json"])

fetchMock.mockRejectedValueOnce(new TypeError("Failed to fetch https://serpapi.com/search.json?api_key=v2-test-key"))
await expect(providers[0].execute({ query: "headphones" }, { signal: new AbortController().signal }))
.rejects.toThrow("SerpApi web search failed: Failed to fetch https://serpapi.com/search.json?api_key=[REDACTED]")
})
})
})
18 changes: 14 additions & 4 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ async function executeSearch(args: SearchArguments, signal: AbortSignal): Promis
const queryParam = queryParamFor(engine)
const requestParams: Record<string, string> = {
engine,
output: "md",
...(args.params ? Object.fromEntries(Object.entries(args.params).map(([key, value]) => [key, String(value)])) : {}),
}
if (args.q && !requestParams[queryParam]) requestParams[queryParam] = args.q
Expand All @@ -64,7 +65,7 @@ async function searchWithRestApi(
apiKey: string,
signal: AbortSignal,
): Promise<string> {
const url = new URL("https://serpapi.com/search.json")
const url = new URL("https://serpapi.com/search")
for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value)
url.searchParams.set("api_key", apiKey)

Expand All @@ -79,7 +80,7 @@ async function executeWebSearch(query: string, signal: AbortSignal) {
if (!apiKey) throw new Error("SERPAPI_API_KEY is not available to the OpenCode process.")

try {
const output = await searchWithRestApi({ engine: "google_light", q: query }, apiKey, signal)
const output = await searchWithRestApi({ engine: "google_light", q: query, output: "json" }, apiKey, signal)
const response: unknown = JSON.parse(output)
if (typeof response !== "object" || response === null || !("organic_results" in response)) return []

Expand Down Expand Up @@ -116,7 +117,7 @@ export const SerpApiPlugin: Plugin = async () => {
params: tool.schema
.record(tool.schema.string(), tool.schema.union([tool.schema.string(), tool.schema.number(), tool.schema.boolean()]))
.optional()
.describe("Additional engine-specific SerpApi parameters."),
.describe("Additional engine-specific SerpApi parameters. Set output to json for structured data; defaults to md."),
},
async execute(args, context) {
return executeSearch(args, context.abort)
Expand Down Expand Up @@ -167,7 +168,7 @@ export const SerpApiV2Plugin: V2Plugin = {
additionalProperties: {
anyOf: [{ type: "string" }, { type: "number" }, { type: "boolean" }],
},
description: "Additional engine-specific SerpApi parameters.",
description: "Additional engine-specific SerpApi parameters. Set output to json for structured data; defaults to md.",
},
},
additionalProperties: false,
Expand All @@ -178,6 +179,15 @@ export const SerpApiV2Plugin: V2Plugin = {
})
})

await context.tool.hook("execute.before", (event) => {
if (event.tool !== "serpapi_search" && event.tool !== "serpapi.search") return
const { input } = event
if (!input || typeof input !== "object") return
const params = "params" in input ? input.params : undefined
if (params != null && (typeof params !== "object" || Array.isArray(params) || "output" in params)) return
event.input = { ...input, params: { ...params, output: "md" } }
})

await context.websearch.transform((editor) => {
editor.add({
id: "serpapi",
Expand Down
2 changes: 1 addition & 1 deletion skills/serpapi-web-search/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ authenticate with `serpapi login` or the CLI's supported `SERPAPI_KEY` variable.
- Prefer `google_light` for ordinary web searches; use `google` for advanced SERP features.
- Use the `serpapi` engine resource and schema before guessing unusual parameters.
- Include location, country, and language when they materially affect results.
- Use field restriction, compact output, or Markdown when complete JSON is unnecessary.
- Prefer Markdown for model-facing results. Use `params.output: "json"` when exact structured fields are needed.
- Confirm before several uncached searches when the user has not clearly requested a comparison.
- Respect account credit and concurrency limits.
- Use `page` for page-based engines and `start` for Google-family offsets.
Expand Down
6 changes: 4 additions & 2 deletions skills/serpapi-web-search/references/curl.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,17 @@ The direct REST tool calls the SerpApi endpoint with the runtime's built-in
`fetch`; it does not require a shell or cURL. Its name is `serpapi_search` on
OpenCode 1 and `serpapi_rest_search` on OpenCode 2. The REST endpoint uses
`api_key` authentication in the query string, unlike the OpenCode 2 MCP
endpoint's bearer header.
endpoint's bearer header. The tool defaults to Markdown; set `params.output`
to `json` for structured data.

For manual troubleshooting outside the plugin:

```bash
curl --fail-with-body --silent --show-error \
--get "https://serpapi.com/search.json" \
--get "https://serpapi.com/search" \
--data-urlencode "engine=google_light" \
--data-urlencode "q=coffee" \
--data-urlencode "output=md" \
--data-urlencode "api_key=${SERPAPI_API_KEY}"
```

Expand Down
3 changes: 2 additions & 1 deletion skills/serpapi-web-search/references/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ search arguments include:
{"params":{"engine":"google_scholar","q":"retrieval augmented generation"}}
```

Use compact or Markdown output when complete JSON is unnecessary. Use server-side
The plugin defaults searches to Markdown. Set `params.output` to `json` for
structured data; add `mode: "compact"` to omit JSON metadata. Use server-side
field restriction for small result fields. Do not assume the tool name or schema
when OpenCode has exposed a newer MCP version; inspect the live schema first.

Expand Down