Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
|
token budgeting needed to run a multi-provider agent in production. BYO
|
||||||
concrete tools, BYO provider clients, BYO memory/knowledge-graph plugins.
|
concrete tools, BYO provider clients, BYO memory/knowledge-graph plugins.
|
||||||
|
|
||||||
> **Status: v0.4.2.** Latest tagged release. The `runtime` API
|
> **Status: v0.6.0.** Latest tagged release. The `runtime` API
|
||||||
> surface may still shift in the v0.x line — pin your version.
|
> surface may still shift in the v0.x line — pin your version.
|
||||||
|
|
||||||
## Why Harness
|
## Why Harness
|
||||||
@@ -26,6 +26,26 @@ opinions about how your agents should be deployed. There is no
|
|||||||
`harness` binary. You import packages, compose a `Runtime`, and call
|
`harness` binary. You import packages, compose a `Runtime`, and call
|
||||||
`rt.Run(ctx, msg, nil)`.
|
`rt.Run(ctx, msg, nil)`.
|
||||||
|
|
||||||
|
## 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
|
## What's in v0.4.2
|
||||||
|
|
||||||
[v0.4.2](https://github.com/sausheong/harness/releases/tag/v0.4.2)
|
[v0.4.2](https://github.com/sausheong/harness/releases/tag/v0.4.2)
|
||||||
@@ -181,7 +201,7 @@ github.com/sausheong/harness/
|
|||||||
└── tools/ # Batteries-included concrete tools (each importable separately)
|
└── tools/ # Batteries-included concrete tools (each importable separately)
|
||||||
├── file/ # read_file (with vision), write_file, edit_file
|
├── file/ # read_file (with vision), write_file, edit_file
|
||||||
├── bash/ # bash (with ExecPolicy: deny | allowlist | full)
|
├── 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
|
├── browser/ # chromedp wrapper with per-session reuse
|
||||||
├── stagehand/ # natural-language browser (Stagehand: act/observe/extract),
|
├── stagehand/ # natural-language browser (Stagehand: act/observe/extract),
|
||||||
│ # local Chrome or Browserbase; inference via your LLMProvider
|
│ # local Chrome or Browserbase; inference via your LLMProvider
|
||||||
@@ -452,12 +472,12 @@ tests. See [`scripts/QUALIFICATION.md`](./scripts/QUALIFICATION.md).
|
|||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
`v0.4.2` is the latest tagged release. The v0.x line follows Go
|
`v0.6.0` is the latest tagged release. The v0.x line follows Go
|
||||||
module semver: minor bumps may break API, patch bumps are bug-fix
|
module semver: minor bumps may break API, patch bumps are bug-fix
|
||||||
only. Pin your dependency:
|
only. Pin your dependency:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go get github.com/sausheong/harness@v0.4.2
|
go get github.com/sausheong/harness@v0.6.0
|
||||||
```
|
```
|
||||||
|
|
||||||
Likely sources of v0.x churn before a v1.0.0:
|
Likely sources of v0.x churn before a v1.0.0:
|
||||||
|
|||||||
@@ -79,6 +79,12 @@ func (a *mcpToolAdapter) Execute(ctx context.Context, input json.RawMessage) (to
|
|||||||
// ToolResult: TextContent concatenated into Output (or Error if
|
// ToolResult: TextContent concatenated into Output (or Error if
|
||||||
// IsError), ImageContent collected into Images. Other content types
|
// IsError), ImageContent collected into Images. Other content types
|
||||||
// (audio, embedded resources) are described in Output as a placeholder.
|
// (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 {
|
func mcpResultToToolResult(res *sdk.CallToolResult) tool.ToolResult {
|
||||||
var text strings.Builder
|
var text strings.Builder
|
||||||
var images []llm.ImageContent
|
var images []llm.ImageContent
|
||||||
@@ -103,6 +109,13 @@ func mcpResultToToolResult(res *sdk.CallToolResult) tool.ToolResult {
|
|||||||
fmt.Fprintf(&text, "[unsupported MCP content: %T]", c)
|
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}
|
out := tool.ToolResult{Images: images}
|
||||||
if res.IsError {
|
if res.IsError {
|
||||||
out.Error = text.String()
|
out.Error = text.String()
|
||||||
|
|||||||
@@ -135,6 +135,37 @@ func TestMCPAdapter_ImageContentMapping(t *testing.T) {
|
|||||||
var _ llm.ImageContent = res.Images[0]
|
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) {
|
func TestMCPClient_ConnectDiscovers(t *testing.T) {
|
||||||
cli := startInProcessServer(t, "srv", []sdkToolFixture{
|
cli := startInProcessServer(t, "srv", []sdkToolFixture{
|
||||||
stringArgTool("a", "first", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
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