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
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,33 @@ For more details about available configuration options and features, refer to th

</details>

## Web search

The built-in **Search** action uses DuckDuckGo by default. To use
[Parallel Search MCP](https://docs.parallel.ai/integrations/mcp/search-mcp), select
**Parallel Search MCP** in the action's **Search Provider** field. Parallel offers
free web search powered by Fast mode, without an account or API key. Selecting it
sends the search query to the hosted `https://search.parallel.ai/mcp` endpoint;
keep DuckDuckGo selected if you do not want to use that service.

For JSON agent configuration, set the search action's configuration to
`{"provider":"parallel"}`. For example:

```json
{
"actions": [
{"name": "search", "config": "{\"provider\":\"parallel\"}"}
]
}
```

Existing configurations without a provider keep DuckDuckGo. The tool remains
`search_internet`, with source URLs included in its result metadata, and existing
tool allow/deny lists still apply. The **Number of Results** setting applies only
to DuckDuckGo; Parallel manages its own result count. Parallel requests have a
60-second timeout and honor job cancellation. Service errors, including free-tier
rate limits, are returned to the agent without switching providers.

## 🔧 Extending LocalAGI

LocalAGI provides two powerful ways to extend its functionality with custom actions:
Expand Down
106 changes: 106 additions & 0 deletions services/actions/parallel_search.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package actions

import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"

"github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/mudler/LocalAGI/core/types"
"mvdan.cc/xurls/v2"
)

const parallelSearchEndpoint = "https://search.parallel.ai/mcp"

// parallelSearchTransport identifies LocalAGI on every MCP request, including
// initialization and session cleanup. It never reads ambient API credentials.
type parallelSearchTransport struct {
base http.RoundTripper
ctx context.Context
}

func (t parallelSearchTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// The SDK detaches its HTTP context from the caller, including while
// initializing. Bind all requests and response reads to this action's
// deadline and cancellation rather than the session's detached lifetime.
req = req.Clone(t.ctx)
if req.Method == http.MethodDelete {
// The SDK detaches the session cleanup context from the caller. Keep
// cleanup short and let job cancellation stop it too.
ctx, cancel := context.WithTimeout(t.ctx, 2*time.Second)
defer cancel()
req = req.Clone(ctx)
}
req.Header.Set("User-Agent", "LocalAGI (https://github.com/mudler/LocalAGI)")
return t.base.RoundTrip(req)
}

func parallelSearch(ctx context.Context, query string) (types.ActionResult, error) {
if strings.TrimSpace(query) == "" {
return types.ActionResult{}, fmt.Errorf("Parallel search requires a query")
}
ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()

client := mcp.NewClient(&mcp.Implementation{Name: "LocalAGI", Version: "1.0.0"}, nil)
session, err := client.Connect(ctx, &mcp.StreamableClientTransport{
Endpoint: parallelSearchEndpoint,
HTTPClient: &http.Client{
Timeout: 60 * time.Second,
Transport: parallelSearchTransport{base: http.DefaultTransport, ctx: ctx},
},
}, nil)
if err != nil {
return types.ActionResult{}, fmt.Errorf("connect to Parallel Search MCP: %w", err)
}
defer session.Close()

// Actions receive a job context, not a stable conversation identity. Leave
// the optional session_id unset rather than sharing one across agent chats
// or changing it on each tool call. The MCP connection is not a conversation.
response, err := session.CallTool(ctx, &mcp.CallToolParams{
Name: "web_search",
Arguments: map[string]any{
"objective": query,
"search_queries": []string{query},
},
})
if err != nil {
return types.ActionResult{}, fmt.Errorf("Parallel search: %w", err)
}
var text []string
for _, content := range response.Content {
if c, ok := content.(*mcp.TextContent); ok {
text = append(text, c.Text)
}
}
result := strings.Join(text, "\n")
if response.IsError {
return types.ActionResult{}, fmt.Errorf("Parallel search: %s", result)
}
if strings.TrimSpace(result) == "" {
return types.ActionResult{}, fmt.Errorf("Parallel search returned no text")
}
// Search MCP returns JSON text. Read source URLs from its result entries so
// URLs in JSON-escaped excerpts cannot leak into citation metadata.
var search struct {
Results []struct {
URL string `json:"url"`
} `json:"results"`
}
urls := []string{}
if json.Unmarshal([]byte(result), &search) == nil && search.Results != nil {
for _, entry := range search.Results {
if u, err := url.Parse(entry.URL); err == nil && u.Host != "" && (u.Scheme == "http" || u.Scheme == "https") {
urls = append(urls, entry.URL)
}
}
} else {
urls = xurls.Strict().FindAllString(result, -1)
}
return types.ActionResult{Result: result, Metadata: map[string]interface{}{MetadataUrls: urls}}, nil
}
28 changes: 25 additions & 3 deletions services/actions/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,13 @@ func NewSearch(config map[string]string) *SearchAction {
}

slog.Info("Search action with results: ", "results", intResult)
return &SearchAction{results: intResult}
return &SearchAction{results: intResult, provider: config["provider"]}
}

type SearchAction struct{ results int }
type SearchAction struct {
results int
provider string
}

func (a *SearchAction) Run(ctx context.Context, sharedState *types.AgentSharedState, params types.ActionParams) (types.ActionResult, error) {
result := struct {
Expand All @@ -45,6 +48,14 @@ func (a *SearchAction) Run(ctx context.Context, sharedState *types.AgentSharedSt

return types.ActionResult{}, err
}
switch a.provider {
case "parallel":
return parallelSearch(ctx, result.Query)
case "", "duckduckgo":
// Empty provider preserves search configurations saved before the selector.
default:
return types.ActionResult{}, fmt.Errorf("unknown search provider %q", a.provider)
}
ddg, err := duckduckgo.New(a.results, "LocalAGI")
if err != nil {
fmt.Printf("error: %v", err)
Expand Down Expand Up @@ -94,6 +105,17 @@ func (a *SearchAction) Plannable() bool {
// SearchConfigMeta returns the metadata for Search action configuration fields
func SearchConfigMeta() []config.Field {
return []config.Field{
{
Name: "provider",
Label: "Search Provider",
Type: config.FieldTypeSelect,
DefaultValue: "duckduckgo",
Options: []config.FieldOption{
{Value: "duckduckgo", Label: "DuckDuckGo"},
{Value: "parallel", Label: "Parallel Search MCP"},
},
HelpText: "Parallel sends searches to search.parallel.ai, with no account or API key required. DuckDuckGo remains the default.",
},
{
Name: "results",
Label: "Number of Results",
Expand All @@ -102,7 +124,7 @@ func SearchConfigMeta() []config.Field {
Min: 1,
Max: 100,
Step: 1,
HelpText: "Number of search results to return",
HelpText: "Number of DuckDuckGo search results to return; Parallel manages its own result count",
},
}
}
Loading