Skip to content

Commit b930518

Browse files
Merge pull request #4 from firecrawl/erik/opencode-v2
Support OpenCode 2 alongside OpenCode 1
2 parents 545107f + 4751c4c commit b930518

9 files changed

Lines changed: 4428 additions & 313 deletions

File tree

‎README.md‎

Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,26 @@
44

55
## Installation
66

7-
Add the plugin to your `opencode.json`:
7+
The plugin supports OpenCode 2 and OpenCode 1 (1.18.29 or later) from the same package.
8+
9+
### OpenCode 2
10+
11+
```bash
12+
opencode plugin add @firecrawl/opencode
13+
```
14+
15+
Or add it to `opencode.jsonc` yourself:
16+
17+
```jsonc
18+
{
19+
"$schema": "https://opencode.ai/config.json",
20+
"plugins": ["@firecrawl/opencode"]
21+
}
22+
```
23+
24+
### OpenCode 1
25+
26+
Add it to `opencode.json`:
827

928
```json
1029
{
@@ -13,7 +32,7 @@ Add the plugin to your `opencode.json`:
1332
}
1433
```
1534

16-
OpenCode installs it on the next start. The developer search tool works right away, with no API key and no CLI.
35+
OpenCode installs the package on the next start. The developer search tool works right away, with no API key and no CLI.
1736

1837
For the web skills (scrape, crawl, map, search, agent), install the Firecrawl CLI:
1938

@@ -23,13 +42,17 @@ npx -y firecrawl-cli@latest init -y --browser
2342

2443
## Authentication
2544

