-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp-client-example.py
More file actions
197 lines (159 loc) · 6.1 KB
/
Copy pathmcp-client-example.py
File metadata and controls
197 lines (159 loc) · 6.1 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
#!/usr/bin/env python3
"""
Example MCP client for InsightBot
Demonstrates how to interact with the MCP server
"""
import asyncio
import json
import subprocess
import sys
from typing import Dict, Any
class InsightBotMCPClient:
"""Simple MCP client for InsightBot"""
def __init__(self, server_command: list = None):
self.server_command = server_command or [
"python", "-m", "mcp_server.main"
]
self.process = None
async def start_server(self):
"""Start the MCP server process"""
self.process = await asyncio.create_subprocess_exec(
*self.server_command,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
# Send initialization
init_request = {
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {
"roots": {
"listChanged": True
},
"sampling": {}
},
"clientInfo": {
"name": "InsightBot MCP Client",
"version": "1.0.0"
}
}
}
await self._send_request(init_request)
response = await self._read_response()
if response.get("error"):
raise Exception(f"Initialization failed: {response['error']}")
print("✅ MCP Server initialized successfully")
return response
async def list_tools(self) -> Dict[str, Any]:
"""List available tools"""
request = {
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list",
"params": {}
}
await self._send_request(request)
response = await self._read_response()
if response.get("error"):
raise Exception(f"List tools failed: {response['error']}")
return response.get("result", {})
async def call_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
"""Call a specific tool"""
request = {
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": tool_name,
"arguments": arguments
}
}
await self._send_request(request)
response = await self._read_response()
if response.get("error"):
raise Exception(f"Tool call failed: {response['error']}")
return response.get("result", {})
async def _send_request(self, request: Dict[str, Any]):
"""Send a JSON-RPC request to the server"""
if not self.process:
raise Exception("Server not started")
message = json.dumps(request) + "\n"
self.process.stdin.write(message.encode())
await self.process.stdin.drain()
async def _read_response(self) -> Dict[str, Any]:
"""Read a JSON-RPC response from the server"""
if not self.process:
raise Exception("Server not started")
line = await self.process.stdout.readline()
if not line:
raise Exception("No response from server")
try:
return json.loads(line.decode().strip())
except json.JSONDecodeError as e:
raise Exception(f"Invalid JSON response: {e}")
async def close(self):
"""Close the connection to the server"""
if self.process:
self.process.terminate()
await self.process.wait()
async def main():
"""Main demonstration of MCP client usage"""
client = InsightBotMCPClient()
try:
# Start the server
print("🚀 Starting MCP server...")
await client.start_server()
# List available tools
print("\n📋 Listing available tools...")
tools_result = await client.list_tools()
tools = tools_result.get("tools", [])
print(f"Found {len(tools)} tools:")
for tool in tools:
print(f" - {tool['name']}: {tool['description']}")
# Example 1: Upload a document
print("\n📤 Uploading a sample document...")
upload_result = await client.call_tool("upload_document", {
"content": "This is a sample document about artificial intelligence and machine learning.",
"filename": "sample.txt",
"content_type": "text/plain"
})
print("Upload result:")
for content in upload_result.get("content", []):
print(content["text"])
# Example 2: Query documents
print("\n🔍 Querying documents...")
query_result = await client.call_tool("query_documents", {
"query": "What is artificial intelligence?",
"session_id": "demo-session"
})
print("Query result:")
for content in query_result.get("content", []):
print(content["text"])
# Example 3: Get document stats
print("\n📊 Getting document statistics...")
stats_result = await client.call_tool("get_document_stats", {})
print("Document stats:")
for content in stats_result.get("content", []):
print(content["text"])
# Example 4: Search similar documents
print("\n🔎 Searching for similar documents...")
search_result = await client.call_tool("search_similar_documents", {
"query": "machine learning",
"limit": 3
})
print("Search result:")
for content in search_result.get("content", []):
print(content["text"])
except Exception as e:
print(f"❌ Error: {e}")
return 1
finally:
await client.close()
print("\n✅ MCP client demo completed successfully!")
return 0
if __name__ == "__main__":
sys.exit(asyncio.run(main()))