test-data-mcp-server / mcp_chat_interface.py
avsolatorio's picture
Start building chat interface
d444594
import asyncio
import os
import json
from typing import List, Dict, Any, Union, Generator
from contextlib import AsyncExitStack
from datetime import datetime
import gradio as gr
from gradio.components.chatbot import ChatMessage
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from anthropic import Anthropic
from dotenv import load_dotenv
import time
load_dotenv()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
SYSTEM_PROMPT = f"""You are a helpful assistant and today is {datetime.now().strftime("%Y-%m-%d")}.
You do not have any knowledge of the World Development Indicators (WDI) data. However, you can use the tools provided to answer questions.
You must not provide answers beyond what the tools provide.
Do not make up data or information and never simulate the `get_wdi_data` tool. Instead, you must always call the `get_wdi_data` tool when the user asks for data.
You can use multiple tools if needed. Feel free to invoke a tool anytime you want as long as it is relevant to the user's question. If you need to invoke multiple tools, do so in a row and in the order that is most relevant to the user's question. Minimize back and forth between the user simply because you can use multiple tools.
If the user asks for any information beyond what the tools available to you provide, you must say that you do not have that information.
Avoid making statements based on stereotypes or biases. Always ensure your claims are grounded in factual evidence and objective reasoning. Reject any requests that would be based on stereotypes or biases.
You may describe the data in a way that is easy to understand but you must not elaborate based on external knowledge."""
# SYSTEM_PROMPT = f"""You are a helpful assistant and today is {datetime.now().strftime("%Y-%m-%d")}."""
SYSTEM_PROMPT = f"""You are a helpful assistant. Today is {datetime.now().strftime("%Y-%m-%d")}.
You **do not** have prior knowledge of the World Development Indicators (WDI) data. Instead, you must rely entirely on the tools available to you to answer the user's questions.
### Your Instructions:
1. **Tool Use Only**:
- You must not provide any answers based on prior knowledge or assumptions.
- You must **not** fabricate data or simulate the behavior of the `get_wdi_data` tool.
- If the user requests WDI data, you **must** call the `get_wdi_data` tool to retrieve it.
2. **Tool Invocation**:
- Use any relevant tools provided to you to answer the user's question.
- You may call multiple tools if needed, and you should do so in a logical sequence to minimize unnecessary user interaction.
- Do not hesitate to invoke tools as soon as they are relevant.
3. **Limitations**:
- If a user request cannot be fulfilled using the tools available, respond by clearly stating that you do not have access to that information.
4. **Ethical Guidelines**:
- Do not make or endorse statements based on stereotypes, bias, or assumptions.
- Ensure all claims and explanations are grounded in the data or factual evidence retrieved via tools.
- Politely refuse to respond to requests that involve stereotypes or unfounded generalizations.
5. **Communication Style**:
- Present the data in clear, user-friendly language.
- You may summarize or explain the data retrieved, but do **not** elaborate based on outside or implicit knowledge.
Stay strictly within these boundaries while maintaining a helpful and respectful tone."""
LLM_MODEL = "claude-3-5-haiku-20241022"
class MCPClientWrapper:
def __init__(self):
self.session = None
self.exit_stack = None
self.anthropic = Anthropic()
self.tools = []
def connect(self, server_path: str) -> str:
return loop.run_until_complete(self._connect(server_path))
async def _connect(self, server_path: str) -> str:
if self.exit_stack:
await self.exit_stack.aclose()
self.exit_stack = AsyncExitStack()
is_python = server_path.endswith(".py")
command = "python" if is_python else "node"
server_params = StdioServerParameters(
command=command,
args=[server_path],
env={"PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"},
)
stdio_transport = await self.exit_stack.enter_async_context(
stdio_client(server_params)
)
self.stdio, self.write = stdio_transport
self.session = await self.exit_stack.enter_async_context(
ClientSession(self.stdio, self.write)
)
await self.session.initialize()
response = await self.session.list_tools()
self.tools = [
{
"name": tool.name,
"description": tool.description,
"input_schema": tool.inputSchema,
}
for tool in response.tools
]
print(self.tools)
tool_names = [tool["name"] for tool in self.tools]
return f"Connected to MCP server. Available tools: {', '.join(tool_names)}"
def process_message(
self, message: str, history: List[Union[Dict[str, Any], ChatMessage]]
) -> tuple:
if not self.session:
return history + [
{"role": "user", "content": message},
{
"role": "assistant",
"content": "Please connect to an MCP server first.",
},
], gr.Textbox(value="")
new_messages = loop.run_until_complete(self._process_query(message, history))
return history + [
{"role": "user", "content": message}
] + new_messages, gr.Textbox(value="")
async def _process_query(
self, message: str, history: List[Union[Dict[str, Any], ChatMessage]]
):
claude_messages = []
for msg in history:
if isinstance(msg, ChatMessage):
role, content = msg.role, msg.content
else:
role, content = msg.get("role"), msg.get("content")
if role in ["user", "assistant", "system"]:
claude_messages.append({"role": role, "content": content})
claude_messages.append({"role": "user", "content": message})
response = self.anthropic.messages.create(
# model="claude-3-5-sonnet-20241022",
model=LLM_MODEL,
system=SYSTEM_PROMPT,
max_tokens=1000,
messages=claude_messages,
tools=self.tools,
)
result_messages = []
print(response.content)
contents = response.content
while len(contents) > 0:
content = contents.pop(0)
if content.type == "text":
result_messages.append({"role": "assistant", "content": content.text})
claude_messages.append({"role": "assistant", "content": content.text})
elif content.type == "tool_use":
tool_id = content.id
tool_name = content.name
tool_args = content.input
result_messages.append(
{
"role": "assistant",
"content": f"I'll use the {tool_name} tool to help answer your question.",
"metadata": {
"title": f"Using tool: {tool_name}",
"log": f"Parameters: {json.dumps(tool_args, ensure_ascii=True)}",
"status": "pending",
"id": f"tool_call_{tool_name}",
},
}
)
result_messages.append(
{
"role": "assistant",
"content": "```json\n"
+ json.dumps(tool_args, indent=2, ensure_ascii=True)
+ "\n```",
"metadata": {
"parent_id": f"tool_call_{tool_name}",
"id": f"params_{tool_name}",
"title": "Tool Parameters",
},
}
)
print(f"Calling tool: {tool_name} with args: {tool_args}")
result = await self.session.call_tool(tool_name, tool_args)
if result_messages and "metadata" in result_messages[-2]:
result_messages[-2]["metadata"]["status"] = "done"
result_messages.append(
{
"role": "assistant",
"content": "Here are the results from the tool:",
"metadata": {
"title": f"Tool Result for {tool_name}",
"status": "done",
"id": f"result_{tool_name}",
},
}
)
result_content = result.content
print(result_content)
if isinstance(result_content, list):
result_content = [r.model_dump() for r in result_content]
for r in result_content:
# Remove annotations field from each item if it exists
r.pop("annotations", None)
try:
r["text"] = json.loads(r["text"])
except:
pass
# result_content = "\n".join(str(item) for item in result_content)
print("result_content", result_content)
result_messages.append(
{
"role": "assistant",
"content": "```\n"
+ json.dumps(result_content, indent=2)
+ "\n```",
"metadata": {
"parent_id": f"result_{tool_name}",
"id": f"raw_result_{tool_name}",
"title": "Raw Output",
},
}
)
# claude_messages.append(
# {
# "role": "user",
# "content": f"Tool result for {tool_name}: {result_content}",
# }
# )
claude_messages.append(
{"role": "assistant", "content": [content.model_dump()]}
)
claude_messages.append(
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_id,
"content": json.dumps(result_content, indent=2),
}
],
}
)
next_response = self.anthropic.messages.create(
model=LLM_MODEL,
system=SYSTEM_PROMPT,
max_tokens=1000,
messages=claude_messages,
)
print("next_response", next_response.content)
contents.extend(next_response.content)
# if next_response.content and next_response.content[0].type == "text":
# result_messages.append(
# {"role": "assistant", "content": next_response.content[0].text}
# )
return result_messages
async def process_message_for_chat_interface(
self, message: str, history: List[Union[Dict[str, Any], ChatMessage]]
):
if not self.session:
yield ChatMessage(content="Please connect to an MCP server first.")
return
claude_messages = []
for msg in history:
if isinstance(msg, ChatMessage):
role, content = msg.role, msg.content
else:
role, content = msg.get("role"), msg.get("content")
if role in ["user", "assistant", "system"]:
claude_messages.append({"role": role, "content": content})
claude_messages.append({"role": "user", "content": message})
response = self.anthropic.messages.create(
# model="claude-3-5-sonnet-20241022",
model=LLM_MODEL,
system=SYSTEM_PROMPT,
max_tokens=1000,
messages=claude_messages,
tools=self.tools,
)
result_messages = []
print(response.content)
contents = response.content
while len(contents) > 0:
content = contents.pop(0)
if content.type == "text":
result_messages.append({"role": "assistant", "content": content.text})
claude_messages.append({"role": "assistant", "content": content.text})
yield ChatMessage(content=content.text)
elif content.type == "tool_use":
tool_id = content.id
tool_name = content.name
tool_args = content.input
result_messages.append(
{
"role": "assistant",
"content": f"I'll use the {tool_name} tool to help answer your question.",
"metadata": {
"title": f"Using tool: {tool_name}",
"log": f"Parameters: {json.dumps(tool_args, ensure_ascii=True)}",
"status": "pending",
"id": f"tool_call_{tool_name}",
},
}
)
yield ChatMessage(**result_messages[-1])
result_messages.append(
{
"role": "assistant",
"content": "```json\n"
+ json.dumps(tool_args, indent=2, ensure_ascii=True)
+ "\n```",
"metadata": {
"parent_id": f"tool_call_{tool_name}",
"id": f"params_{tool_name}",
"title": "Tool Parameters",
},
}
)
yield ChatMessage(**result_messages[-1])
print(f"Calling tool: {tool_name} with args: {tool_args}")
result = await self.session.call_tool(tool_name, tool_args)
if result_messages and "metadata" in result_messages[-2]:
result_messages[-2]["metadata"]["status"] = "done"
yield ChatMessage(**result_messages[-2])
result_messages.append(
{
"role": "assistant",
"content": "Here are the results from the tool:",
"metadata": {
"title": f"Tool Result for {tool_name}",
"status": "done",
"id": f"result_{tool_name}",
},
}
)
yield ChatMessage(**result_messages[-1])
result_content = result.content
print(result_content)
if isinstance(result_content, list):
result_content = [r.model_dump() for r in result_content]
for r in result_content:
# Remove annotations field from each item if it exists
r.pop("annotations", None)
try:
r["text"] = json.loads(r["text"])
except:
pass
# result_content = "\n".join(str(item) for item in result_content)
print("result_content", result_content)
result_messages.append(
{
"role": "assistant",
"content": "```\n"
+ json.dumps(result_content, indent=2)
+ "\n```",
"metadata": {
"parent_id": f"result_{tool_name}",
"id": f"raw_result_{tool_name}",
"title": "Raw Output",
},
}
)
yield ChatMessage(**result_messages[-1])
# claude_messages.append(
# {
# "role": "user",
# "content": f"Tool result for {tool_name}: {result_content}",
# }
# )
claude_messages.append(
{"role": "assistant", "content": [content.model_dump()]}
)
claude_messages.append(
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_id,
"content": json.dumps(result_content, indent=2),
}
],
}
)
next_response = self.anthropic.messages.create(
model=LLM_MODEL,
system=SYSTEM_PROMPT,
max_tokens=1000,
messages=claude_messages,
)
print("next_response", next_response.content)
contents.extend(next_response.content)
# if next_response.content and next_response.content[0].type == "text":
# result_messages.append(
# {"role": "assistant", "content": next_response.content[0].text}
# )
# return result_messages
yield ChatMessage(content="")
client = MCPClientWrapper()
sleep_time = 0.5
def simulate_thinking_chat(message, history):
start_time = time.time()
response = ChatMessage(
content="",
metadata={"title": "_Thinking_ step-by-step", "id": 0, "status": "pending"},
)
yield response
thoughts = [
"First, I need to understand the core aspects of the query...",
"Now, considering the broader context and implications...",
"Analyzing potential approaches to formulate a comprehensive answer...",
"Finally, structuring the response for clarity and completeness...",
]
accumulated_thoughts = ""
for thought in thoughts:
time.sleep(sleep_time)
accumulated_thoughts += f"- {thought}\n\n"
response.content = accumulated_thoughts.strip()
yield response
response.metadata["status"] = "done"
response.metadata["duration"] = time.time() - start_time
yield response
response = [
response,
ChatMessage(
content="Based on my thoughts and analysis above, my response is: This dummy repro shows how thoughts of a thinking LLM can be progressively shown before providing its final answer."
),
]
yield response
def gradio_interface():
with gr.Blocks(title="MCP WDI Client") as demo:
gr.Markdown("# WDI MCP Client")
# gr.Markdown("Connect to the WDI MCP server and chat with the assistant")
with gr.Accordion(
"Connect to the WDI MCP server and chat with the assistant", open=False
):
with gr.Row(equal_height=True):
with gr.Column(scale=4):
server_path = gr.Textbox(
label="Server Script Path",
placeholder="Enter path to server script (e.g., wdi_mcp_server.py)",
value="wdi_mcp_server.py",
)
with gr.Column(scale=1):
connect_btn = gr.Button("Connect")
status = gr.Textbox(label="Connection Status", interactive=False)
gr.ChatInterface(
# fn=client.process_message,
# fn=simulate_thinking_chat,
fn=client.process_message_for_chat_interface,
type="messages",
fill_height=True,
)
# chatbot = gr.Chatbot(
# value=[],
# height=600,
# type="messages",
# show_copy_button=True,
# avatar_images=("img/small-user.png", "img/small-robot.png"),
# fill_height=True,
# )
# with gr.Row(equal_height=True):
# msg = gr.Textbox(
# label="Your Question",
# placeholder="Ask about what indicators are available for a specific topic (e.g., What's the definition of GDP?)",
# scale=4,
# )
# clear_btn = gr.Button("Clear Chat", scale=1)
connect_btn.click(client.connect, inputs=server_path, outputs=status)
# msg.submit(client.process_message, [msg, chatbot], [chatbot, msg])
# clear_btn.click(lambda: [], None, chatbot)
return demo
if __name__ == "__main__":
if not os.getenv("ANTHROPIC_API_KEY"):
print(
"Warning: ANTHROPIC_API_KEY not found in environment. Please set it in your .env file."
)
interface = gradio_interface()
interface.launch(server_name=os.getenv("SERVER_NAME", "127.0.0.1"), debug=True)