wigolo-langchain 0.2.0__tar.gz

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.
@@ -0,0 +1,65 @@
1
+
2
+ # Build & runtime
3
+ node_modules/
4
+ dist/
5
+ *.tgz
6
+
7
+ # Single-file binary build (build:binary) — artifacts never committed
8
+ packaging/binary/dist/
9
+ /pkg.build.json
10
+
11
+ # Database files
12
+ *.db
13
+ *.db-journal
14
+ *.db-wal
15
+
16
+ # wigolo data
17
+ .wigolo/
18
+
19
+ # Secrets
20
+ .env
21
+
22
+ # Test coverage
23
+ coverage/
24
+
25
+ # Benchmark output (generated)
26
+ benchmarks/extraction/output/
27
+ benchmarks/extraction/.compare-cache/
28
+
29
+ # Git worktrees
30
+ .worktrees/
31
+
32
+ # OS
33
+ .DS_Store
34
+ Thumbs.db
35
+
36
+ # IDE
37
+ .idea/
38
+ .vscode/
39
+ *.swp
40
+ *.swo
41
+
42
+
43
+ CLAUDE.md
44
+ docs/
45
+
46
+ # IDE / tool configs
47
+ .claude/
48
+ .cursor/
49
+ .github/copilot-instructions.md
50
+
51
+ # Python bytecode
52
+ __pycache__/
53
+ *.pyc
54
+
55
+ # Private strategy doc (never commit)
56
+ competitive-blueprint.md
57
+
58
+
59
+ # local demo tooling (VHS tapes + build scripts), not shipped
60
+ .demo/
61
+
62
+ # SDK dev artifacts (each SDK also ships its own .gitignore)
63
+ .venv/
64
+ .pytest_cache/
65
+ *.egg-info
@@ -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,89 @@
1
+ # wigolo-langchain
2
+
3
+ LangChain integration for [wigolo](https://github.com/KnockOutEZ/wigolo) — a local-first web search MCP server for AI coding agents.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install wigolo-langchain
9
+ ```
10
+
11
+ Requires wigolo to be available via npx:
12
+ ```bash
13
+ npm install -g wigolo
14
+ # or use npx (default, no install needed)
15
+ ```
16
+
17
+ ## Quick Start
18
+
19
+ ### As a Retriever
20
+
21
+ ```python
22
+ from wigolo_langchain import WigoloMcpClient, WigoloSearchRetriever
23
+
24
+ async def main():
25
+ async with WigoloMcpClient() as client:
26
+ retriever = WigoloSearchRetriever(
27
+ client=client,
28
+ max_results=5,
29
+ include_domains=["docs.python.org"],
30
+ )
31
+ docs = await retriever.ainvoke("Python asyncio tutorial")
32
+ for doc in docs:
33
+ print(doc.metadata["title"], doc.metadata["url"])
34
+ ```
35
+
36
+ ### As LangChain Tools (for Agents)
37
+
38
+ ```python
39
+ from wigolo_langchain import WigoloMcpClient, WigoloSearchTool, WigoloFetchTool
40
+
41
+ async def main():
42
+ async with WigoloMcpClient() as client:
43
+ search = WigoloSearchTool(client=client)
44
+ fetch = WigoloFetchTool(client=client)
45
+
46
+ # Use in a LangChain agent
47
+ tools = [search, fetch]
48
+ ```
49
+
50
+ ### Custom MCP Server Command
51
+
52
+ ```python
53
+ # Use a local development build instead of npx
54
+ client = WigoloMcpClient(command="node", args=["./dist/index.js"])
55
+ ```
56
+
57
+ ## API Reference
58
+
59
+ ### WigoloMcpClient
60
+
61
+ Async MCP client that communicates with wigolo via subprocess.
62
+
63
+ - `command` — executable to run (default: `"npx"`)
64
+ - `args` — arguments (default: `["wigolo"]`)
65
+ - `timeout` — request timeout in seconds (default: `30.0`)
66
+ - `connect()` / `disconnect()` — lifecycle management
67
+ - `call_tool(name, arguments)` — invoke any wigolo MCP tool
68
+ - Supports `async with` context manager
69
+
70
+ ### WigoloSearchRetriever
71
+
72
+ LangChain `BaseRetriever` that searches via wigolo.
73
+
74
+ - `client` — `WigoloMcpClient` instance
75
+ - `max_results` — max search results (default: 5)
76
+ - `include_domains` — domain whitelist
77
+ - `category` — "general", "code", "docs", "news", "papers"
78
+
79
+ ### WigoloSearchTool / WigoloFetchTool
80
+
81
+ LangChain `BaseTool` wrappers for wigolo search and fetch.
82
+
83
+ - Accept the same parameters as the wigolo MCP tools
84
+ - Return JSON strings (for agent consumption)
85
+ - Handle errors gracefully (return error JSON instead of raising)
86
+
87
+ ## License
88
+
89
+ [GNU AGPL-3.0-only](../../LICENSE) — same license as the parent wigolo project. Full terms in the root `LICENSE`.
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "wigolo-langchain"
7
+ version = "0.2.0"
8
+ description = "LangChain integration for wigolo — local-first web search MCP server"
9
+ readme = "README.md"
10
+ license = "AGPL-3.0-only"
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "KnockOutEZ" }]
13
+ keywords = ["langchain", "mcp", "web-search", "retriever", "agent-tools"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "License :: Other/Proprietary License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Software Development :: Libraries",
24
+ ]
25
+ dependencies = [
26
+ "langchain-core>=0.3.0",
27
+ "pydantic>=2.0.0",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ dev = [
32
+ "pytest>=8.0",
33
+ "pytest-asyncio>=0.24",
34
+ "pytest-mock>=3.14",
35
+ ]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/KnockOutEZ/wigolo"
39
+ Repository = "https://github.com/KnockOutEZ/wigolo/tree/main/packages/wigolo-langchain"
40
+ Issues = "https://github.com/KnockOutEZ/wigolo/issues"
41
+
42
+ [tool.pytest.ini_options]
43
+ asyncio_mode = "auto"
44
+ testpaths = ["tests"]
File without changes
@@ -0,0 +1,157 @@
1
+ """Shared test fixtures for wigolo-langchain."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+ from unittest.mock import AsyncMock, MagicMock
8
+
9
+ import pytest
10
+
11
+
12
+ MOCK_INITIALIZE_RESPONSE = {
13
+ "jsonrpc": "2.0",
14
+ "id": 1,
15
+ "result": {
16
+ "protocolVersion": "2025-03-26",
17
+ "serverInfo": {"name": "wigolo", "version": "0.4.0"},
18
+ "capabilities": {"tools": {}},
19
+ },
20
+ }
21
+
22
+ MOCK_INITIALIZED_NOTIFICATION = {
23
+ "jsonrpc": "2.0",
24
+ "method": "notifications/initialized",
25
+ }
26
+
27
+ MOCK_TOOLS_LIST_RESPONSE = {
28
+ "jsonrpc": "2.0",
29
+ "id": 2,
30
+ "result": {
31
+ "tools": [
32
+ {"name": "search", "description": "Search the web", "inputSchema": {"type": "object"}},
33
+ {"name": "fetch", "description": "Fetch a URL", "inputSchema": {"type": "object"}},
34
+ {"name": "crawl", "description": "Crawl a site", "inputSchema": {"type": "object"}},
35
+ {"name": "cache", "description": "Query cache", "inputSchema": {"type": "object"}},
36
+ {"name": "extract", "description": "Extract data", "inputSchema": {"type": "object"}},
37
+ ]
38
+ },
39
+ }
40
+
41
+ MOCK_SEARCH_RESPONSE = {
42
+ "jsonrpc": "2.0",
43
+ "id": 3,
44
+ "result": {
45
+ "content": [
46
+ {
47
+ "type": "text",
48
+ "text": json.dumps(
49
+ {
50
+ "results": [
51
+ {
52
+ "title": "Test Result",
53
+ "url": "https://example.com",
54
+ "snippet": "A test snippet",
55
+ "markdown_content": "# Test\nThis is test content.",
56
+ "relevance_score": 0.95,
57
+ }
58
+ ],
59
+ "query": "test query",
60
+ "engines_used": ["duckduckgo"],
61
+ "total_time_ms": 1234,
62
+ }
63
+ ),
64
+ }
65
+ ],
66
+ "isError": False,
67
+ },
68
+ }
69
+
70
+ MOCK_FETCH_RESPONSE = {
71
+ "jsonrpc": "2.0",
72
+ "id": 3,
73
+ "result": {
74
+ "content": [
75
+ {
76
+ "type": "text",
77
+ "text": json.dumps(
78
+ {
79
+ "url": "https://example.com",
80
+ "title": "Example Page",
81
+ "markdown": "# Example\nPage content here.",
82
+ "metadata": {"description": "An example page"},
83
+ "links": ["https://example.com/page2"],
84
+ "images": [],
85
+ "cached": False,
86
+ }
87
+ ),
88
+ }
89
+ ],
90
+ "isError": False,
91
+ },
92
+ }
93
+
94
+ MOCK_ERROR_RESPONSE = {
95
+ "jsonrpc": "2.0",
96
+ "id": 3,
97
+ "result": {
98
+ "content": [
99
+ {
100
+ "type": "text",
101
+ "text": json.dumps({"error": "No results found", "results": [], "query": "empty", "engines_used": [], "total_time_ms": 0}),
102
+ }
103
+ ],
104
+ "isError": True,
105
+ },
106
+ }
107
+
108
+
109
+ def make_mock_process(responses: list[dict[str, Any]]) -> MagicMock:
110
+ """Create a mock subprocess with canned JSON-RPC responses."""
111
+ proc = MagicMock()
112
+ proc.returncode = None
113
+ proc.pid = 12345
114
+
115
+ response_lines = [json.dumps(r) + "\n" for r in responses]
116
+ read_index = {"i": 0}
117
+
118
+ async def mock_readline() -> bytes:
119
+ idx = read_index["i"]
120
+ if idx < len(response_lines):
121
+ read_index["i"] += 1
122
+ return response_lines[idx].encode()
123
+ return b""
124
+
125
+ proc.stdout = MagicMock()
126
+ proc.stdout.readline = mock_readline
127
+
128
+ proc.stdin = MagicMock()
129
+ proc.stdin.write = MagicMock()
130
+ proc.stdin.drain = AsyncMock()
131
+
132
+ proc.stderr = MagicMock()
133
+ proc.stderr.readline = AsyncMock(return_value=b"")
134
+
135
+ proc.wait = AsyncMock(return_value=0)
136
+ proc.terminate = MagicMock()
137
+ proc.kill = MagicMock()
138
+
139
+ return proc
140
+
141
+
142
+ @pytest.fixture
143
+ def mock_search_process():
144
+ """Mock process that returns initialize + search response."""
145
+ return make_mock_process([MOCK_INITIALIZE_RESPONSE, MOCK_SEARCH_RESPONSE])
146
+
147
+
148
+ @pytest.fixture
149
+ def mock_fetch_process():
150
+ """Mock process that returns initialize + fetch response."""
151
+ return make_mock_process([MOCK_INITIALIZE_RESPONSE, MOCK_FETCH_RESPONSE])
152
+
153
+
154
+ @pytest.fixture
155
+ def mock_error_process():
156
+ """Mock process that returns initialize + error response."""
157
+ return make_mock_process([MOCK_INITIALIZE_RESPONSE, MOCK_ERROR_RESPONSE])
@@ -0,0 +1,200 @@
1
+ """Unit tests for the MCP subprocess client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ from unittest.mock import AsyncMock, MagicMock, patch
8
+
9
+ import pytest
10
+
11
+ from wigolo_langchain.client import WigoloMcpClient, WigoloClientError
12
+ from tests.conftest import (
13
+ MOCK_INITIALIZE_RESPONSE,
14
+ MOCK_SEARCH_RESPONSE,
15
+ MOCK_FETCH_RESPONSE,
16
+ MOCK_ERROR_RESPONSE,
17
+ make_mock_process,
18
+ )
19
+
20
+
21
+ class TestWigoloMcpClientInit:
22
+ """Test client initialization and configuration."""
23
+
24
+ def test_default_command(self):
25
+ client = WigoloMcpClient()
26
+ assert client.command == "npx"
27
+ assert client.args == ["wigolo"]
28
+
29
+ def test_custom_command(self):
30
+ client = WigoloMcpClient(command="node", args=["./dist/index.js"])
31
+ assert client.command == "node"
32
+ assert client.args == ["./dist/index.js"]
33
+
34
+ def test_custom_timeout(self):
35
+ client = WigoloMcpClient(timeout=60.0)
36
+ assert client.timeout == 60.0
37
+
38
+ def test_default_timeout_is_30(self):
39
+ client = WigoloMcpClient()
40
+ assert client.timeout == 30.0
41
+
42
+ def test_not_connected_initially(self):
43
+ client = WigoloMcpClient()
44
+ assert client.is_connected is False
45
+
46
+
47
+ class TestWigoloMcpClientConnect:
48
+ """Test client connection lifecycle."""
49
+
50
+ @pytest.mark.asyncio
51
+ async def test_connect_spawns_subprocess(self):
52
+ mock_proc = make_mock_process([MOCK_INITIALIZE_RESPONSE])
53
+ with patch("asyncio.create_subprocess_exec", new_callable=AsyncMock, return_value=mock_proc):
54
+ client = WigoloMcpClient()
55
+ await client.connect()
56
+ assert client.is_connected is True
57
+ await client.disconnect()
58
+
59
+ @pytest.mark.asyncio
60
+ async def test_connect_sends_initialize_request(self):
61
+ mock_proc = make_mock_process([MOCK_INITIALIZE_RESPONSE])
62
+ with patch("asyncio.create_subprocess_exec", new_callable=AsyncMock, return_value=mock_proc):
63
+ client = WigoloMcpClient()
64
+ await client.connect()
65
+ write_calls = mock_proc.stdin.write.call_args_list
66
+ assert len(write_calls) >= 1
67
+ first_msg = json.loads(write_calls[0][0][0])
68
+ assert first_msg["method"] == "initialize"
69
+ await client.disconnect()
70
+
71
+ @pytest.mark.asyncio
72
+ async def test_disconnect_terminates_subprocess(self):
73
+ mock_proc = make_mock_process([MOCK_INITIALIZE_RESPONSE])
74
+ with patch("asyncio.create_subprocess_exec", new_callable=AsyncMock, return_value=mock_proc):
75
+ client = WigoloMcpClient()
76
+ await client.connect()
77
+ await client.disconnect()
78
+ mock_proc.terminate.assert_called_once()
79
+
80
+ @pytest.mark.asyncio
81
+ async def test_disconnect_when_not_connected_is_noop(self):
82
+ client = WigoloMcpClient()
83
+ await client.disconnect() # Should not raise
84
+
85
+ @pytest.mark.asyncio
86
+ async def test_connect_timeout_raises_error(self):
87
+ mock_proc = make_mock_process([])
88
+ mock_proc.stdout.readline = AsyncMock(side_effect=asyncio.TimeoutError)
89
+ with patch("asyncio.create_subprocess_exec", new_callable=AsyncMock, return_value=mock_proc):
90
+ client = WigoloMcpClient(timeout=0.1)
91
+ with pytest.raises(WigoloClientError, match="timeout|connect"):
92
+ await client.connect()
93
+
94
+
95
+ class TestWigoloMcpClientCallTool:
96
+ """Test tool invocation via JSON-RPC."""
97
+
98
+ @pytest.mark.asyncio
99
+ async def test_call_search_tool(self):
100
+ mock_proc = make_mock_process([MOCK_INITIALIZE_RESPONSE, MOCK_SEARCH_RESPONSE])
101
+ with patch("asyncio.create_subprocess_exec", new_callable=AsyncMock, return_value=mock_proc):
102
+ client = WigoloMcpClient()
103
+ await client.connect()
104
+ result = await client.call_tool("search", {"query": "test"})
105
+ assert "results" in result
106
+ assert len(result["results"]) == 1
107
+ assert result["results"][0]["title"] == "Test Result"
108
+ await client.disconnect()
109
+
110
+ @pytest.mark.asyncio
111
+ async def test_call_fetch_tool(self):
112
+ mock_proc = make_mock_process([MOCK_INITIALIZE_RESPONSE, MOCK_FETCH_RESPONSE])
113
+ with patch("asyncio.create_subprocess_exec", new_callable=AsyncMock, return_value=mock_proc):
114
+ client = WigoloMcpClient()
115
+ await client.connect()
116
+ result = await client.call_tool("fetch", {"url": "https://example.com"})
117
+ assert result["title"] == "Example Page"
118
+ assert result["markdown"].startswith("# Example")
119
+ await client.disconnect()
120
+
121
+ @pytest.mark.asyncio
122
+ async def test_call_tool_when_not_connected_raises(self):
123
+ client = WigoloMcpClient()
124
+ with pytest.raises(WigoloClientError, match="not connected"):
125
+ await client.call_tool("search", {"query": "test"})
126
+
127
+ @pytest.mark.asyncio
128
+ async def test_call_tool_with_error_response(self):
129
+ mock_proc = make_mock_process([MOCK_INITIALIZE_RESPONSE, MOCK_ERROR_RESPONSE])
130
+ with patch("asyncio.create_subprocess_exec", new_callable=AsyncMock, return_value=mock_proc):
131
+ client = WigoloMcpClient()
132
+ await client.connect()
133
+ result = await client.call_tool("search", {"query": "empty"})
134
+ assert result.get("error") is not None
135
+ await client.disconnect()
136
+
137
+ @pytest.mark.asyncio
138
+ async def test_call_tool_sends_correct_jsonrpc(self):
139
+ mock_proc = make_mock_process([MOCK_INITIALIZE_RESPONSE, MOCK_SEARCH_RESPONSE])
140
+ with patch("asyncio.create_subprocess_exec", new_callable=AsyncMock, return_value=mock_proc):
141
+ client = WigoloMcpClient()
142
+ await client.connect()
143
+ await client.call_tool("search", {"query": "test", "max_results": 3})
144
+ write_calls = mock_proc.stdin.write.call_args_list
145
+ tool_calls = []
146
+ for c in write_calls:
147
+ raw = c[0][0] if isinstance(c[0][0], str) else c[0][0].decode()
148
+ if "tools/call" in raw:
149
+ tool_calls.append(json.loads(raw))
150
+ assert len(tool_calls) >= 1
151
+ call_msg = tool_calls[0]
152
+ assert call_msg["method"] == "tools/call"
153
+ assert call_msg["params"]["name"] == "search"
154
+ assert call_msg["params"]["arguments"]["query"] == "test"
155
+ await client.disconnect()
156
+
157
+ @pytest.mark.asyncio
158
+ async def test_call_tool_increments_request_id(self):
159
+ mock_proc = make_mock_process([
160
+ MOCK_INITIALIZE_RESPONSE,
161
+ MOCK_SEARCH_RESPONSE,
162
+ {**MOCK_SEARCH_RESPONSE, "id": 4},
163
+ ])
164
+ with patch("asyncio.create_subprocess_exec", new_callable=AsyncMock, return_value=mock_proc):
165
+ client = WigoloMcpClient()
166
+ await client.connect()
167
+ await client.call_tool("search", {"query": "first"})
168
+ await client.call_tool("search", {"query": "second"})
169
+ write_calls = mock_proc.stdin.write.call_args_list
170
+ ids = set()
171
+ for c in write_calls:
172
+ raw = c[0][0] if isinstance(c[0][0], str) else c[0][0].decode()
173
+ msg = json.loads(raw)
174
+ if "id" in msg:
175
+ ids.add(msg["id"])
176
+ assert len(ids) >= 3
177
+ await client.disconnect()
178
+
179
+
180
+ class TestWigoloMcpClientContextManager:
181
+ """Test async context manager usage."""
182
+
183
+ @pytest.mark.asyncio
184
+ async def test_context_manager_connects_and_disconnects(self):
185
+ mock_proc = make_mock_process([MOCK_INITIALIZE_RESPONSE])
186
+ with patch("asyncio.create_subprocess_exec", new_callable=AsyncMock, return_value=mock_proc):
187
+ client = WigoloMcpClient()
188
+ async with client:
189
+ assert client.is_connected is True
190
+ mock_proc.terminate.assert_called_once()
191
+
192
+ @pytest.mark.asyncio
193
+ async def test_context_manager_disconnects_on_exception(self):
194
+ mock_proc = make_mock_process([MOCK_INITIALIZE_RESPONSE])
195
+ with patch("asyncio.create_subprocess_exec", new_callable=AsyncMock, return_value=mock_proc):
196
+ client = WigoloMcpClient()
197
+ with pytest.raises(ValueError):
198
+ async with client:
199
+ raise ValueError("test error")
200
+ mock_proc.terminate.assert_called_once()