Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1098ee0362 | ||
|
|
d199a33b1a | ||
|
|
5a1983af2f | ||
|
|
e7f2641af5 | ||
|
|
e10c8d2119 | ||
|
|
40fb986b3f | ||
|
|
611198dc64 | ||
|
|
26f81ac21f |
No files matched your search
@@ -5,7 +5,7 @@ streaming agent loop, tool registry, session storage, compaction, and
|
||||
token budgeting needed to run a multi-provider agent in production. BYO
|
||||
concrete tools, BYO provider clients, BYO memory/knowledge-graph plugins.
|
||||
|
||||
> **Status: v0.4.2.** Latest tagged release. The `runtime` API
|
||||
> **Status: v0.6.2.** Latest tagged release. The `runtime` API
|
||||
> surface may still shift in the v0.x line — pin your version.
|
||||
|
||||
## Why Harness
|
||||
@@ -26,6 +26,40 @@ opinions about how your agents should be deployed. There is no
|
||||
`harness` binary. You import packages, compose a `Runtime`, and call
|
||||
`rt.Run(ctx, msg, nil)`.
|
||||
|
||||
## What's in v0.6.2
|
||||
|
||||
[v0.6.2](https://github.com/sausheong/harness/releases/tag/v0.6.2) and
|
||||
[v0.6.1](https://github.com/sausheong/harness/releases/tag/v0.6.1) are
|
||||
patch releases with no API changes:
|
||||
|
||||
- **Updated provider and MCP SDKs.** `anthropic-sdk-go` moves to v1.78.0,
|
||||
`google.golang.org/genai` to v1.72.0 and the MCP Go SDK to v1.8.0.
|
||||
Applications that also import these modules will be raised to at least
|
||||
these versions by Go's minimum version selection.
|
||||
- **MCP structured results.** When an MCP tool returns its result only as
|
||||
`structuredContent`, with no text block, the adapter passes the JSON to
|
||||
the agent instead of an empty result. Text still wins when present.
|
||||
|
||||
## What's in v0.6.0
|
||||
|
||||
[v0.6.0](https://github.com/sausheong/harness/releases/tag/v0.6.0) and
|
||||
[v0.5.0](https://github.com/sausheong/harness/releases/tag/v0.5.0) add two
|
||||
tools and raise the minimum Go version:
|
||||
|
||||
- **Go 1.26 required.** The module declares `go 1.26.0`, needed by the
|
||||
Stagehand SDK. With the default `GOTOOLCHAIN=auto`, older toolchains
|
||||
download 1.26 automatically; pinned CI images must be updated.
|
||||
- **Natural-language browser.** `tools/stagehand` drives a browser with
|
||||
instructions such as "click the Sign in button" instead of CSS selectors
|
||||
(`act`, `observe`, `extract`, plus `navigate`, `get_text`, `screenshot`).
|
||||
It runs on local Chrome or Browserbase, and Stagehand's inference goes
|
||||
through your own `LLMProvider`.
|
||||
- **Exa search.** `web.ExaSearchTool` (`exa_search`) returns ranked results
|
||||
with query-relevant highlights, with category, domain and date filters.
|
||||
- **Smaller changes.** PDF attachments are sent to Anthropic as document
|
||||
blocks, Opus 5.5 uses adaptive low-effort thinking when reasoning is off,
|
||||
and `WebFetchTool`'s output cap is raised to about 1M tokens.
|
||||
|
||||
## What's in v0.4.2
|
||||
|
||||
[v0.4.2](https://github.com/sausheong/harness/releases/tag/v0.4.2)
|
||||
@@ -181,7 +215,7 @@ github.com/sausheong/harness/
|
||||
└── tools/ # Batteries-included concrete tools (each importable separately)
|
||||
├── file/ # read_file (with vision), write_file, edit_file
|
||||
├── bash/ # bash (with ExecPolicy: deny | allowlist | full)
|
||||
├── web/ # web_fetch, web_search, ssrf guard
|
||||
├── web/ # web_fetch, web_search, exa_search, ssrf guard
|
||||
├── browser/ # chromedp wrapper with per-session reuse
|
||||
├── stagehand/ # natural-language browser (Stagehand: act/observe/extract),
|
||||
│ # local Chrome or Browserbase; inference via your LLMProvider
|
||||
@@ -452,12 +486,12 @@ tests. See [`scripts/QUALIFICATION.md`](./scripts/QUALIFICATION.md).
|
||||
|
||||
## Status
|
||||
|
||||
`v0.4.2` is the latest tagged release. The v0.x line follows Go
|
||||
`v0.6.2` is the latest tagged release. The v0.x line follows Go
|
||||
module semver: minor bumps may break API, patch bumps are bug-fix
|
||||
only. Pin your dependency:
|
||||
|
||||
```bash
|
||||
go get github.com/sausheong/harness@v0.4.2
|
||||
go get github.com/sausheong/harness@v0.6.2
|
||||
```
|
||||
|
||||
Likely sources of v0.x churn before a v1.0.0:
|
||||
|
||||
@@ -4,17 +4,17 @@ go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0
|
||||
github.com/anthropics/anthropic-sdk-go v1.35.0
|
||||
github.com/anthropics/anthropic-sdk-go v1.78.0
|
||||
github.com/browserbase/stagehand/packages/sdk-go/v4 v4.1.0
|
||||
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327
|
||||
github.com/chromedp/chromedp v0.14.2
|
||||
github.com/modelcontextprotocol/go-sdk v1.5.0
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0
|
||||
github.com/sashabaranov/go-openai v1.41.2
|
||||
github.com/stretchr/testify v1.11.1
|
||||
go.opentelemetry.io/otel v1.43.0
|
||||
go.opentelemetry.io/otel/trace v1.43.0
|
||||
golang.org/x/sys v0.42.0
|
||||
google.golang.org/genai v1.49.0
|
||||
google.golang.org/genai v1.72.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -34,7 +34,7 @@ require (
|
||||
github.com/gobwas/ws v1.4.0 // indirect
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/jsonschema-go v0.4.2 // indirect
|
||||
github.com/google/jsonschema-go v0.4.3 // indirect
|
||||
github.com/google/s2a-go v0.1.8 // indirect
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.4 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
@@ -43,6 +43,7 @@ require (
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/segmentio/asm v1.1.3 // indirect
|
||||
github.com/segmentio/encoding v0.5.4 // indirect
|
||||
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect
|
||||
github.com/tidwall/gjson v1.18.0 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
@@ -57,6 +58,7 @@ require (
|
||||
golang.org/x/oauth2 v0.35.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/text v0.35.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect
|
||||
google.golang.org/grpc v1.80.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
|
||||
@@ -10,8 +10,8 @@ github.com/JohannesKaufmann/dom v0.2.0 h1:1bragmEb19K8lHAqgFgqCpiPCFEZMTXzOIEjux
|
||||
github.com/JohannesKaufmann/dom v0.2.0/go.mod h1:57iSUl5RKric4bUkgos4zu6Xt5LMHUnw3TF1l5CbGZo=
|
||||
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0 h1:mklaPbT4f/EiDr1Q+zPrEt9lgKAkVrIBtWf33d9GpVA=
|
||||
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0/go.mod h1:D56Cl9r8M5i3UwAchE+LlLc5hPN3kJtdZNVJn06lSHU=
|
||||
github.com/anthropics/anthropic-sdk-go v1.35.0 h1:W6K8mIkD1zIU0VUPMuokWONUvdlt2C//b11Zr6v5Oz4=
|
||||
github.com/anthropics/anthropic-sdk-go v1.35.0/go.mod h1:dSIO7kSrOI7MA4fE6RRVaw8tyWP7HNQU5/H/KS4cax8=
|
||||
github.com/anthropics/anthropic-sdk-go v1.78.0 h1:8uluL7g84HtSSm347tMGtrUuCEBLmme7vOcFCMn7bnk=
|
||||
github.com/anthropics/anthropic-sdk-go v1.78.0/go.mod h1:x+lPk/cCl48uRegeP0hlYYBN1b7bEBTveInIMgLicnY=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/browserbase/stagehand/packages/sdk-go/v4 v4.1.0 h1:XELhAEkPJlyjirc1aWPhd0n+ZdFP0U+wRWamGRD05K0=
|
||||
@@ -78,8 +78,8 @@ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
|
||||
github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
|
||||
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/s2a-go v0.1.8 h1:zZDs9gcbt9ZPLV0ndSyQk6Kacx2g/X+SKYovpnz3SMM=
|
||||
github.com/google/s2a-go v0.1.8/go.mod h1:6iNWHTpQ+nfNRN5E00MSdfDwVesa8hhS32PhPO8deJA=
|
||||
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
@@ -93,8 +93,8 @@ github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8i
|
||||
github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I=
|
||||
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo=
|
||||
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs=
|
||||
github.com/modelcontextprotocol/go-sdk v1.5.0 h1:CHU0FIX9kpueNkxuYtfYQn1Z0slhFzBZuq+x6IiblIU=
|
||||
github.com/modelcontextprotocol/go-sdk v1.5.0/go.mod h1:gggDIhoemhWs3BGkGwd1umzEXCEMMvAnhTrnbXJKKKA=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
|
||||
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
|
||||
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
|
||||
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
|
||||
github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY=
|
||||
@@ -112,6 +112,8 @@ github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfv
|
||||
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
|
||||
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
|
||||
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
|
||||
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 h1:uOfcYT+3QungH6tIGSVCR/Y3KJmgJiHcojJbMTPDZAI=
|
||||
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1/go.mod h1:L1MQhA6x4dn9r007T033lsaZMv9EmBAdXyU/+EF40fo=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
@@ -187,6 +189,8 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
||||
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||
@@ -199,8 +203,8 @@ gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/genai v1.49.0 h1:Se+QJaH2GYK1aaR1o5S38mlU2GD5FnVvP76nfkV7LH0=
|
||||
google.golang.org/genai v1.49.0/go.mod h1:A3kkl0nyBjyFlNjgxIwKq70julKbIxpSxqKO5gw/gmk=
|
||||
google.golang.org/genai v1.72.0 h1:sn3V1cHkHQhMcjtUrO2y1r54jprbFjmeokBU1IKfpZk=
|
||||
google.golang.org/genai v1.72.0/go.mod h1:2j40fGpqPPIZNjaDKmjGGjYwCJi6Nm2ofmyP65GnqtY=
|
||||
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
|
||||
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
|
||||
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
# Rejects commit messages carrying AI attribution: Claude/Anthropic
|
||||
# co-author trailers or "Generated with Claude Code" lines.
|
||||
# Install once per clone: git config core.hooksPath scripts/hooks
|
||||
|
||||
if grep -v '^#' "$1" | grep -Eiq '^[[:space:]]*co-authored-by:.*(claude|anthropic)|generated (with|by) (\[)?claude'; then
|
||||
echo "commit-msg: remove the AI attribution line from the commit message:" >&2
|
||||
grep -v '^#' "$1" | grep -Ein '^[[:space:]]*co-authored-by:.*(claude|anthropic)|generated (with|by) (\[)?claude' >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -79,6 +79,12 @@ func (a *mcpToolAdapter) Execute(ctx context.Context, input json.RawMessage) (to
|
||||
// ToolResult: TextContent concatenated into Output (or Error if
|
||||
// IsError), ImageContent collected into Images. Other content types
|
||||
// (audio, embedded resources) are described in Output as a placeholder.
|
||||
//
|
||||
// StructuredContent is used only when there is no text: the MCP spec says
|
||||
// a tool returning structured content SHOULD also send it serialized as a
|
||||
// TextContent block, so when both are present the text already carries it.
|
||||
// Servers that send structured content alone would otherwise reach the
|
||||
// agent as an empty result.
|
||||
func mcpResultToToolResult(res *sdk.CallToolResult) tool.ToolResult {
|
||||
var text strings.Builder
|
||||
var images []llm.ImageContent
|
||||
@@ -103,6 +109,13 @@ func mcpResultToToolResult(res *sdk.CallToolResult) tool.ToolResult {
|
||||
fmt.Fprintf(&text, "[unsupported MCP content: %T]", c)
|
||||
}
|
||||
}
|
||||
if text.Len() == 0 && res.StructuredContent != nil {
|
||||
if b, err := json.Marshal(res.StructuredContent); err == nil {
|
||||
text.Write(b)
|
||||
} else {
|
||||
fmt.Fprintf(&text, "[unserializable MCP structured content: %v]", err)
|
||||
}
|
||||
}
|
||||
out := tool.ToolResult{Images: images}
|
||||
if res.IsError {
|
||||
out.Error = text.String()
|
||||
|
||||
@@ -135,6 +135,37 @@ func TestMCPAdapter_ImageContentMapping(t *testing.T) {
|
||||
var _ llm.ImageContent = res.Images[0]
|
||||
}
|
||||
|
||||
func TestMCPAdapter_StructuredContentFallback(t *testing.T) {
|
||||
cli := startInProcessServer(t, "srv", []sdkToolFixture{
|
||||
stringArgTool("structured_only", "hits as structured content only", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
return &sdk.CallToolResult{
|
||||
Content: []sdk.Content{},
|
||||
StructuredContent: map[string]any{"hits": []any{map[string]any{"text": "leave policy", "score": 0.9}}},
|
||||
}, nil
|
||||
}),
|
||||
stringArgTool("both", "text and structured content", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
return &sdk.CallToolResult{
|
||||
Content: []sdk.Content{&sdk.TextContent{Text: "summary text"}},
|
||||
StructuredContent: map[string]any{"hits": []any{}},
|
||||
}, nil
|
||||
}),
|
||||
})
|
||||
byName := map[string]int{}
|
||||
for i, tl := range cli.Tools() {
|
||||
byName[tl.Name()] = i
|
||||
}
|
||||
require.Len(t, byName, 2)
|
||||
|
||||
res, err := cli.Tools()[byName["mcp__srv__structured_only"]].Execute(context.Background(), json.RawMessage(`{}`))
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, res.Error)
|
||||
assert.JSONEq(t, `{"hits":[{"text":"leave policy","score":0.9}]}`, res.Output)
|
||||
|
||||
res, err = cli.Tools()[byName["mcp__srv__both"]].Execute(context.Background(), json.RawMessage(`{}`))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "summary text", res.Output, "text wins when present; structured content is not duplicated")
|
||||
}
|
||||
|
||||
func TestMCPClient_ConnectDiscovers(t *testing.T) {
|
||||
cli := startInProcessServer(t, "srv", []sdkToolFixture{
|
||||
stringArgTool("a", "first", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// exaBaseURL is the Exa API origin. Docs: https://exa.ai/docs/search/quickstart
|
||||
const exaBaseURL = "https://api.exa.ai"
|
||||
|
||||
// exaMaxResultChars bounds the highlight text kept per result so a search
|
||||
// result list stays small in the model's context.
|
||||
const exaMaxResultChars = 1500
|
||||
|
||||
// exaTypes are the search types exa_search accepts. The deep and
|
||||
// deep-reasoning modes (4-40s) are left out: agents that need that depth
|
||||
// can iterate with fetches instead of blocking on one call.
|
||||
var exaTypes = map[string]bool{"auto": true, "fast": true, "instant": true, "deep-lite": true}
|
||||
|
||||
// exaCategories are Exa's known data categories.
|
||||
var exaCategories = map[string]bool{
|
||||
"company": true, "publication": true, "news": true,
|
||||
"personal site": true, "financial report": true, "people": true,
|
||||
}
|
||||
|
||||
// ExaSearchTool searches the web with the Exa Search API, which returns
|
||||
// ranked results with query-relevant highlights extracted from each page.
|
||||
// It requires an Exa API key (https://dashboard.exa.ai/api-keys).
|
||||
type ExaSearchTool struct {
|
||||
// APIKey authenticates requests (sent as the x-api-key header).
|
||||
APIKey string
|
||||
// BaseURL overrides the API origin; empty means https://api.exa.ai.
|
||||
BaseURL string
|
||||
|
||||
// client overrides the HTTP client (tests); nil means the shared
|
||||
// SSRF-safe searchClient.
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
type exaSearchInput struct {
|
||||
Query string `json:"query"`
|
||||
NumResults int `json:"num_results,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Category string `json:"category,omitempty"`
|
||||
IncludeDomains []string `json:"include_domains,omitempty"`
|
||||
ExcludeDomains []string `json:"exclude_domains,omitempty"`
|
||||
StartPublishedDate string `json:"start_published_date,omitempty"`
|
||||
}
|
||||
|
||||
func (t *ExaSearchTool) Name() string { return "exa_search" }
|
||||
|
||||
func (t *ExaSearchTool) Description() string {
|
||||
return "Search the web with Exa, a search engine built for agents. Write the query in natural language, describing what you want to find. Returns ranked results with titles, URLs, publication dates, and the passages of each page most relevant to the query. Optionally filter by category, domains, or publication date."
|
||||
}
|
||||
|
||||
func (t *ExaSearchTool) Parameters() json.RawMessage {
|
||||
return json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {
|
||||
"type": "string",
|
||||
"description": "A natural-language description of what to find, e.g. \"recent news on Singapore's HDB resale prices\""
|
||||
},
|
||||
"num_results": {
|
||||
"type": "integer",
|
||||
"description": "Maximum number of results to return (default: 5, max: 10)"
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": ["auto", "fast", "instant", "deep-lite"],
|
||||
"description": "Search mode: auto (default, ~1s), fast (~0.5s), instant (~0.25s), or deep-lite (~4s, light multi-step research)"
|
||||
},
|
||||
"category": {
|
||||
"type": "string",
|
||||
"enum": ["company", "publication", "news", "personal site", "financial report", "people"],
|
||||
"description": "Focus on one kind of source. company and people do not support exclude_domains or start_published_date."
|
||||
},
|
||||
"include_domains": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Only return results from these domains or path prefixes, e.g. [\"straitstimes.com\", \"*.gov.sg\"]"
|
||||
},
|
||||
"exclude_domains": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
"description": "Never return results from these domains or path prefixes"
|
||||
},
|
||||
"start_published_date": {
|
||||
"type": "string",
|
||||
"description": "Only return pages published on or after this date (ISO 8601, e.g. 2026-01-01)"
|
||||
}
|
||||
},
|
||||
"required": ["query"]
|
||||
}`)
|
||||
}
|
||||
|
||||
// IsConcurrencySafe returns true — exa_search is a pure read.
|
||||
func (t *ExaSearchTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
|
||||
|
||||
func (t *ExaSearchTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
||||
var in exaSearchInput
|
||||
if err := json.Unmarshal(input, &in); err != nil {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
|
||||
}
|
||||
in.Query = strings.TrimSpace(in.Query)
|
||||
if in.Query == "" {
|
||||
return tool.ToolResult{Error: "query is required"}, nil
|
||||
}
|
||||
if t.APIKey == "" {
|
||||
return tool.ToolResult{Error: "exa_search: no Exa API key configured"}, nil
|
||||
}
|
||||
if in.Type == "" {
|
||||
in.Type = "auto"
|
||||
}
|
||||
if !exaTypes[in.Type] {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("invalid type %q (want auto, fast, instant or deep-lite)", in.Type)}, nil
|
||||
}
|
||||
if in.Category != "" && !exaCategories[in.Category] {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("invalid category %q", in.Category)}, nil
|
||||
}
|
||||
n := in.NumResults
|
||||
if n <= 0 {
|
||||
n = 5
|
||||
}
|
||||
if n > 10 {
|
||||
n = 10
|
||||
}
|
||||
|
||||
body := map[string]any{
|
||||
"query": in.Query,
|
||||
"type": in.Type,
|
||||
"numResults": n,
|
||||
"contents": map[string]any{"highlights": true},
|
||||
}
|
||||
if in.Category != "" {
|
||||
body["category"] = in.Category
|
||||
}
|
||||
if len(in.IncludeDomains) > 0 {
|
||||
body["includeDomains"] = in.IncludeDomains
|
||||
}
|
||||
if len(in.ExcludeDomains) > 0 {
|
||||
body["excludeDomains"] = in.ExcludeDomains
|
||||
}
|
||||
if in.StartPublishedDate != "" {
|
||||
body["startPublishedDate"] = in.StartPublishedDate
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, searchTimeout)
|
||||
defer cancel()
|
||||
|
||||
results, err := t.search(ctx, body)
|
||||
if err != nil {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("exa search failed: %v", err)}, nil
|
||||
}
|
||||
if len(results) == 0 {
|
||||
return tool.ToolResult{Output: "No results found for: " + in.Query}, nil
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
for i, r := range results {
|
||||
fmt.Fprintf(&sb, "%d. **%s**\n %s\n", i+1, r.Title, r.URL)
|
||||
if r.PublishedDate != "" {
|
||||
date, _, _ := strings.Cut(r.PublishedDate, "T")
|
||||
fmt.Fprintf(&sb, " Published: %s\n", date)
|
||||
}
|
||||
if text := exaHighlightText(r.Highlights); text != "" {
|
||||
fmt.Fprintf(&sb, " %s\n", text)
|
||||
}
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
return tool.ToolResult{
|
||||
Output: sb.String(),
|
||||
Metadata: map[string]any{
|
||||
"query": in.Query,
|
||||
"num_results": len(results),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
type exaResult struct {
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
PublishedDate string `json:"publishedDate"`
|
||||
Highlights []string `json:"highlights"`
|
||||
}
|
||||
|
||||
func (t *ExaSearchTool) search(ctx context.Context, body map[string]any) ([]exaResult, error) {
|
||||
payload, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
base := t.BaseURL
|
||||
if base == "" {
|
||||
base = exaBaseURL
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(base, "/")+"/search", bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("x-api-key", t.APIKey)
|
||||
client := t.client
|
||||
if client == nil {
|
||||
client = searchClient
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
return nil, fmt.Errorf("exa returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(raw)))
|
||||
}
|
||||
var parsed struct {
|
||||
Results []exaResult `json:"results"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(&parsed); err != nil {
|
||||
return nil, fmt.Errorf("exa decode: %w", err)
|
||||
}
|
||||
return parsed.Results, nil
|
||||
}
|
||||
|
||||
// exaHighlightText joins a result's highlights into one line, collapsing
|
||||
// whitespace and truncating to exaMaxResultChars.
|
||||
func exaHighlightText(highlights []string) string {
|
||||
text := strings.Join(strings.Fields(strings.Join(highlights, " … ")), " ")
|
||||
if r := []rune(text); len(r) > exaMaxResultChars {
|
||||
text = string(r[:exaMaxResultChars]) + "…"
|
||||
}
|
||||
return text
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newExaTestTool(t *testing.T, handler http.HandlerFunc) *ExaSearchTool {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
return &ExaSearchTool{APIKey: "test-key", BaseURL: srv.URL, client: srv.Client()}
|
||||
}
|
||||
|
||||
func TestExaSearch_RequestAndOutput(t *testing.T) {
|
||||
var gotKey string
|
||||
var gotBody map[string]any
|
||||
tl := newExaTestTool(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodPost, r.Method)
|
||||
require.Equal(t, "/search", r.URL.Path)
|
||||
gotKey = r.Header.Get("x-api-key")
|
||||
require.NoError(t, json.NewDecoder(r.Body).Decode(&gotBody))
|
||||
w.Write([]byte(`{"results":[
|
||||
{"title":"HDB prices","url":"https://example.com/a","publishedDate":"2026-09-01T00:00:00.000Z","highlights":["Resale prices rose\n 2%.","Second point."]},
|
||||
{"title":"No date","url":"https://example.com/b"}
|
||||
]}`))
|
||||
})
|
||||
|
||||
res, err := tl.Execute(context.Background(), json.RawMessage(`{
|
||||
"query":"HDB resale prices","num_results":50,"category":"news",
|
||||
"include_domains":["straitstimes.com"],"start_published_date":"2026-01-01"}`))
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, res.Error)
|
||||
|
||||
require.Equal(t, "test-key", gotKey)
|
||||
require.Equal(t, "HDB resale prices", gotBody["query"])
|
||||
require.Equal(t, "auto", gotBody["type"])
|
||||
require.EqualValues(t, 10, gotBody["numResults"], "num_results is capped at 10")
|
||||
require.Equal(t, "news", gotBody["category"])
|
||||
require.Equal(t, []any{"straitstimes.com"}, gotBody["includeDomains"])
|
||||
require.Equal(t, "2026-01-01", gotBody["startPublishedDate"])
|
||||
require.NotContains(t, gotBody, "excludeDomains")
|
||||
require.Equal(t, map[string]any{"highlights": true}, gotBody["contents"])
|
||||
|
||||
require.Contains(t, res.Output, "1. **HDB prices**\n https://example.com/a\n Published: 2026-09-01\n Resale prices rose 2%. … Second point.")
|
||||
require.Contains(t, res.Output, "2. **No date**\n https://example.com/b\n\n")
|
||||
require.Equal(t, 2, res.Metadata["num_results"])
|
||||
}
|
||||
|
||||
func TestExaSearch_HTTPError(t *testing.T) {
|
||||
tl := newExaTestTool(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, `{"error":"invalid key"}`, http.StatusUnauthorized)
|
||||
})
|
||||
res, err := tl.Execute(context.Background(), json.RawMessage(`{"query":"x"}`))
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, res.Error, "HTTP 401")
|
||||
require.Contains(t, res.Error, "invalid key")
|
||||
}
|
||||
|
||||
func TestExaSearch_NoResults(t *testing.T) {
|
||||
tl := newExaTestTool(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`{"results":[]}`))
|
||||
})
|
||||
res, err := tl.Execute(context.Background(), json.RawMessage(`{"query":"nothing"}`))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "No results found for: nothing", res.Output)
|
||||
}
|
||||
|
||||
func TestExaSearch_InvalidInput(t *testing.T) {
|
||||
called := false
|
||||
tl := newExaTestTool(t, func(w http.ResponseWriter, r *http.Request) { called = true })
|
||||
for _, in := range []string{
|
||||
`{"query":" "}`,
|
||||
`{"query":"x","type":"deep-reasoning"}`,
|
||||
`{"query":"x","category":"recipes"}`,
|
||||
`not json`,
|
||||
} {
|
||||
res, err := tl.Execute(context.Background(), json.RawMessage(in))
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res.Error, in)
|
||||
}
|
||||
require.False(t, called, "invalid input must not reach the API")
|
||||
|
||||
noKey := &ExaSearchTool{}
|
||||
res, _ := noKey.Execute(context.Background(), json.RawMessage(`{"query":"x"}`))
|
||||
require.Contains(t, res.Error, "no Exa API key")
|
||||
}
|
||||
|
||||
func TestExaSearch_DefaultClientIsSafe(t *testing.T) {
|
||||
// The zero-value tool must use the SSRF-safe client, which refuses
|
||||
// loopback addresses.
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(`{"results":[]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
tl := &ExaSearchTool{APIKey: "k", BaseURL: srv.URL}
|
||||
res, err := tl.Execute(context.Background(), json.RawMessage(`{"query":"x"}`))
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res.Error)
|
||||
}
|
||||
|
||||
func TestExaHighlightText_Truncates(t *testing.T) {
|
||||
text := exaHighlightText([]string{strings.Repeat("a", exaMaxResultChars+100)})
|
||||
require.Equal(t, exaMaxResultChars+1, len([]rune(text)))
|
||||
require.True(t, strings.HasSuffix(text, "…"))
|
||||
}
|
||||
Reference in new issue
Block a user