-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp_chatbot.py
More file actions
311 lines (265 loc) · 12.6 KB
/
mcp_chatbot.py
File metadata and controls
311 lines (265 loc) · 12.6 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
from dotenv import load_dotenv
from anthropic import Anthropic
from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
from typing import List, Dict, TypedDict
from contextlib import AsyncExitStack
import json
import asyncio
load_dotenv()
class ToolDefinition(TypedDict):
name: str
description: str
input_schema: dict
class PromptDefinition(TypedDict):
name: str
description: str
arguments: list
class MCP_ChatBot:
def __init__(self):
# Initialize session and client objects
self.sessions: List[ClientSession] = [] # new
self.exit_stack = AsyncExitStack() # new
self.anthropic = Anthropic()
self.available_tools: List[ToolDefinition] = []
self.available_prompts: List[PromptDefinition] = []
self.available_resources = [] # new
self.tool_to_session: Dict[str, ClientSession] = {}
self.prompt_to_session: Dict[str, ClientSession] = {}
self.resource_to_session: Dict[str, ClientSession] = {} # new
async def connect_to_server(self, server_name: str, server_config: dict) -> None:
"""Connect to a single MCP server."""
try:
server_params = StdioServerParameters(**server_config)
stdio_transport = await self.exit_stack.enter_async_context(
stdio_client(server_params)
) # new
read, write = stdio_transport
session = await self.exit_stack.enter_async_context(
ClientSession(read, write)
) # new
await session.initialize()
self.sessions.append(session)
try:
# List available tools for this session
response = await session.list_tools()
tools = response.tools
print(f"\nConnected to {server_name} with tools:", [t.name for t in tools])
for tool in tools: # new
self.tool_to_session[tool.name] = session
self.available_tools.append({
"name": tool.name,
"description": tool.description,
"input_schema": tool.inputSchema
})
# List available prompts
prompt_response = await session.list_prompts()
if prompt_response and prompt_response.prompts:
for prompt in prompt_response.prompts:
self.prompt_to_session[prompt.name] = session
self.available_prompts.append({
"name": prompt.name,
"description": prompt.description,
"arguments": prompt.arguments
})
# List available resources
resource_response = await session.list_resources()
if resource_response and resource_response.resources:
for resource in resource_response.resources:
resource_uri = str(resource.uri)
self.resource_to_session[resource_uri] = session
self.available_resources.append(resource_uri)
except Exception as e:
print(f"Error listing tools, prompts or resources for {server_name}: {e}")
except Exception as e:
print(f"Failed to connect to {server_name}: {e}")
async def connect_to_servers(self): # new
"""Connect to all configured MCP servers."""
try:
with open("server_config.json", "r") as file:
data = json.load(file)
servers = data.get("mcpServers", {})
for server_name, server_config in servers.items():
await self.connect_to_server(server_name, server_config)
except Exception as e:
print(f"Error loading server configuration: {e}")
raise
async def process_query(self, query):
messages = [{'role':'user', 'content':query}]
response = self.anthropic.messages.create(max_tokens = 2024,
system = """print("Type your queries or 'quit' to exit.")
print("Use @folders to see available topics")
print("Use @<topic> to search papers in that topic")
print("Use /prompts to list available prompts")
print("Use /prompt <name> <arg1 = value1> to execute a prompt")""",
model = 'claude-3-7-sonnet-20250219',
tools = self.available_tools,
messages = messages)
process_query = True
while process_query:
assistant_content = []
has_tool_use = False
for content in response.content:
if content.type =='text':
print(content.text)
assistant_content.append(content)
if(len(response.content) == 1):
process_query= False
elif content.type == 'tool_use':
has_tool_use = True
assistant_content.append(content)
messages.append({'role':'assistant', 'content':assistant_content})
tool_id = content.id
tool_args = content.input
tool_name = content.name
print(f"Calling tool {tool_name} with args {tool_args}")
# Call a tool
session = self.tool_to_session[tool_name] # new
if not session:
print(f"No tool with name {tool_name} found.")
break
result = await session.call_tool(tool_name, arguments=tool_args)
messages.append({"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id":tool_id,
"content": result.content
}
]
})
response = self.anthropic.messages.create(max_tokens = 2024,
system = """print("Type your queries or 'quit' to exit.")
print("Use @folders to see available topics")
print("Use @<topic> to search papers in that topic")
print("Use /prompts to list available prompts")
print("Use /prompt <name> <arg1 = value1> to execute a prompt")""",
model = 'claude-3-7-sonnet-20250219',
tools = self.available_tools,
messages = messages)
if(len(response.content) == 1 and response.content[0].type == "text"):
print(response.content[0].text)
process_query= False
async def get_resources(self, resource_uri):
session = self.resource_to_session.get(resource_uri)
# Fall back for papers URIs - try any papers resource session
if not session and resource_uri.startswith("papers://"):
for uri, sess in self.resource_to_session.items():
if uri.startswith("papers://"):
session = sess
break
if not session:
print(f"Resource {resource_uri} not found in any server")
return
try:
result = await session.read_resource(uri=resource_uri)
if result and result.contents:
print(f"\nResource: {resource_uri}")
print("Content:")
print(result.contents[0].text)
else:
print(f"No content available")
except Exception as e:
print(f"Error: {e}")
async def list_prompts(self):
"""List all available prompts"""
if not self.available_prompts:
print("No prompts available.")
return
print("\nAvailable Prompts:")
for prompt in self.available_prompts:
print(f"- {prompt['name']}: {prompt['description']}")
if prompt['arguments']:
for arg in prompt['arguments']:
arg_name = arg.name if hasattr(arg, 'name') else arg.get('name', '')
print(f" - {arg_name}")
async def execute_prompt(self, prompt_name, args):
"""Execute a specific prompt with given arguments"""
session = self.prompt_to_session.get(prompt_name)
if not session:
print(f"Prompt {prompt_name} not found in any server")
return
try:
result = await session.get_prompt(prompt_name, arguments = args)
if result and result.messages:
prompt_content = result.messages[0].content
# Extract text from content (handles different formats)
if isinstance(prompt_content, str):
text = prompt_content
elif hasattr(prompt_content, 'text'):
text = prompt_content.text
else:
# Handles list of content items
text = " ".join(item.text if hasattr(item, 'text') else str(item) for item in prompt_content)
print(f"\nExecuting Prompt: {prompt_name}...")
await self.process_query(text)
except Exception as e:
print(f"Error executing prompt {prompt_name}: {e}")
async def chat_loop(self):
# For adding the particular user interface for getting accesss to the prompts and resources in each servers.
"""Run an interactive chat loop"""
print("\nMCP Chatbot Started!")
print("Type your queries or 'quit' to exit.")
print("Use @folders to see available topics")
print("Use @<topic> to search papers in that topic")
print("Use /prompts to list available prompts")
print("Use /prompt <name> <arg1 = value1> to execute a prompt")
while True:
try:
query = input("\nQuery: ").strip()
if not query:
continue
if query.lower() == 'quit':
break
# Check for @Resource syntax first
if query.startswith('@'):
# Remove @ sign
topic = query[1:].strip()
if topic == "folders":
resource_uri = "papers://folders"
else:
resource_uri = f"papers://{topic}"
await self.get_resources(resource_uri)
continue
# Check for /prompts command
if query.startswith('/'):
parts = query.split()
command = parts[0].lower()
if command == '/prompts':
await self.list_prompts()
elif command == '/prompt':
if len(parts) < 2:
print("Usage: /prompt <name> <arg1=value1> <arg2=value2> ...")
continue
prompt_name = parts[1]
args = {}
#parse arguments
for arg in parts[2:]:
if '=' in arg:
key, value = arg.split('=', 1)
args[key] = value.strip()
else:
print(f"Invalid argument format: {arg}")
continue
await self.execute_prompt(prompt_name, args)
else:
print(f"Unknown command: {command}")
continue
await self.process_query(query)
except Exception as e:
print(f"\nError: {str(e)}")
async def cleanup(self): # new
"""Cleanly close all resources using AsyncExitStack."""
await self.exit_stack.aclose()
async def main():
chatbot = MCP_ChatBot()
try:
# the mcp clients and sessions are not initialized using "with"
# like in the previous lesson
# so the cleanup should be manually handled
await chatbot.connect_to_servers() # new!
await chatbot.chat_loop()
finally:
await chatbot.cleanup() #new!
if __name__ == "__main__":
asyncio.run(main())