forked from sevalla-templates/python-demo-mcp-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_client.py
More file actions
198 lines (161 loc) Β· 6.35 KB
/
test_client.py
File metadata and controls
198 lines (161 loc) Β· 6.35 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
#!/usr/bin/env python3
"""
Test client for the MCP server using Server-Sent Events (SSE)
This demonstrates the correct way to interact with an MCP server.
"""
import json
import requests
import time
import sys
from typing import Dict, Any
def test_sse_connection(base_url: str = "http://localhost:8080"):
"""Test the SSE endpoint connection"""
try:
response = requests.get(f"{base_url}/sse", stream=True, timeout=5)
if response.status_code == 200:
print(f"β
SSE endpoint is accessible at {base_url}/sse")
return True
else:
print(f"β SSE endpoint returned status code: {response.status_code}")
return False
except requests.exceptions.RequestException as e:
print(f"β Failed to connect to SSE endpoint: {e}")
return False
def test_basic_endpoints(base_url: str = "http://localhost:8080"):
"""Test basic server endpoints"""
endpoints_to_test = [
"/",
"/sse",
"/messages/",
"/mcp"
]
print(f"\nπ Testing endpoints at {base_url}:")
for endpoint in endpoints_to_test:
try:
response = requests.get(f"{base_url}{endpoint}", timeout=5)
status = "β
" if response.status_code < 400 else "β οΈ"
print(f" {status} {endpoint} - Status: {response.status_code}")
# For SSE endpoint, check if it's actually streaming
if endpoint == "/sse" and response.status_code == 200:
content_type = response.headers.get('content-type', '')
if 'text/event-stream' in content_type:
print(f" π‘ Streaming content type detected: {content_type}")
except requests.exceptions.RequestException as e:
print(f" β {endpoint} - Error: {e}")
def create_mcp_message(method: str, params: Dict[str, Any] = None) -> Dict[str, Any]:
"""Create a properly formatted MCP message"""
message = {
"jsonrpc": "2.0",
"id": int(time.time()),
"method": method
}
if params:
message["params"] = params
return message
def test_mcp_protocol(base_url: str = "http://localhost:8080"):
"""Test MCP protocol messages"""
print(f"\nπ§ Testing MCP protocol at {base_url}:")
# Test messages endpoint
messages_url = f"{base_url}/messages/"
# Test 1: Initialize connection
init_message = create_mcp_message("initialize", {
"protocolVersion": "2024-11-05",
"capabilities": {
"roots": {
"listChanged": True
},
"sampling": {}
},
"clientInfo": {
"name": "test-client",
"version": "1.0.0"
}
})
try:
response = requests.post(
messages_url,
json=init_message,
headers={"Content-Type": "application/json"},
timeout=10
)
print(f" π€ Initialize request - Status: {response.status_code}")
if response.status_code == 200:
try:
result = response.json()
print(f" π₯ Initialize response: {json.dumps(result, indent=2)}")
except json.JSONDecodeError:
print(f" π₯ Initialize response (text): {response.text[:200]}...")
except requests.exceptions.RequestException as e:
print(f" β Initialize request failed: {e}")
# Test 2: List tools
tools_message = create_mcp_message("tools/list")
try:
response = requests.post(
messages_url,
json=tools_message,
headers={"Content-Type": "application/json"},
timeout=10
)
print(f" π€ Tools list request - Status: {response.status_code}")
if response.status_code == 200:
try:
result = response.json()
print(f" π₯ Available tools: {json.dumps(result, indent=2)}")
except json.JSONDecodeError:
print(f" π₯ Tools response (text): {response.text[:200]}...")
except requests.exceptions.RequestException as e:
print(f" β Tools list request failed: {e}")
def test_weather_tool_safely(base_url: str = "http://localhost:8080"):
"""Test the weather tool using proper MCP protocol"""
print(f"\nπ€οΈ Testing weather tool at {base_url}:")
messages_url = f"{base_url}/messages/"
# Call the weather tool
weather_message = create_mcp_message("tools/call", {
"name": "get_current_weather",
"arguments": {
"city": "Amsterdam"
}
})
try:
response = requests.post(
messages_url,
json=weather_message,
headers={"Content-Type": "application/json"},
timeout=15
)
print(f" π€ Weather tool call - Status: {response.status_code}")
if response.status_code == 200:
try:
result = response.json()
print(f" π₯ Weather result: {json.dumps(result, indent=2)}")
except json.JSONDecodeError:
print(f" π₯ Weather response (text): {response.text[:500]}...")
else:
print(f" π₯ Error response: {response.text[:200]}...")
except requests.exceptions.RequestException as e:
print(f" β Weather tool call failed: {e}")
def main():
"""Main test function"""
base_url = "http://localhost:8080"
print("π§ͺ MCP Server Security Test Suite")
print("=" * 50)
# Test 1: Basic connectivity
if not test_sse_connection(base_url):
print("\nβ Server is not running or not accessible.")
print("Please start the server with: python3 server.py")
return 1
# Test 2: Endpoint enumeration
test_basic_endpoints(base_url)
# Test 3: MCP protocol testing
test_mcp_protocol(base_url)
# Test 4: Tool testing
test_weather_tool_safely(base_url)
print("\nβ
Security testing completed!")
print("\nπ Security Notes:")
print(" β’ MCP server only responds to proper MCP protocol messages")
print(" β’ Tools cannot be called via simple HTTP GET requests")
print(" β’ Server uses structured JSON-RPC 2.0 protocol")
print(" β’ All tool calls are properly validated")
return 0
if __name__ == "__main__":
sys.exit(main())