Skip to content

Commit 5901abc

Browse files
committed
Add MCP AI assistant code
1 parent 38147ac commit 5901abc

File tree

8 files changed

+2692
-0
lines changed

8 files changed

+2692
-0
lines changed

.gitmodules

Whitespace-only changes.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
3.12
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# MCP-powered Ultimate AI Assistant
2+
3+
A Streamlit application that provides a chat interface for interacting with MCP (Model Context Protocol) servers. This app allows you to configure multiple MCP servers and chat with them using natural language.
4+
5+
Tech stack:
6+
- [mcp-use](https://github.com/mcp-use/mcp-use) to connect LLM to MCP servers
7+
- [Stagehand MCP](https://github.com/browserbase/mcp-server-browserbase) for browser access
8+
- [Firecrawl MCP](https://github.com/mendableai/firecrawl-mcp-server) for scraping
9+
- [Ragie MCP](https://github.com/ragieai/ragie-mcp-server) for multimodal RAG
10+
- [Graphiti MCP](https://github.com/getzep/graphiti/tree/main/mcp_server) as memory
11+
- [Terminal](https://github.com/wonderwhy-er/DesktopCommanderMCP) & [GitIngest](https://github.com/adhikasp/mcp-git-ingest) MCP
12+
13+
## Setup
14+
15+
1. **Install Dependencies**:
16+
```bash
17+
uv sync
18+
```
19+
20+
2. **Environment Variables**:
21+
Create a `.env` file with your API keys:
22+
```env
23+
OPENAI_API_KEY=your-openai-api-key
24+
FIRECRAWL_API_KEY=your-firecrawl-api-key
25+
RAGIE_API_KEY=your-ragie-api-key
26+
```
27+
28+
3. **Setup MCP Servers**
29+
30+
Go to server.py and update the paths to the MCP servers according to your system.
31+
32+
3. **Run the App**:
33+
```bash
34+
streamlit run mcp_streamlit_app.py
35+
```
36+
37+
## Usage
38+
39+
1. **Configure MCP Servers**:
40+
- Use the sidebar to enter your MCP server configuration in JSON format
41+
- Click "Load Example Config" to see a sample configuration
42+
- Click "Activate Configuration" to initialize the MCP client
43+
44+
2. **Chat with MCP Tools**:
45+
- Once configured, use the chat interface to interact with your MCP servers
46+
- Ask questions about available tools or request specific actions
47+
- The agent will use the appropriate MCP tools to respond
48+
49+
## Example Configuration
50+
51+
```json
52+
{
53+
"mcpServers": {
54+
"stagehand": {
55+
"command": "node",
56+
"args": ["/path/to/stagehand/dist/index.js"],
57+
"env": {
58+
"OPENAI_API_KEY": "your-api-key",
59+
"LOCAL_CDP_URL": "http://localhost:9222"
60+
}
61+
},
62+
"firecrawl": {
63+
"command": "npx",
64+
"args": ["-y", "firecrawl-mcp"],
65+
"env": {
66+
"FIRECRAWL_API_KEY": "your-firecrawl-key"
67+
}
68+
}
69+
}
70+
}
71+
```
72+
73+
## 📬 Stay Updated with Our Newsletter!
74+
**Get a FREE Data Science eBook** 📖 with 150+ essential lessons in Data Science when you subscribe to our newsletter! Stay in the loop with the latest tutorials, insights, and exclusive resources. [Subscribe now!](https://join.dailydoseofds.com)
75+
76+
[![Daily Dose of Data Science Newsletter](https://github.com/patchy631/ai-engineering/blob/main/resources/join_ddods.png)](https://join.dailydoseofds.com)
77+
78+
---
79+
80+
## Contribution
81+
82+
Contributions are welcome! Please fork the repository and submit a pull request with your improvements.
Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
1+
import streamlit as st
2+
import asyncio
3+
import os
4+
import json
5+
from dotenv import load_dotenv
6+
# from langchain_ollama import ChatOllama
7+
from langchain_openai import ChatOpenAI
8+
from mcp_use import MCPAgent, MCPClient
9+
import mcp_use
10+
import warnings
11+
import base64
12+
13+
# Suppress warnings
14+
warnings.filterwarnings("ignore")
15+
mcp_use.set_debug(0)
16+
17+
# Load environment variables
18+
load_dotenv()
19+
20+
# Page configuration
21+
st.set_page_config(
22+
page_title="MCP-powered Perplexity Clone",
23+
page_icon="🤖",
24+
layout="wide",
25+
initial_sidebar_state="expanded"
26+
)
27+
28+
# Initialize session state
29+
if "messages" not in st.session_state:
30+
st.session_state.messages = []
31+
32+
if "mcp_client" not in st.session_state:
33+
st.session_state.mcp_client = None
34+
35+
if "agent" not in st.session_state:
36+
st.session_state.agent = None
37+
38+
def reset_chat():
39+
st.session_state.messages = []
40+
st.session_state.mcp_client = None
41+
st.session_state.agent = None
42+
43+
def create_mcp_client(config_dict):
44+
"""Create MCPClient from configuration dictionary."""
45+
try:
46+
client = MCPClient.from_dict(config_dict)
47+
return client
48+
except Exception as e:
49+
st.error(f"Error creating MCP client: {str(e)}")
50+
return None
51+
52+
def create_agent(client):
53+
"""Create MCPAgent with the client."""
54+
try:
55+
# Create LLM - you can switch between Ollama and OpenAI
56+
llm = ChatOpenAI(model="gpt-4o")
57+
# llm = ChatOllama(model="qwen3:1.7b")
58+
59+
agent = MCPAgent(llm=llm, client=client, max_steps=100)
60+
return agent
61+
except Exception as e:
62+
st.error(f"Error creating agent: {str(e)}")
63+
return None
64+
65+
async def run_agent_query(agent, query):
66+
"""Run a query through the MCP agent."""
67+
try:
68+
result = await agent.run(query)
69+
return result
70+
except Exception as e:
71+
return f"Error running query: {str(e)}"
72+
73+
# Main title
74+
st.markdown("""
75+
# 100% local Ultimate AI Assistant using mcp-use
76+
""", unsafe_allow_html=True)
77+
78+
st.markdown("Configure your MCP servers and chat with them using natural language!")
79+
80+
# Sidebar for configuration
81+
with st.sidebar:
82+
st.header("MCP Configuration")
83+
84+
# Configuration text area
85+
config_text = st.text_area(
86+
"Enter MCP Configuration (JSON)",
87+
height=400,
88+
placeholder='''{
89+
"mcpServers": {
90+
"stagehand": {
91+
"command": "node",
92+
"args": ["/path/to/mcp-server-browserbase/stagehand/dist/index.js"],
93+
"env": {
94+
"OPENAI_API_KEY": "your-api-key",
95+
"LOCAL_CDP_URL": "http://localhost:9222"
96+
}
97+
}
98+
}
99+
}''',
100+
help="Enter your MCP server configuration in JSON format"
101+
)
102+
103+
# Load example configuration
104+
if st.button("Load Example Config"):
105+
example_config = {
106+
"mcpServers": {
107+
"stagehand": {
108+
"command": "node",
109+
"args": ["/path/to/mcp-server-browserbase/stagehand/dist/index.js"],
110+
"env": {
111+
"OPENAI_API_KEY": os.getenv("OPENAI_API_KEY"),
112+
"LOCAL_CDP_URL": "http://localhost:9222",
113+
"DOWNLOADS_DIR": "/path/to/downloads/stagehand"
114+
}
115+
},
116+
"mcp-server-firecrawl": {
117+
"command": "npx",
118+
"args": ["-y", "firecrawl-mcp"],
119+
"env": {
120+
"FIRECRAWL_API_KEY": os.getenv("FIRECRAWL_API_KEY")
121+
}
122+
},
123+
"ragie": {
124+
"command": "npx",
125+
"args": ["-y", "@ragieai/mcp-server", "--partition", "default"],
126+
"env": {
127+
"RAGIE_API_KEY": os.getenv("RAGIE_API_KEY")
128+
}
129+
}
130+
}
131+
}
132+
st.session_state.example_config = json.dumps(example_config, indent=2)
133+
st.rerun()
134+
135+
# Display example config if loaded
136+
if 'example_config' in st.session_state:
137+
st.text_area("Example Configuration", st.session_state.example_config, height=200, disabled=True)
138+
139+
st.divider()
140+
141+
# Activate configuration button
142+
if st.button("Activate Configuration", type="primary"):
143+
if config_text.strip():
144+
try:
145+
# Parse JSON configuration
146+
config_dict = json.loads(config_text)
147+
148+
# Create MCP client
149+
client = create_mcp_client(config_dict)
150+
if client:
151+
st.session_state.mcp_client = client
152+
153+
# Create agent
154+
agent = create_agent(client)
155+
if agent:
156+
st.session_state.agent = agent
157+
st.success("✅ Configuration activated successfully!")
158+
159+
# Show available tools
160+
try:
161+
tools_info = "Available MCP tools:\n"
162+
for server_name, server_info in config_dict.get("mcpServers", {}).items():
163+
tools_info += f"- {server_name}\n"
164+
st.info(tools_info)
165+
except Exception as e:
166+
st.warning(f"Could not display tools info: {str(e)}")
167+
else:
168+
st.error("Failed to create agent")
169+
else:
170+
st.error("Failed to create MCP client")
171+
except json.JSONDecodeError as e:
172+
st.error(f"Invalid JSON configuration: {str(e)}")
173+
except Exception as e:
174+
st.error(f"Error activating configuration: {str(e)}")
175+
else:
176+
st.warning("Please enter a configuration first")
177+
178+
# Clear button
179+
if st.button("Clear Chat & Config"):
180+
reset_chat()
181+
st.rerun()
182+
183+
# Status indicator
184+
st.divider()
185+
st.subheader("Status")
186+
if st.session_state.mcp_client and st.session_state.agent:
187+
st.success("✅ MCP Client Active")
188+
st.success("✅ Agent Ready")
189+
else:
190+
st.warning("⚠️ Configuration not activated")
191+
192+
# Main chat interface
193+
194+
195+
# Display chat messages
196+
for message in st.session_state.messages:
197+
with st.chat_message(message["role"]):
198+
st.markdown(message["content"])
199+
200+
# Chat input
201+
if prompt := st.chat_input("Ask about your MCP tools..."):
202+
# Add user message to chat
203+
st.session_state.messages.append({"role": "user", "content": prompt})
204+
with st.chat_message("user"):
205+
st.markdown(prompt)
206+
207+
# Check if agent is available
208+
if not st.session_state.agent:
209+
with st.chat_message("assistant"):
210+
st.error("Please activate the MCP configuration first!")
211+
else:
212+
with st.chat_message("assistant"):
213+
with st.spinner("Processing your request..."):
214+
try:
215+
# Run the query asynchronously
216+
loop = asyncio.new_event_loop()
217+
asyncio.set_event_loop(loop)
218+
result = loop.run_until_complete(run_agent_query(st.session_state.agent, prompt))
219+
loop.close()
220+
221+
# Display result
222+
st.markdown(result)
223+
st.session_state.messages.append({"role": "assistant", "content": result})
224+
except Exception as e:
225+
error_msg = f"Error processing request: {str(e)}"
226+
st.error(error_msg)
227+
st.session_state.messages.append({"role": "assistant", "content": error_msg})
228+
229+
# Footer
230+
st.markdown("---")
231+
st.markdown("Built using mcp-use and Streamlit")
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
[project]
2+
name = "mcp-use-visual"
3+
version = "0.1.0"
4+
description = "Add your description here"
5+
readme = "README.md"
6+
requires-python = ">=3.12"
7+
dependencies = [
8+
"assemblyai>=0.42.0",
9+
"ipykernel>=6.30.0",
10+
"langchain-ollama>=0.3.5",
11+
"langchain-openai>=0.3.28",
12+
"mcp-use>=1.3.7",
13+
"streamlit>=1.47.1",
14+
]
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
streamlit>=1.28.0
2+
python-dotenv>=1.0.0
3+
langchain-openai>=0.1.0
4+
langchain-ollama>=0.1.0
5+
mcp-use>=0.1.0
6+
asyncio

0 commit comments

Comments
 (0)