26-
Get an API key at [firecrawl.dev](https://firecrawl.dev) and export it before starting OpenCode:
45+
Get an API key at [firecrawl.dev](https://firecrawl.dev).
46+
47+
On OpenCode 2, connect Firecrawl with `/connect` in the TUI (or `opencode auth login`). This is the same Firecrawl connection OpenCode's built-in web search uses. Connecting or disconnecting takes effect without a restart. `FIRECRAWL_API_KEY` in the environment works too.
48+
49+
On OpenCode 1, export the key before starting OpenCode:
2750

2851
```bash
2952
export FIRECRAWL_API_KEY=fc-your-api-key
3053
```
3154

32-
With the key set, the plugin:
55+
With a key, the plugin:
3356

3457
- registers the `firecrawl_alexandria` tool
3558
- passes the key to shell commands, so the CLI is authenticated
@@ -57,15 +80,23 @@ Finds and runs [Alexandria](https://www.firecrawl.dev/alexandria) data providers
5780
What has the unemployment rate in California been over the last two years?
5881
```
5982

60-
The agent passes `query` to discover matching capabilities with their input contract and price (free), then `provider`, `capability`, and `options` to run one. A run spends Firecrawl credits at the listed price. Runs go through the `firecrawl_alexandria` permission, matched on `provider/capability`. To confirm each one before it spends:
83+
The agent passes `query` to discover matching capabilities with their input contract and price (free), then `provider`, `capability`, and `options` to run one. A run spends Firecrawl credits at the listed price. The tool only appears once a key is connected.
84+
85+
On OpenCode 1, runs go through the `firecrawl_alexandria` permission, matched on `provider/capability`. To confirm each one before it spends:
6186

6287
```json
6388
{
6489
"permission": { "firecrawl_alexandria": "ask" }
6590
}
6691
```
6792

68-
The tool only appears when `FIRECRAWL_API_KEY` is set.
93+
OpenCode 2 does not let plugin tools prompt for each call, so runs there are not confirmed one by one. To turn the tool off:
94+
95+
```jsonc
96+
{
97+
"permissions": [{ "action": "firecrawl_alexandria", "resource": "*", "effect": "deny" }]
98+
}
99+
```
69100

70101
## Skills
71102

@@ -75,7 +106,7 @@ The plugin bundles the Firecrawl CLI skills (search, scrape, crawl, map, interac
75106

76107
- [Firecrawl CLI documentation](https://docs.firecrawl.dev/sdks/cli)
77108
- [Firecrawl CLI on GitHub](https://github.com/firecrawl/cli)
78-
- [OpenCode plugin docs](https://opencode.ai/docs/plugins)
109+
- [OpenCode plugin docs](https://opencode.ai/v2/docs/plugins)
79110

80111
## License
81112

‎alexandria.ts‎

Lines changed: 67 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { tool } from "@opencode-ai/plugin";
1+
import { z } from "zod";
22

33
const API = "https://api.firecrawl.dev/v2";
44
const TIMEOUT_MS = 120_000;
@@ -37,75 +37,80 @@ async function post<T extends ApiError>(path: string, body: unknown, apiKey: str
3737
throw new Error(`Alexandria request failed with ${response.status} ${response.statusText}${detail}`);
3838
}
3939

40-
export const alexandria = (apiKey: string) =>
41-
tool({
42-
description: `Find and run Firecrawl Alexandria data providers: official APIs, licensed publishers, and Firecrawl indexes that return structured records instead of a web page.
40+
const input = z.object({
41+
query: z.string().optional().describe("What data you need, in plain words. Finds providers"),
42+
provider: z.string().optional().describe('Provider slug from discovery, e.g. "bls-gov"'),
43+
capability: z
44+
.string()
45+
.optional()
46+
.describe('Capability address from discovery, e.g. "economic-statistics/bls_unemployment_rate"'),
47+
options: z
48+
.record(z.string(), z.unknown())
49+
.optional()
50+
.describe("Options matching the capability's contract"),
51+
});
52+
53+
/** Asks the user before a run spends credits. Only OpenCode 1 can prompt from a plugin tool. */
54+
type Confirm = (target: string, metadata: Record<string, unknown>) => Promise<void>;
55+
56+
export const alexandria = {
57+
name: "firecrawl_alexandria",
58+
description: `Find and run Firecrawl Alexandria data providers: official APIs, licensed publishers, and Firecrawl indexes that return structured records instead of a web page.
4359
4460
Two modes, exactly one per call:
4561
- Discover: pass query, describing the data you need in plain words. Returns matching capabilities with their input contract (options), response fields, and credit price. Discovery is free.
4662
- Run: pass provider and capability exactly as discovery returned them, plus options matching that capability's contract. Running spends Firecrawl credits at the listed price.
4763
4864
Discover first and only run a capability discovery returned. Check each result item for an error before using it, and report the credits the run cost. When no provider fits, fall back to web search or scraping.`,
49-
args: {
50-
query: tool.schema.string().optional().describe("What data you need, in plain words. Finds providers"),
51-
provider: tool.schema.string().optional().describe('Provider slug from discovery, e.g. "bls-gov"'),
52-
capability: tool.schema
53-
.string()
54-
.optional()
55-
.describe('Capability address from discovery, e.g. "economic-statistics/bls_unemployment_rate"'),
56-
options: tool.schema
57-
.record(tool.schema.string(), tool.schema.unknown())
58-
.optional()
59-
.describe("Options matching the capability's contract"),
60-
},
61-
async execute(args, context) {
62-
const query = args.query?.trim();
63-
const target = args.provider && args.capability ? `${args.provider}/${args.capability}` : undefined;
64-
if (!query === !target) {
65-
throw new Error("Pass either query (to find providers) or provider and capability (to run one), not both.");
66-
}
65+
input,
66+
async run(
67+
args: z.output<typeof input>,
68+
abort: AbortSignal,
69+
apiKey: string,
70+
confirm?: Confirm,
71+
) {
72+
const query = args.query?.trim();
73+
const target = args.provider && args.capability ? `${args.provider}/${args.capability}` : undefined;
74+
if (!query === !target) {
75+
throw new Error("Pass either query (to find providers) or provider and capability (to run one), not both.");
76+
}
6777

68-
if (query) {
69-
const body = await post<SearchResponse>(
70-
"/search",
71-
// Full detail carries each capability's input contract, so the model can run it without guessing options.
72-
{ query, sources: [{ type: "alexandria" }], limit: 5, toolDetail: "full" },
73-
apiKey,
74-
context.abort,
75-
);
76-
// A recorded example response can run to hundreds of rows; the field list already describes the shape.
77-
const tools = (body.data?.tools ?? []).map(({ example, ...rest }) =>
78-
example?.request ? { ...rest, example: { request: example.request } } : rest,
79-
);
80-
return {
81-
title: query,
82-
output: tools.length
83-
? JSON.stringify(tools, null, 2)
84-
: "No Alexandria providers matched. Describe the data differently, or use web search.",
85-
metadata: { count: tools.length },
86-
};
87-
}
88-
89-
await context.ask({
90-
permission: "firecrawl_alexandria",
91-
patterns: [target!],
92-
always: [target!],
93-
metadata: { provider: args.provider, capability: args.capability, options: args.options },
94-
});
95-
const body = await post<ScrapeResponse>(
96-
"/scrape",
97-
{ alexandria: [{ provider: args.provider, capability: args.capability, options: args.options ?? {} }] },
78+
if (query) {
79+
const body = await post<SearchResponse>(
80+
"/search",
81+
// Full detail carries each capability's input contract, so the model can run it without guessing options.
82+
{ query, sources: [{ type: "alexandria" }], limit: 5, toolDetail: "full" },
9883
apiKey,
99-
context.abort,
84+
abort,
85+
);
86+
// A recorded example response can run to hundreds of rows; the field list already describes the shape.
87+
const tools = (body.data?.tools ?? []).map(({ example, ...rest }) =>
88+
example?.request ? { ...rest, example: { request: example.request } } : rest,
10089
);
101-
const results = body.data?.alexandria ?? [];
10290
return {
103-
title: target!,
104-
output: results.length ? JSON.stringify(body.data, null, 2) : "The capability returned no data.",
105-
metadata: {
106-
creditsCost: body.data?.creditsCost,
107-
failed: results.some((item) => item.error),
108-
},
91+
title: query,
92+
output: tools.length
93+
? JSON.stringify(tools, null, 2)
94+
: "No Alexandria providers matched. Describe the data differently, or use web search.",
95+
metadata: { count: tools.length },
10996
};
110-
},
111-
});
97+
}
98+
99+
await confirm?.(target!, { provider: args.provider, capability: args.capability, options: args.options });
100+
const body = await post<ScrapeResponse>(
101+
"/scrape",
102+
{ alexandria: [{ provider: args.provider, capability: args.capability, options: args.options ?? {} }] },
103+
apiKey,
104+
abort,
105+
);
106+
const results = body.data?.alexandria ?? [];
107+
return {
108+
title: target!,
109+
output: results.length ? JSON.stringify(body.data, null, 2) : "The capability returned no data.",
110+
metadata: {
111+
creditsCost: body.data?.creditsCost,
112+
failed: results.some((item) => item.error),
113+
},
114+
};
115+
},
116+
};

‎developer-search.ts‎

Lines changed: 40 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { tool } from "@opencode-ai/plugin";
1+
import { z } from "zod";
22

33
const ENDPOINT = "https://api.firecrawl.dev/v2/search/developer";
44
const TIMEOUT_MS = 30_000;
@@ -76,7 +76,39 @@ function render(response: SearchResponse, scope: Scope) {
7676
return [...blocks, ...notes].join("\n\n");
7777
}
7878

79-
export const developerSearch = tool({
79+
const input = z.object({
80+
query: z
81+
.string()
82+
.describe("The developer question, literal error string, or API contract to look up"),
83+
k: z.number().min(1).max(100).default(10).describe("Number of results to return"),
84+
types: z
85+
.array(z.enum(["doc", "issue", "pull_request", "readme"]))
86+
.optional()
87+
.describe(
88+
"Artifact kinds to search. Defaults to all four; narrowing here is the cheapest way to sharpen a query",
89+
),
90+
repos: z
91+
.array(z.string())
92+
.optional()
93+
.describe("Scope the repository half (issue, pull_request, readme) to these owner/name slugs"),
94+
sources: z
95+
.array(z.string())
96+
.optional()
97+
.describe(
98+
"Scope the documentation half (doc) to these source ids, at most 20. Unions with repos rather than intersecting",
99+
),
100+
passages: z
101+
.number()
102+
.min(1)
103+
.max(5)
104+
.default(1)
105+
.describe(
106+
"Maximum passages per result. Raise when a page is clearly right but the first passage is the wrong part of it",
107+
),
108+
});
109+
110+
export const developerSearch = {
111+
name: "firecrawl_developer_search",
80112
description: `Search a curated index of GitHub issues, merged pull requests, READMEs, and library documentation, returning the matched passages as markdown.
81113
82114
Reach for this before a web search whenever the question is how a library or API behaves, what an error message means, whether a bug was fixed, or what an API contract guarantees. It answers from the primary source: the issue where the bug was reported, the merged PR that fixed it, the doc page that defines the contract. A blog post describing a behaviour is a weaker answer than the passage defining it.
@@ -90,47 +122,16 @@ Matching the query to the question:
90122
- Scoped to one library: repos ["owner/name"]. If a scoped search comes back empty, read the "Not indexed" note before rephrasing.
91123
92124
Search broadly first, then narrow with types or repos once you have seen what the hits look like; scoping first hides the result that would have told you where to look. Quote the passages and cite the url, falling back to the url when a doc result has no title. When the index has nothing to say, comparisons, opinion, news, or an unindexed project, use the Firecrawl CLI to search or scrape the open web instead.`,
93-
args: {
94-
query: tool.schema
95-
.string()
96-
.describe("The developer question, literal error string, or API contract to look up"),
97-
k: tool.schema.number().min(1).max(100).default(10).describe("Number of results to return"),
98-
types: tool.schema
99-
.array(tool.schema.enum(["doc", "issue", "pull_request", "readme"]))
100-
.optional()
101-
.describe(
102-
"Artifact kinds to search. Defaults to all four; narrowing here is the cheapest way to sharpen a query",
103-
),
104-
repos: tool.schema
105-
.array(tool.schema.string())
106-
.optional()
107-
.describe("Scope the repository half (issue, pull_request, readme) to these owner/name slugs"),
108-
sources: tool.schema
109-
.array(tool.schema.string())
110-
.optional()
111-
.describe(
112-
"Scope the documentation half (doc) to these source ids, at most 20. Unions with repos rather than intersecting",
113-
),
114-
passages: tool.schema
115-
.number()
116-
.min(1)
117-
.max(5)
118-
.default(1)
119-
.describe(
120-
"Maximum passages per result. Raise when a page is clearly right but the first passage is the wrong part of it",
121-
),
122-
},
123-
async execute(args, context) {
125+
input,
126+
// Keyless by default; a key only raises the rate limit.
127+
async run(args: z.output<typeof input>, abort: AbortSignal, apiKey: string | undefined) {
124128
const timeout = AbortSignal.timeout(TIMEOUT_MS);
125129
const response = await fetch(ENDPOINT, {
126130
method: "POST",
127-
signal: AbortSignal.any([context.abort, timeout]),
131+
signal: AbortSignal.any([abort, timeout]),
128132
headers: {
129133
"Content-Type": "application/json",
130-
// Keyless by default; a key only raises the rate limit.
131-
...(process.env.FIRECRAWL_API_KEY && {
132-
Authorization: `Bearer ${process.env.FIRECRAWL_API_KEY}`,
133-
}),
134+
...(apiKey && { Authorization: `Bearer ${apiKey}` }),
134135
},
135136
body: JSON.stringify(args),
136137
});
@@ -151,4 +152,4 @@ Search broadly first, then narrow with types or repos once you have seen what th
151152
},
152153
};
153154
},
154-
});
155+
};

‎index.ts‎

Lines changed: 4 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,5 @@
1-
import type { Plugin } from "@opencode-ai/plugin";
2-
import { dirname, join } from "node:path";
3-
import { fileURLToPath } from "node:url";
4-
import { alexandria } from "./alexandria.ts";
5-
import { developerSearch } from "./developer-search.ts";
1+
import { server } from "./v1.ts";
2+
import { v2 } from "./v2.ts";
63

7-
const current_dir = dirname(fileURLToPath(import.meta.url));
8-
9-
export const plugin: Plugin = async () => {
10-
const apiKey = process.env.FIRECRAWL_API_KEY;
11-
12-
return {
13-
async config(input) {
14-
input.instructions ??= [];
15-
// @ts-expect-error -- opencode reads skills.paths, but the plugin SDK's Config type does not declare it yet
16-
input.skills ??= {};
17-
// @ts-expect-error -- see above
18-
input.skills.paths ??= [];
19-
20-
input.instructions.push(join(current_dir, "skills", "firecrawl", "rules", "install.md"));
21-
22-
// @ts-expect-error -- see above
23-
input.skills.paths.push(join(current_dir, "skills"));
24-
},
25-
26-
"shell.env": async (_input, output) => {
27-
if (apiKey) {
28-
output.env.FIRECRAWL_API_KEY = apiKey;
29-
}
30-
},
31-
32-
tool: {
33-
firecrawl_developer_search: developerSearch,
34-
// Alexandria runs spend credits against an account, so the tool only exists once a key is connected.
35-
...(apiKey && { firecrawl_alexandria: alexandria(apiKey) }),
36-
},
37-
};
38-
};
39-
40-
export default plugin;
4+
// One entrypoint for both hosts: OpenCode 1 calls `server()`, OpenCode 2 reads `id` and `setup()`.
5+
export default { ...v2, server };

0 commit comments

Comments
 (0)