wigolo-langchain 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- wigolo_langchain/__init__.py +17 -0
- wigolo_langchain/client.py +245 -0
- wigolo_langchain/retrievers.py +108 -0
- wigolo_langchain/tools.py +212 -0
- wigolo_langchain/types.py +109 -0
- wigolo_langchain-0.2.0.dist-info/METADATA +117 -0
- wigolo_langchain-0.2.0.dist-info/RECORD +8 -0
- wigolo_langchain-0.2.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""LangChain integration for wigolo — local-first web search MCP server."""
|
|
2
|
+
|
|
3
|
+
from wigolo_langchain.client import WigoloMcpClient
|
|
4
|
+
from wigolo_langchain.retrievers import WigoloSearchRetriever
|
|
5
|
+
from wigolo_langchain.tools import WigoloFetchTool, WigoloSearchTool
|
|
6
|
+
from wigolo_langchain.types import FetchInput, FetchOutput, SearchInput, SearchOutput
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"WigoloMcpClient",
|
|
10
|
+
"WigoloSearchRetriever",
|
|
11
|
+
"WigoloSearchTool",
|
|
12
|
+
"WigoloFetchTool",
|
|
13
|
+
"SearchInput",
|
|
14
|
+
"SearchOutput",
|
|
15
|
+
"FetchInput",
|
|
16
|
+
"FetchOutput",
|
|
17
|
+
]
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""MCP subprocess client for communicating with wigolo."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
from typing import Any, Optional
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class WigoloClientError(Exception):
|
|
14
|
+
"""Raised when the MCP client encounters an error."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class WigoloMcpClient:
|
|
18
|
+
"""Async MCP client that communicates with wigolo via subprocess stdio.
|
|
19
|
+
|
|
20
|
+
Spawns `npx wigolo` as a child process, sends JSON-RPC 2.0
|
|
21
|
+
requests over stdin, and reads responses from stdout. Stderr is consumed
|
|
22
|
+
and logged.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
command: str = "npx",
|
|
28
|
+
args: Optional[list[str]] = None,
|
|
29
|
+
timeout: float = 30.0,
|
|
30
|
+
env: Optional[dict[str, str]] = None,
|
|
31
|
+
) -> None:
|
|
32
|
+
self.command = command
|
|
33
|
+
self.args = args or ["wigolo"]
|
|
34
|
+
self.timeout = timeout
|
|
35
|
+
self.env = env
|
|
36
|
+
self._process: Optional[asyncio.subprocess.Process] = None
|
|
37
|
+
self._request_id = 0
|
|
38
|
+
self._connected = False
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def is_connected(self) -> bool:
|
|
42
|
+
return self._connected and self._process is not None
|
|
43
|
+
|
|
44
|
+
def _next_id(self) -> int:
|
|
45
|
+
self._request_id += 1
|
|
46
|
+
return self._request_id
|
|
47
|
+
|
|
48
|
+
async def connect(self) -> None:
|
|
49
|
+
"""Spawn the wigolo subprocess and send the MCP initialize handshake."""
|
|
50
|
+
if self._connected:
|
|
51
|
+
return
|
|
52
|
+
|
|
53
|
+
try:
|
|
54
|
+
self._process = await asyncio.create_subprocess_exec(
|
|
55
|
+
self.command,
|
|
56
|
+
*self.args,
|
|
57
|
+
stdin=asyncio.subprocess.PIPE,
|
|
58
|
+
stdout=asyncio.subprocess.PIPE,
|
|
59
|
+
stderr=asyncio.subprocess.PIPE,
|
|
60
|
+
env=self.env,
|
|
61
|
+
)
|
|
62
|
+
except FileNotFoundError as exc:
|
|
63
|
+
raise WigoloClientError(f"command not found: {self.command}") from exc
|
|
64
|
+
except OSError as exc:
|
|
65
|
+
raise WigoloClientError(f"failed to spawn subprocess: {exc}") from exc
|
|
66
|
+
|
|
67
|
+
self._stderr_task = asyncio.create_task(self._read_stderr())
|
|
68
|
+
|
|
69
|
+
try:
|
|
70
|
+
init_response = await self._send_request(
|
|
71
|
+
"initialize",
|
|
72
|
+
{
|
|
73
|
+
"protocolVersion": "2025-03-26",
|
|
74
|
+
"clientInfo": {"name": "wigolo-langchain", "version": "0.2.0"},
|
|
75
|
+
"capabilities": {},
|
|
76
|
+
},
|
|
77
|
+
)
|
|
78
|
+
logger.debug("MCP initialized: %s", init_response)
|
|
79
|
+
|
|
80
|
+
await self._send_notification("notifications/initialized", {})
|
|
81
|
+
|
|
82
|
+
self._connected = True
|
|
83
|
+
except asyncio.TimeoutError as exc:
|
|
84
|
+
await self._kill_process()
|
|
85
|
+
raise WigoloClientError("timeout waiting for MCP initialize response") from exc
|
|
86
|
+
except Exception as exc:
|
|
87
|
+
await self._kill_process()
|
|
88
|
+
raise WigoloClientError(f"failed to connect: {exc}") from exc
|
|
89
|
+
|
|
90
|
+
async def disconnect(self) -> None:
|
|
91
|
+
"""Terminate the subprocess and clean up."""
|
|
92
|
+
if self._process is None:
|
|
93
|
+
return
|
|
94
|
+
|
|
95
|
+
self._connected = False
|
|
96
|
+
try:
|
|
97
|
+
self._process.terminate()
|
|
98
|
+
try:
|
|
99
|
+
await asyncio.wait_for(self._process.wait(), timeout=5.0)
|
|
100
|
+
except asyncio.TimeoutError:
|
|
101
|
+
logger.warning("subprocess did not exit gracefully, killing")
|
|
102
|
+
self._process.kill()
|
|
103
|
+
await self._process.wait()
|
|
104
|
+
except ProcessLookupError:
|
|
105
|
+
pass
|
|
106
|
+
except Exception as exc:
|
|
107
|
+
logger.warning("error during disconnect: %s", exc)
|
|
108
|
+
finally:
|
|
109
|
+
self._process = None
|
|
110
|
+
if hasattr(self, "_stderr_task"):
|
|
111
|
+
self._stderr_task.cancel()
|
|
112
|
+
|
|
113
|
+
async def call_tool(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
|
|
114
|
+
"""Send a tools/call request and return the parsed result."""
|
|
115
|
+
if not self.is_connected:
|
|
116
|
+
raise WigoloClientError("not connected — call connect() first")
|
|
117
|
+
|
|
118
|
+
try:
|
|
119
|
+
response = await self._send_request(
|
|
120
|
+
"tools/call",
|
|
121
|
+
{"name": name, "arguments": arguments},
|
|
122
|
+
)
|
|
123
|
+
except asyncio.TimeoutError as exc:
|
|
124
|
+
raise WigoloClientError(f"timeout calling tool '{name}'") from exc
|
|
125
|
+
except Exception as exc:
|
|
126
|
+
raise WigoloClientError(f"error calling tool '{name}': {exc}") from exc
|
|
127
|
+
|
|
128
|
+
return self._parse_tool_response(response)
|
|
129
|
+
|
|
130
|
+
async def _send_request(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
|
|
131
|
+
"""Send a JSON-RPC request and wait for the response."""
|
|
132
|
+
assert self._process is not None
|
|
133
|
+
assert self._process.stdin is not None
|
|
134
|
+
assert self._process.stdout is not None
|
|
135
|
+
|
|
136
|
+
req_id = self._next_id()
|
|
137
|
+
request = {
|
|
138
|
+
"jsonrpc": "2.0",
|
|
139
|
+
"id": req_id,
|
|
140
|
+
"method": method,
|
|
141
|
+
"params": params,
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
msg = json.dumps(request) + "\n"
|
|
145
|
+
self._process.stdin.write(msg.encode())
|
|
146
|
+
await self._process.stdin.drain()
|
|
147
|
+
logger.debug("sent: %s", method)
|
|
148
|
+
|
|
149
|
+
response = await asyncio.wait_for(
|
|
150
|
+
self._read_response(),
|
|
151
|
+
timeout=self.timeout,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
if "error" in response and response["error"] is not None:
|
|
155
|
+
err = response["error"]
|
|
156
|
+
raise WigoloClientError(
|
|
157
|
+
f"MCP error {err.get('code', 'unknown')}: {err.get('message', 'unknown error')}"
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
return response.get("result", {})
|
|
161
|
+
|
|
162
|
+
async def _send_notification(self, method: str, params: dict[str, Any]) -> None:
|
|
163
|
+
"""Send a JSON-RPC notification (no id, no response expected)."""
|
|
164
|
+
assert self._process is not None
|
|
165
|
+
assert self._process.stdin is not None
|
|
166
|
+
|
|
167
|
+
notification = {"jsonrpc": "2.0", "method": method, "params": params}
|
|
168
|
+
msg = json.dumps(notification) + "\n"
|
|
169
|
+
self._process.stdin.write(msg.encode())
|
|
170
|
+
await self._process.stdin.drain()
|
|
171
|
+
|
|
172
|
+
async def _read_response(self) -> dict[str, Any]:
|
|
173
|
+
"""Read a single JSON-RPC response from stdout."""
|
|
174
|
+
assert self._process is not None
|
|
175
|
+
assert self._process.stdout is not None
|
|
176
|
+
|
|
177
|
+
while True:
|
|
178
|
+
line = await self._process.stdout.readline()
|
|
179
|
+
if not line:
|
|
180
|
+
raise WigoloClientError("subprocess stdout closed unexpectedly")
|
|
181
|
+
|
|
182
|
+
text = line.decode().strip()
|
|
183
|
+
if not text:
|
|
184
|
+
continue
|
|
185
|
+
|
|
186
|
+
try:
|
|
187
|
+
msg = json.loads(text)
|
|
188
|
+
except json.JSONDecodeError:
|
|
189
|
+
logger.debug("non-JSON stdout line: %s", text[:200])
|
|
190
|
+
continue
|
|
191
|
+
|
|
192
|
+
if "id" not in msg:
|
|
193
|
+
continue
|
|
194
|
+
|
|
195
|
+
return msg
|
|
196
|
+
|
|
197
|
+
async def _read_stderr(self) -> None:
|
|
198
|
+
"""Continuously read stderr and log it."""
|
|
199
|
+
assert self._process is not None
|
|
200
|
+
assert self._process.stderr is not None
|
|
201
|
+
|
|
202
|
+
try:
|
|
203
|
+
while True:
|
|
204
|
+
line = await self._process.stderr.readline()
|
|
205
|
+
if not line:
|
|
206
|
+
break
|
|
207
|
+
logger.debug("wigolo stderr: %s", line.decode().strip())
|
|
208
|
+
except asyncio.CancelledError:
|
|
209
|
+
pass
|
|
210
|
+
except Exception as exc:
|
|
211
|
+
logger.debug("stderr reader error: %s", exc)
|
|
212
|
+
|
|
213
|
+
async def _kill_process(self) -> None:
|
|
214
|
+
"""Force-kill the subprocess."""
|
|
215
|
+
if self._process is not None:
|
|
216
|
+
try:
|
|
217
|
+
self._process.kill()
|
|
218
|
+
await self._process.wait()
|
|
219
|
+
except ProcessLookupError:
|
|
220
|
+
pass
|
|
221
|
+
self._process = None
|
|
222
|
+
|
|
223
|
+
@staticmethod
|
|
224
|
+
def _parse_tool_response(result: dict[str, Any]) -> dict[str, Any]:
|
|
225
|
+
"""Parse the MCP tool response content into a dict."""
|
|
226
|
+
content = result.get("content", [])
|
|
227
|
+
if not content:
|
|
228
|
+
return {}
|
|
229
|
+
|
|
230
|
+
for block in content:
|
|
231
|
+
if block.get("type") == "text":
|
|
232
|
+
text = block.get("text", "")
|
|
233
|
+
try:
|
|
234
|
+
return json.loads(text)
|
|
235
|
+
except json.JSONDecodeError:
|
|
236
|
+
return {"raw_text": text}
|
|
237
|
+
|
|
238
|
+
return {}
|
|
239
|
+
|
|
240
|
+
async def __aenter__(self) -> WigoloMcpClient:
|
|
241
|
+
await self.connect()
|
|
242
|
+
return self
|
|
243
|
+
|
|
244
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
245
|
+
await self.disconnect()
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""WigoloSearchRetriever — LangChain BaseRetriever backed by wigolo search."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import logging
|
|
7
|
+
from typing import Any, Optional
|
|
8
|
+
|
|
9
|
+
from langchain_core.callbacks import CallbackManagerForRetrieverRun
|
|
10
|
+
from langchain_core.documents import Document
|
|
11
|
+
from langchain_core.retrievers import BaseRetriever
|
|
12
|
+
from pydantic import ConfigDict, Field
|
|
13
|
+
|
|
14
|
+
from wigolo_langchain.client import WigoloMcpClient
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class WigoloSearchRetriever(BaseRetriever):
|
|
20
|
+
"""Retriever that uses wigolo's search tool to find relevant documents.
|
|
21
|
+
|
|
22
|
+
Each search result is converted to a LangChain Document with the page's
|
|
23
|
+
markdown content as page_content and url/title/score as metadata.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
client: Any = Field(description="WigoloMcpClient instance")
|
|
27
|
+
max_results: int = Field(default=5, description="Maximum search results")
|
|
28
|
+
include_content: bool = Field(default=True, description="Fetch full content")
|
|
29
|
+
include_domains: Optional[list[str]] = Field(default=None, description="Domain whitelist")
|
|
30
|
+
exclude_domains: Optional[list[str]] = Field(default=None, description="Domain blacklist")
|
|
31
|
+
category: Optional[str] = Field(default=None, description="Search category")
|
|
32
|
+
time_range: Optional[str] = Field(default=None, description="Time range filter")
|
|
33
|
+
from_date: Optional[str] = Field(default=None, description="Results after this ISO date")
|
|
34
|
+
to_date: Optional[str] = Field(default=None, description="Results before this ISO date")
|
|
35
|
+
|
|
36
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
37
|
+
|
|
38
|
+
def _get_relevant_documents(
|
|
39
|
+
self,
|
|
40
|
+
query: str,
|
|
41
|
+
*,
|
|
42
|
+
run_manager: Optional[CallbackManagerForRetrieverRun] = None,
|
|
43
|
+
) -> list[Document]:
|
|
44
|
+
"""Synchronous retrieval — runs the async method in an event loop."""
|
|
45
|
+
try:
|
|
46
|
+
loop = asyncio.get_running_loop()
|
|
47
|
+
except RuntimeError:
|
|
48
|
+
loop = None
|
|
49
|
+
|
|
50
|
+
if loop and loop.is_running():
|
|
51
|
+
import concurrent.futures
|
|
52
|
+
with concurrent.futures.ThreadPoolExecutor() as pool:
|
|
53
|
+
future = pool.submit(asyncio.run, self._aget_relevant_documents(query))
|
|
54
|
+
return future.result()
|
|
55
|
+
else:
|
|
56
|
+
return asyncio.run(self._aget_relevant_documents(query))
|
|
57
|
+
|
|
58
|
+
async def _aget_relevant_documents(
|
|
59
|
+
self,
|
|
60
|
+
query: str,
|
|
61
|
+
*,
|
|
62
|
+
run_manager: Optional[CallbackManagerForRetrieverRun] = None,
|
|
63
|
+
) -> list[Document]:
|
|
64
|
+
"""Search wigolo and convert results to LangChain Documents."""
|
|
65
|
+
search_params: dict[str, Any] = {
|
|
66
|
+
"query": query,
|
|
67
|
+
"max_results": self.max_results,
|
|
68
|
+
"include_content": self.include_content,
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if self.include_domains:
|
|
72
|
+
search_params["include_domains"] = self.include_domains
|
|
73
|
+
if self.exclude_domains:
|
|
74
|
+
search_params["exclude_domains"] = self.exclude_domains
|
|
75
|
+
if self.category:
|
|
76
|
+
search_params["category"] = self.category
|
|
77
|
+
if self.time_range:
|
|
78
|
+
search_params["time_range"] = self.time_range
|
|
79
|
+
if self.from_date:
|
|
80
|
+
search_params["from_date"] = self.from_date
|
|
81
|
+
if self.to_date:
|
|
82
|
+
search_params["to_date"] = self.to_date
|
|
83
|
+
|
|
84
|
+
try:
|
|
85
|
+
output = await self.client.call_tool("search", search_params)
|
|
86
|
+
except Exception as exc:
|
|
87
|
+
logger.error("wigolo search failed: %s", exc)
|
|
88
|
+
return []
|
|
89
|
+
|
|
90
|
+
results = output.get("results", [])
|
|
91
|
+
if not results:
|
|
92
|
+
return []
|
|
93
|
+
|
|
94
|
+
documents: list[Document] = []
|
|
95
|
+
for result in results:
|
|
96
|
+
page_content = result.get("markdown_content") or result.get("snippet", "")
|
|
97
|
+
metadata = {
|
|
98
|
+
"title": result.get("title", ""),
|
|
99
|
+
"url": result.get("url", ""),
|
|
100
|
+
"relevance_score": result.get("relevance_score", 0.0),
|
|
101
|
+
"source": "wigolo",
|
|
102
|
+
}
|
|
103
|
+
if result.get("snippet"):
|
|
104
|
+
metadata["snippet"] = result["snippet"]
|
|
105
|
+
|
|
106
|
+
documents.append(Document(page_content=page_content, metadata=metadata))
|
|
107
|
+
|
|
108
|
+
return documents
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""LangChain tool wrappers for wigolo search and fetch."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
from typing import Any, Optional, Type
|
|
8
|
+
|
|
9
|
+
from langchain_core.callbacks import (
|
|
10
|
+
AsyncCallbackManagerForToolRun,
|
|
11
|
+
CallbackManagerForToolRun,
|
|
12
|
+
)
|
|
13
|
+
from langchain_core.tools import BaseTool
|
|
14
|
+
from pydantic import ConfigDict, Field
|
|
15
|
+
|
|
16
|
+
from wigolo_langchain.client import WigoloMcpClient
|
|
17
|
+
from wigolo_langchain.types import FetchInput, SearchInput
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class WigoloSearchTool(BaseTool):
|
|
23
|
+
"""Search the web using wigolo and return results as JSON.
|
|
24
|
+
|
|
25
|
+
Wraps wigolo's search MCP tool. Returns a JSON string with search results
|
|
26
|
+
including titles, URLs, snippets, and optionally full markdown content.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
name: str = "wigolo_search"
|
|
30
|
+
description: str = (
|
|
31
|
+
"Search the web for information on any topic. Returns titles, URLs, "
|
|
32
|
+
"relevance scores, and full extracted markdown content. Supports domain "
|
|
33
|
+
"filtering, date ranges, and content categories. Input should include "
|
|
34
|
+
"a 'query' string with keyword-based search terms."
|
|
35
|
+
)
|
|
36
|
+
args_schema: Type[SearchInput] = SearchInput
|
|
37
|
+
client: Any = Field(description="WigoloMcpClient instance")
|
|
38
|
+
|
|
39
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
40
|
+
|
|
41
|
+
def _run(
|
|
42
|
+
self,
|
|
43
|
+
query: str = "",
|
|
44
|
+
max_results: int = 5,
|
|
45
|
+
include_content: bool = True,
|
|
46
|
+
content_max_chars: int = 30000,
|
|
47
|
+
max_total_chars: int = 50000,
|
|
48
|
+
time_range: Optional[str] = None,
|
|
49
|
+
include_domains: Optional[list[str]] = None,
|
|
50
|
+
exclude_domains: Optional[list[str]] = None,
|
|
51
|
+
from_date: Optional[str] = None,
|
|
52
|
+
to_date: Optional[str] = None,
|
|
53
|
+
category: Optional[str] = None,
|
|
54
|
+
format: Optional[str] = None,
|
|
55
|
+
run_manager: Optional[CallbackManagerForToolRun] = None,
|
|
56
|
+
**kwargs: Any,
|
|
57
|
+
) -> str:
|
|
58
|
+
"""Synchronous search — wraps async version."""
|
|
59
|
+
import asyncio
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
loop = asyncio.get_running_loop()
|
|
63
|
+
except RuntimeError:
|
|
64
|
+
loop = None
|
|
65
|
+
|
|
66
|
+
params = self._build_params(
|
|
67
|
+
query=query, max_results=max_results, include_content=include_content,
|
|
68
|
+
content_max_chars=content_max_chars, max_total_chars=max_total_chars,
|
|
69
|
+
time_range=time_range, include_domains=include_domains,
|
|
70
|
+
exclude_domains=exclude_domains, from_date=from_date, to_date=to_date,
|
|
71
|
+
category=category, format=format,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
if loop and loop.is_running():
|
|
75
|
+
import concurrent.futures
|
|
76
|
+
with concurrent.futures.ThreadPoolExecutor() as pool:
|
|
77
|
+
future = pool.submit(asyncio.run, self._call_tool(params))
|
|
78
|
+
return future.result()
|
|
79
|
+
return asyncio.run(self._call_tool(params))
|
|
80
|
+
|
|
81
|
+
async def _arun(
|
|
82
|
+
self,
|
|
83
|
+
query: str = "",
|
|
84
|
+
max_results: int = 5,
|
|
85
|
+
include_content: bool = True,
|
|
86
|
+
content_max_chars: int = 30000,
|
|
87
|
+
max_total_chars: int = 50000,
|
|
88
|
+
time_range: Optional[str] = None,
|
|
89
|
+
include_domains: Optional[list[str]] = None,
|
|
90
|
+
exclude_domains: Optional[list[str]] = None,
|
|
91
|
+
from_date: Optional[str] = None,
|
|
92
|
+
to_date: Optional[str] = None,
|
|
93
|
+
category: Optional[str] = None,
|
|
94
|
+
format: Optional[str] = None,
|
|
95
|
+
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
|
|
96
|
+
**kwargs: Any,
|
|
97
|
+
) -> str:
|
|
98
|
+
"""Async search execution."""
|
|
99
|
+
params = self._build_params(
|
|
100
|
+
query=query, max_results=max_results, include_content=include_content,
|
|
101
|
+
content_max_chars=content_max_chars, max_total_chars=max_total_chars,
|
|
102
|
+
time_range=time_range, include_domains=include_domains,
|
|
103
|
+
exclude_domains=exclude_domains, from_date=from_date, to_date=to_date,
|
|
104
|
+
category=category, format=format,
|
|
105
|
+
)
|
|
106
|
+
return await self._call_tool(params)
|
|
107
|
+
|
|
108
|
+
@staticmethod
|
|
109
|
+
def _build_params(**kwargs: Any) -> dict[str, Any]:
|
|
110
|
+
"""Build the tool call parameters, stripping None values."""
|
|
111
|
+
return {k: v for k, v in kwargs.items() if v is not None}
|
|
112
|
+
|
|
113
|
+
async def _call_tool(self, params: dict[str, Any]) -> str:
|
|
114
|
+
"""Call the wigolo search tool and return JSON string."""
|
|
115
|
+
try:
|
|
116
|
+
result = await self.client.call_tool("search", params)
|
|
117
|
+
return json.dumps(result, ensure_ascii=False)
|
|
118
|
+
except Exception as exc:
|
|
119
|
+
logger.error("wigolo search tool error: %s", exc)
|
|
120
|
+
return json.dumps({"error": str(exc)})
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class WigoloFetchTool(BaseTool):
|
|
124
|
+
"""Fetch a web page using wigolo and return the result as JSON.
|
|
125
|
+
|
|
126
|
+
Wraps wigolo's fetch MCP tool. Returns a JSON string with the page title,
|
|
127
|
+
clean markdown content, links, images, and metadata.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
name: str = "wigolo_fetch"
|
|
131
|
+
description: str = (
|
|
132
|
+
"Fetch a specific web page and return its content as clean markdown. "
|
|
133
|
+
"Supports JavaScript rendering, section extraction, and authenticated "
|
|
134
|
+
"browsing. Input must include a 'url' string."
|
|
135
|
+
)
|
|
136
|
+
args_schema: Type[FetchInput] = FetchInput
|
|
137
|
+
client: Any = Field(description="WigoloMcpClient instance")
|
|
138
|
+
|
|
139
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
140
|
+
|
|
141
|
+
def _run(
|
|
142
|
+
self,
|
|
143
|
+
url: str = "",
|
|
144
|
+
render_js: str = "auto",
|
|
145
|
+
max_chars: Optional[int] = None,
|
|
146
|
+
section: Optional[str] = None,
|
|
147
|
+
section_index: Optional[int] = None,
|
|
148
|
+
use_auth: bool = False,
|
|
149
|
+
run_manager: Optional[CallbackManagerForToolRun] = None,
|
|
150
|
+
**kwargs: Any,
|
|
151
|
+
) -> str:
|
|
152
|
+
"""Synchronous fetch — wraps async version."""
|
|
153
|
+
import asyncio
|
|
154
|
+
|
|
155
|
+
params = self._build_params(
|
|
156
|
+
url=url, render_js=render_js, max_chars=max_chars,
|
|
157
|
+
section=section, section_index=section_index, use_auth=use_auth,
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
loop = asyncio.get_running_loop()
|
|
162
|
+
except RuntimeError:
|
|
163
|
+
loop = None
|
|
164
|
+
|
|
165
|
+
if loop and loop.is_running():
|
|
166
|
+
import concurrent.futures
|
|
167
|
+
with concurrent.futures.ThreadPoolExecutor() as pool:
|
|
168
|
+
future = pool.submit(asyncio.run, self._call_tool(params))
|
|
169
|
+
return future.result()
|
|
170
|
+
return asyncio.run(self._call_tool(params))
|
|
171
|
+
|
|
172
|
+
async def _arun(
|
|
173
|
+
self,
|
|
174
|
+
url: str = "",
|
|
175
|
+
render_js: str = "auto",
|
|
176
|
+
max_chars: Optional[int] = None,
|
|
177
|
+
section: Optional[str] = None,
|
|
178
|
+
section_index: Optional[int] = None,
|
|
179
|
+
use_auth: bool = False,
|
|
180
|
+
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
|
|
181
|
+
**kwargs: Any,
|
|
182
|
+
) -> str:
|
|
183
|
+
"""Async fetch execution."""
|
|
184
|
+
params = self._build_params(
|
|
185
|
+
url=url, render_js=render_js, max_chars=max_chars,
|
|
186
|
+
section=section, section_index=section_index, use_auth=use_auth,
|
|
187
|
+
)
|
|
188
|
+
return await self._call_tool(params)
|
|
189
|
+
|
|
190
|
+
@staticmethod
|
|
191
|
+
def _build_params(**kwargs: Any) -> dict[str, Any]:
|
|
192
|
+
"""Build the tool call parameters, stripping None values."""
|
|
193
|
+
params = {}
|
|
194
|
+
for k, v in kwargs.items():
|
|
195
|
+
if v is not None:
|
|
196
|
+
if k == "render_js" and v == "auto":
|
|
197
|
+
continue
|
|
198
|
+
if k == "use_auth" and v is False:
|
|
199
|
+
continue
|
|
200
|
+
params[k] = v
|
|
201
|
+
if "url" not in params and "url" in kwargs:
|
|
202
|
+
params["url"] = kwargs["url"]
|
|
203
|
+
return params
|
|
204
|
+
|
|
205
|
+
async def _call_tool(self, params: dict[str, Any]) -> str:
|
|
206
|
+
"""Call the wigolo fetch tool and return JSON string."""
|
|
207
|
+
try:
|
|
208
|
+
result = await self.client.call_tool("fetch", params)
|
|
209
|
+
return json.dumps(result, ensure_ascii=False)
|
|
210
|
+
except Exception as exc:
|
|
211
|
+
logger.error("wigolo fetch tool error: %s", exc)
|
|
212
|
+
return json.dumps({"error": str(exc)})
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Shared Pydantic models for wigolo-langchain."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, Field
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SearchInput(BaseModel):
|
|
11
|
+
"""Input schema for the wigolo search tool."""
|
|
12
|
+
|
|
13
|
+
query: str = Field(description="Search query")
|
|
14
|
+
max_results: int = Field(default=5, ge=1, le=20, description="Max results to return")
|
|
15
|
+
include_content: bool = Field(default=True, description="Fetch full content for results")
|
|
16
|
+
content_max_chars: int = Field(default=30000, ge=0, description="Max chars per result content")
|
|
17
|
+
max_total_chars: int = Field(default=50000, ge=0, description="Max total chars across all results")
|
|
18
|
+
time_range: Optional[str] = Field(
|
|
19
|
+
default=None, pattern=r"^(day|week|month|year)$", description="Time range filter"
|
|
20
|
+
)
|
|
21
|
+
include_domains: Optional[list[str]] = Field(default=None, description="Only return results from these domains")
|
|
22
|
+
exclude_domains: Optional[list[str]] = Field(default=None, description="Never return results from these domains")
|
|
23
|
+
from_date: Optional[str] = Field(default=None, description="ISO date — results after this date")
|
|
24
|
+
to_date: Optional[str] = Field(default=None, description="ISO date — results before this date")
|
|
25
|
+
category: Optional[str] = Field(
|
|
26
|
+
default=None,
|
|
27
|
+
pattern=r"^(general|news|code|docs|papers|images)$",
|
|
28
|
+
description="Search category",
|
|
29
|
+
)
|
|
30
|
+
format: Optional[str] = Field(
|
|
31
|
+
default=None, pattern=r"^(full|context)$", description="Output format"
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class FetchInput(BaseModel):
|
|
36
|
+
"""Input schema for the wigolo fetch tool."""
|
|
37
|
+
|
|
38
|
+
url: str = Field(description="URL to fetch")
|
|
39
|
+
render_js: str = Field(default="auto", pattern=r"^(auto|always|never)$", description="JS rendering mode")
|
|
40
|
+
max_chars: Optional[int] = Field(default=None, ge=0, description="Maximum characters to return")
|
|
41
|
+
section: Optional[str] = Field(default=None, description="Extract a specific section by heading text")
|
|
42
|
+
section_index: Optional[int] = Field(default=None, ge=0, description="Index of section match")
|
|
43
|
+
use_auth: bool = Field(default=False, description="Use stored auth credentials")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class SearchResultItem(BaseModel):
|
|
47
|
+
"""A single search result."""
|
|
48
|
+
|
|
49
|
+
title: str = ""
|
|
50
|
+
url: str = ""
|
|
51
|
+
snippet: str = ""
|
|
52
|
+
markdown_content: Optional[str] = None
|
|
53
|
+
fetch_failed: Optional[str] = None
|
|
54
|
+
content_truncated: Optional[bool] = None
|
|
55
|
+
relevance_score: float = 0.0
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class SearchOutput(BaseModel):
|
|
59
|
+
"""Output from the wigolo search tool."""
|
|
60
|
+
|
|
61
|
+
results: list[SearchResultItem] = Field(default_factory=list)
|
|
62
|
+
query: str = ""
|
|
63
|
+
engines_used: list[str] = Field(default_factory=list)
|
|
64
|
+
total_time_ms: int = 0
|
|
65
|
+
error: Optional[str] = None
|
|
66
|
+
warning: Optional[str] = None
|
|
67
|
+
context_text: Optional[str] = None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class FetchMetadata(BaseModel):
|
|
71
|
+
"""Metadata from a fetched page."""
|
|
72
|
+
|
|
73
|
+
description: Optional[str] = None
|
|
74
|
+
author: Optional[str] = None
|
|
75
|
+
date: Optional[str] = None
|
|
76
|
+
language: Optional[str] = None
|
|
77
|
+
section_matched: Optional[bool] = None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class FetchOutput(BaseModel):
|
|
81
|
+
"""Output from the wigolo fetch tool."""
|
|
82
|
+
|
|
83
|
+
url: str = ""
|
|
84
|
+
title: str = ""
|
|
85
|
+
markdown: str = ""
|
|
86
|
+
metadata: FetchMetadata = Field(default_factory=FetchMetadata)
|
|
87
|
+
links: list[str] = Field(default_factory=list)
|
|
88
|
+
images: list[str] = Field(default_factory=list)
|
|
89
|
+
screenshot: Optional[str] = None
|
|
90
|
+
cached: bool = False
|
|
91
|
+
error: Optional[str] = None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class McpToolCallRequest(BaseModel):
|
|
95
|
+
"""JSON-RPC request for tools/call."""
|
|
96
|
+
|
|
97
|
+
jsonrpc: str = "2.0"
|
|
98
|
+
id: int
|
|
99
|
+
method: str = "tools/call"
|
|
100
|
+
params: dict
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class McpResponse(BaseModel):
|
|
104
|
+
"""JSON-RPC response from MCP server."""
|
|
105
|
+
|
|
106
|
+
jsonrpc: str = "2.0"
|
|
107
|
+
id: int
|
|
108
|
+
result: Optional[dict] = None
|
|
109
|
+
error: Optional[dict] = None
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: wigolo-langchain
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: LangChain integration for wigolo — local-first web search MCP server
|
|
5
|
+
Project-URL: Homepage, https://github.com/KnockOutEZ/wigolo
|
|
6
|
+
Project-URL: Repository, https://github.com/KnockOutEZ/wigolo/tree/main/packages/wigolo-langchain
|
|
7
|
+
Project-URL: Issues, https://github.com/KnockOutEZ/wigolo/issues
|
|
8
|
+
Author: KnockOutEZ
|
|
9
|
+
License-Expression: AGPL-3.0-only
|
|
10
|
+
Keywords: agent-tools,langchain,mcp,retriever,web-search
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: Other/Proprietary License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Requires-Dist: langchain-core>=0.3.0
|
|
22
|
+
Requires-Dist: pydantic>=2.0.0
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest-mock>=3.14; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# wigolo-langchain
|
|
30
|
+
|
|
31
|
+
LangChain integration for [wigolo](https://github.com/KnockOutEZ/wigolo) — a local-first web search MCP server for AI coding agents.
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install wigolo-langchain
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Requires wigolo to be available via npx:
|
|
40
|
+
```bash
|
|
41
|
+
npm install -g wigolo
|
|
42
|
+
# or use npx (default, no install needed)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Quick Start
|
|
46
|
+
|
|
47
|
+
### As a Retriever
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from wigolo_langchain import WigoloMcpClient, WigoloSearchRetriever
|
|
51
|
+
|
|
52
|
+
async def main():
|
|
53
|
+
async with WigoloMcpClient() as client:
|
|
54
|
+
retriever = WigoloSearchRetriever(
|
|
55
|
+
client=client,
|
|
56
|
+
max_results=5,
|
|
57
|
+
include_domains=["docs.python.org"],
|
|
58
|
+
)
|
|
59
|
+
docs = await retriever.ainvoke("Python asyncio tutorial")
|
|
60
|
+
for doc in docs:
|
|
61
|
+
print(doc.metadata["title"], doc.metadata["url"])
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### As LangChain Tools (for Agents)
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from wigolo_langchain import WigoloMcpClient, WigoloSearchTool, WigoloFetchTool
|
|
68
|
+
|
|
69
|
+
async def main():
|
|
70
|
+
async with WigoloMcpClient() as client:
|
|
71
|
+
search = WigoloSearchTool(client=client)
|
|
72
|
+
fetch = WigoloFetchTool(client=client)
|
|
73
|
+
|
|
74
|
+
# Use in a LangChain agent
|
|
75
|
+
tools = [search, fetch]
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Custom MCP Server Command
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
# Use a local development build instead of npx
|
|
82
|
+
client = WigoloMcpClient(command="node", args=["./dist/index.js"])
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## API Reference
|
|
86
|
+
|
|
87
|
+
### WigoloMcpClient
|
|
88
|
+
|
|
89
|
+
Async MCP client that communicates with wigolo via subprocess.
|
|
90
|
+
|
|
91
|
+
- `command` — executable to run (default: `"npx"`)
|
|
92
|
+
- `args` — arguments (default: `["wigolo"]`)
|
|
93
|
+
- `timeout` — request timeout in seconds (default: `30.0`)
|
|
94
|
+
- `connect()` / `disconnect()` — lifecycle management
|
|
95
|
+
- `call_tool(name, arguments)` — invoke any wigolo MCP tool
|
|
96
|
+
- Supports `async with` context manager
|
|
97
|
+
|
|
98
|
+
### WigoloSearchRetriever
|
|
99
|
+
|
|
100
|
+
LangChain `BaseRetriever` that searches via wigolo.
|
|
101
|
+
|
|
102
|
+
- `client` — `WigoloMcpClient` instance
|
|
103
|
+
- `max_results` — max search results (default: 5)
|
|
104
|
+
- `include_domains` — domain whitelist
|
|
105
|
+
- `category` — "general", "code", "docs", "news", "papers"
|
|
106
|
+
|
|
107
|
+
### WigoloSearchTool / WigoloFetchTool
|
|
108
|
+
|
|
109
|
+
LangChain `BaseTool` wrappers for wigolo search and fetch.
|
|
110
|
+
|
|
111
|
+
- Accept the same parameters as the wigolo MCP tools
|
|
112
|
+
- Return JSON strings (for agent consumption)
|
|
113
|
+
- Handle errors gracefully (return error JSON instead of raising)
|
|
114
|
+
|
|
115
|
+
## License
|
|
116
|
+
|
|
117
|
+
[GNU AGPL-3.0-only](../../LICENSE) — same license as the parent wigolo project. Full terms in the root `LICENSE`.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
wigolo_langchain/__init__.py,sha256=6gCT8bPJRCLTefgvMqYd-i5NRevXdzqba2nxYqz9vek,538
|
|
2
|
+
wigolo_langchain/client.py,sha256=w-AEKzfsjGBk1NLGnvRwX7-mpOsbwBdBErU-bhFl-uk,8266
|
|
3
|
+
wigolo_langchain/retrievers.py,sha256=F5VZ35UkXGEbUfwA4EvW2jx3Oxd9ZQ672uqx63Boh4Y,4162
|
|
4
|
+
wigolo_langchain/tools.py,sha256=pPjY7ixV8WjHizf-ohBGXx8Ex5iznqRZ4Ogom11OAHI,7865
|
|
5
|
+
wigolo_langchain/types.py,sha256=RtvUKm8LXZgydSQHeP9Cn2h-Xua_BFJe0Mp_VKFXJAk,3827
|
|
6
|
+
wigolo_langchain-0.2.0.dist-info/METADATA,sha256=aAg3d5rbEZwxhkQxZjXXFlzwcfQUlAtILrKF0CZ-b00,3651
|
|
7
|
+
wigolo_langchain-0.2.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
8
|
+
wigolo_langchain-0.2.0.dist-info/RECORD,,
|