-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest_client.py
More file actions
243 lines (197 loc) · 8.31 KB
/
test_client.py
File metadata and controls
243 lines (197 loc) · 8.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
"""Tests for the MCP HTTP client."""
from __future__ import annotations
import pytest
from pytest_httpx import HTTPXMock
from talk_python_cli.client import DEFAULT_URL, MCPClient, MCPError
from tests.conftest import (
add_init_responses,
jsonrpc_error,
jsonrpc_result,
request_json,
tool_result,
)
class TestMCPClientInit:
"""Verify the MCP initialize handshake."""
def test_initialize_sends_correct_requests(self, httpx_mock: HTTPXMock, mcp_client: MCPClient) -> None:
add_init_responses(httpx_mock)
httpx_mock.add_response(
method='POST',
url=DEFAULT_URL,
json=tool_result(3, 'hello'),
)
mcp_client.call_tool('search_episodes', {'query': 'test'})
requests = httpx_mock.get_requests()
assert len(requests) == 3
# First request: initialize
init_body = request_json(requests[0])
assert init_body['method'] == 'initialize'
assert 'protocolVersion' in init_body['params']
assert init_body['params']['clientInfo']['name'] == 'talk-python-cli'
# Second request: notifications/initialized
notif_body = request_json(requests[1])
assert notif_body['method'] == 'notifications/initialized'
assert 'id' not in notif_body # notifications have no id
# Third request: tools/call
call_body = request_json(requests[2])
assert call_body['method'] == 'tools/call'
assert call_body['params']['name'] == 'search_episodes'
def test_session_id_propagated(self, httpx_mock: HTTPXMock, mcp_client: MCPClient) -> None:
add_init_responses(httpx_mock, session_id='session-abc')
httpx_mock.add_response(
method='POST',
url=DEFAULT_URL,
json=tool_result(3, 'ok'),
)
mcp_client.call_tool('get_episodes')
# The tools/call request should carry the session header
last_req = httpx_mock.get_requests()[-1]
assert last_req.headers.get('mcp-session-id') == 'session-abc'
def test_initialize_only_once(self, httpx_mock: HTTPXMock, mcp_client: MCPClient) -> None:
add_init_responses(httpx_mock)
httpx_mock.add_response(method='POST', url=DEFAULT_URL, json=tool_result(3, 'one'))
httpx_mock.add_response(method='POST', url=DEFAULT_URL, json=tool_result(4, 'two'))
mcp_client.call_tool('get_episodes')
mcp_client.call_tool('get_guests')
requests = httpx_mock.get_requests()
# init (1) + notification (1) + two tool calls (2) = 4
assert len(requests) == 4
methods = [request_json(r)['method'] for r in requests]
assert methods.count('initialize') == 1
class TestCallTool:
"""Verify tool call behaviour."""
def test_returns_text_content(self, httpx_mock: HTTPXMock, mcp_client: MCPClient) -> None:
add_init_responses(httpx_mock)
httpx_mock.add_response(
method='POST',
url=DEFAULT_URL,
json=tool_result(3, 'Episode 535: PyView'),
)
result = mcp_client.call_tool('get_episode', {'show_id': 535})
assert result == 'Episode 535: PyView'
def test_passes_arguments(self, httpx_mock: HTTPXMock, mcp_client: MCPClient) -> None:
add_init_responses(httpx_mock)
httpx_mock.add_response(
method='POST',
url=DEFAULT_URL,
json=tool_result(3, 'results'),
)
mcp_client.call_tool('search_episodes', {'query': 'FastAPI', 'limit': 5})
body = request_json(httpx_mock.get_requests()[-1])
assert body['params']['arguments'] == {'query': 'FastAPI', 'limit': 5}
def test_empty_arguments_sends_empty_dict(self, httpx_mock: HTTPXMock, mcp_client: MCPClient) -> None:
add_init_responses(httpx_mock)
httpx_mock.add_response(
method='POST',
url=DEFAULT_URL,
json=tool_result(3, 'all episodes'),
)
mcp_client.call_tool('get_episodes')
body = request_json(httpx_mock.get_requests()[-1])
assert body['params']['arguments'] == {}
def test_jsonrpc_error_raises(self, httpx_mock: HTTPXMock, mcp_client: MCPClient) -> None:
add_init_responses(httpx_mock)
httpx_mock.add_response(
method='POST',
url=DEFAULT_URL,
json=jsonrpc_error(3, -32602, 'Invalid params'),
)
with pytest.raises(MCPError) as exc_info:
mcp_client.call_tool('get_episode', {'show_id': -1})
assert exc_info.value.code == -32602
assert 'Invalid params' in str(exc_info.value)
def test_multiple_content_blocks_joined(self, httpx_mock: HTTPXMock, mcp_client: MCPClient) -> None:
add_init_responses(httpx_mock)
httpx_mock.add_response(
method='POST',
url=DEFAULT_URL,
json=jsonrpc_result(
3,
{
'content': [
{'type': 'text', 'text': 'Part 1'},
{'type': 'text', 'text': 'Part 2'},
],
},
),
)
result = mcp_client.call_tool('get_episode', {'show_id': 1})
assert result == 'Part 1\nPart 2'
class TestOutputFormat:
"""Verify the format query parameter."""
def test_text_format_no_query_param(self, httpx_mock: HTTPXMock) -> None:
client = MCPClient(base_url=DEFAULT_URL, output_format='text')
add_init_responses(httpx_mock)
httpx_mock.add_response(
method='POST',
url=DEFAULT_URL,
json=tool_result(3, 'text content'),
)
client.call_tool('get_episodes')
# All requests should go to the base URL without ?format=
for req in httpx_mock.get_requests():
assert 'format=' not in str(req.url)
client.close()
def test_json_format_adds_query_param(self, httpx_mock: HTTPXMock) -> None:
json_url = f'{DEFAULT_URL}?format=json'
client = MCPClient(base_url=DEFAULT_URL, output_format='json')
httpx_mock.add_response(
method='POST',
url=json_url,
json=jsonrpc_result(
1,
{
'protocolVersion': '2025-03-26',
'capabilities': {'tools': {}},
'serverInfo': {'name': 'test', 'version': '0.1'},
},
),
headers={'mcp-session-id': 's1'},
)
httpx_mock.add_response(method='POST', url=json_url, status_code=202, headers={'mcp-session-id': 's1'})
httpx_mock.add_response(
method='POST',
url=json_url,
json=tool_result(3, '{"data": "json"}'),
)
client.call_tool('get_episodes')
for req in httpx_mock.get_requests():
assert 'format=json' in str(req.url)
client.close()
def test_markdown_format_adds_query_param(self, httpx_mock: HTTPXMock) -> None:
md_url = f'{DEFAULT_URL}?format=markdown'
client = MCPClient(base_url=DEFAULT_URL, output_format='markdown')
httpx_mock.add_response(
method='POST',
url=md_url,
json=jsonrpc_result(
1,
{
'protocolVersion': '2025-03-26',
'capabilities': {'tools': {}},
'serverInfo': {'name': 'test', 'version': '0.1'},
},
),
headers={'mcp-session-id': 's1'},
)
httpx_mock.add_response(method='POST', url=md_url, status_code=202, headers={'mcp-session-id': 's1'})
httpx_mock.add_response(
method='POST',
url=md_url,
json=tool_result(3, '# Episode 535\n\nSome markdown content'),
)
client.call_tool('get_episodes')
for req in httpx_mock.get_requests():
assert 'format=markdown' in str(req.url)
client.close()
class TestContextManager:
"""Verify MCPClient works as a context manager."""
def test_context_manager(self, httpx_mock: HTTPXMock) -> None:
add_init_responses(httpx_mock)
httpx_mock.add_response(
method='POST',
url=DEFAULT_URL,
json=tool_result(3, 'ok'),
)
with MCPClient(base_url=DEFAULT_URL) as client:
result = client.call_tool('get_episodes')
assert result == 'ok'