Timothy Eastridge commited on
Commit Β·
f831e98
1
Parent(s): da2713e
commit streamlit
Browse filesFiles changed (7)
34 unmodified lines35363738394011 unmodified lines5253545556575859606112 unmodified lines7475767778794 unmodified lines84858687888934 unmodified lines@docker-compose exec postgres pg_isready -U postgres > /dev/null 2>&1 && echo "β PostgreSQL: Healthy" || echo "β PostgreSQL: Unhealthy"@curl -s http://localhost:8000/health > /dev/null && echo "β MCP Server: Healthy" || echo "β MCP Server: Unhealthy"@curl -s http://localhost:3000 > /dev/null && echo "β Frontend: Healthy" || echo "β Frontend: Unhealthy"@docker-compose ps agent | grep -q "Up" && echo "β Agent: Running" || echo "β Agent: Not running"# Run integration test11 unmodified lines@make seed@echo ""@echo "π Demo Ready!"@echo "1. Open http://localhost:3000 in your browser"@echo "2. Ask a question like: 'Show me all customers who have placed orders'"@echo "3. Watch the agent process through the workflow"@echo "4. Check Neo4j Browser at http://localhost:7474 (neo4j/password)"@echo ""@echo "During 5-minute pauses, you can edit instructions in Neo4j Browser:"@echo "MATCH (i:Instruction {status: 'pending'}) SET i.parameters = '{\"question\": \"new question\"}'"12 unmodified linesrestart-frontend:docker-compose restart frontend# Debug commandsdebug-agent:docker-compose logs agent4 unmodified linesdebug-frontend:docker-compose logs frontend# Quick status checkstatus:docker-compose ps34 unmodified lines3536373839404111 unmodified lines535455565758596061626312 unmodified lines7677787980818283844 unmodified lines89909192939495969734 unmodified lines@docker-compose exec postgres pg_isready -U postgres > /dev/null 2>&1 && echo "β PostgreSQL: Healthy" || echo "β PostgreSQL: Unhealthy"@curl -s http://localhost:8000/health > /dev/null && echo "β MCP Server: Healthy" || echo "β MCP Server: Unhealthy"@curl -s http://localhost:3000 > /dev/null && echo "β Frontend: Healthy" || echo "β Frontend: Unhealthy"@curl -s http://localhost:8501 > /dev/null && echo "β Streamlit: Healthy" || echo "β Streamlit: Unhealthy"@docker-compose ps agent | grep -q "Up" && echo "β Agent: Running" || echo "β Agent: Not running"# Run integration test11 unmodified lines@make seed@echo ""@echo "π Demo Ready!"@echo "1. Open http://localhost:3000 in your browser (Main Chat Interface)"@echo "2. Open http://localhost:8501 in your browser (Streamlit Monitor)"@echo "3. Ask a question like: 'Show me all customers who have placed orders'"@echo "4. Watch the agent process through the workflow"@echo "5. Check Neo4j Browser at http://localhost:7474 (neo4j/password)"@echo ""@echo "During 5-minute pauses, you can edit instructions in Neo4j Browser:"@echo "MATCH (i:Instruction {status: 'pending'}) SET i.parameters = '{\"question\": \"new question\"}'"12 unmodified linesrestart-frontend:docker-compose restart frontendrestart-streamlit:docker-compose restart streamlit# Debug commandsdebug-agent:docker-compose logs agent4 unmodified linesdebug-frontend:docker-compose logs frontenddebug-streamlit:docker-compose logs streamlit# Quick status checkstatus:docker-compose ps
123# Graph-Driven Agentic System with Human-in-the-Loop Controls## What This System Is12345678#### Quick start prompt:Scan the repo: list the directory tree, key config files, and required env vars. Summarize how to start the system using existing scripts. Do not modify files; just report and wait for confirmation before any changes.Proceed with a fresh start by leveraging: powershell -ExecutionPolicy Bypass -File ops/scripts/fresh_start.ps1# Graph-Driven Agentic System with Human-in-the-Loop Controls## What This System Is
100 unmodified lines101102103104105106100 unmodified linesnetworks:- agent-networknetworks:agent-network:driver: bridge100 unmodified lines101102103104105106107108109110111112113114115116117118119120121100 unmodified linesnetworks:- agent-networkstreamlit:build: ./streamlitports:- "8501:8501"environment:- MCP_URL=http://mcp:8000/mcp- MCP_API_KEY=dev-key-123depends_on:mcp:condition: service_healthyvolumes:- ./streamlit:/appnetworks:- agent-networknetworks:agent-network:driver: bridge
12345678910111213141516171819FROM python:3.11-slim
WORKDIR /app
# Install system dependenciesRUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
# Copy requirements and install Python dependenciesCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# Copy application codeCOPY . .
# Expose portEXPOSE 8501
# Run StreamlitCMD ["streamlit", "run", "app.py", "--server.address=0.0.0.0"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484#!/usr/bin/env python3"""Streamlit MCP Monitor & Query TesterA lightweight monitoring and testing interface for the agentic system.All database access MUST go through MCP server - no direct connections allowed."""
import streamlit as stimport requestsimport timeimport jsonimport pandas as pdfrom datetime import datetime, timedeltaimport osfrom typing import Dict, Any, Optional, Tuple
# ConfigurationMCP_URL = os.getenv("MCP_URL", "http://mcp:8000/mcp")MCP_API_KEY = os.getenv("MCP_API_KEY", "dev-key-123")
# Page configurationst.set_page_config( page_title="MCP Monitor & Query Tester", page_icon="π€", layout="wide", initial_sidebar_state="expanded")
# Initialize session stateif 'workflow_id' not in st.session_state: st.session_state.workflow_id = Noneif 'debug_log' not in st.session_state: st.session_state.debug_log = []if 'last_refresh' not in st.session_state: st.session_state.last_refresh = None
def call_mcp(tool: str, params: Optional[Dict[str, Any]] = None) -> Tuple[Dict[str, Any], int]: """ Call MCP server - the ONLY way to access databases. Returns (response_data, response_time_ms) """ start_time = time.time() try: response = requests.post( MCP_URL, headers={ "X-API-Key": MCP_API_KEY, "Content-Type": "application/json" }, json={"tool": tool, "params": params or {}}, timeout=10 ) response_time = int((time.time() - start_time) * 1000) # Log the request/response for debugging debug_entry = { "timestamp": datetime.now().isoformat(), "tool": tool, "params": params, "status_code": response.status_code, "response_time_ms": response_time, "success": response.status_code == 200 } st.session_state.debug_log.append(debug_entry) # Keep only last 5 entries if len(st.session_state.debug_log) > 5: st.session_state.debug_log = st.session_state.debug_log[-5:] if response.status_code == 200: return response.json(), response_time else: return {"error": f"HTTP {response.status_code}: {response.text}"}, response_time except requests.exceptions.RequestException as e: response_time = int((time.time() - start_time) * 1000) error_msg = f"MCP Server Error: {str(e)}" # Log the error debug_entry = { "timestamp": datetime.now().isoformat(), "tool": tool, "params": params, "status_code": 0, "response_time_ms": response_time, "success": False, "error": error_msg } st.session_state.debug_log.append(debug_entry) return {"error": error_msg}, response_time
def test_neo4j_connection() -> Tuple[bool, int, str]: """Test Neo4j connection through MCP server""" result, response_time = call_mcp("get_schema") if "error" in result: return False, response_time, result["error"] return True, response_time, "Connected"
def test_postgres_connection() -> Tuple[bool, int, str]: """Test PostgreSQL connection through MCP server""" result, response_time = call_mcp("query_postgres", {"query": "SELECT 1 as test"}) if "error" in result: return False, response_time, result["error"] return True, response_time, "Connected"
def test_mcp_server() -> Tuple[bool, int, str]: """Test MCP server health""" try: start_time = time.time() response = requests.get(f"{MCP_URL.replace('/mcp', '/health')}", timeout=5) response_time = int((time.time() - start_time) * 1000) if response.status_code == 200: return True, response_time, "Healthy" else: return False, response_time, f"HTTP {response.status_code}" except Exception as e: return False, 0, str(e)
def get_performance_stats() -> Dict[str, Any]: """Get performance statistics through MCP""" result, _ = call_mcp("query_graph", { "query": "MATCH (l:Log) WHERE l.timestamp > datetime() - duration('PT1H') RETURN count(l) as count" }) if "error" in result: return {"error": result["error"]} return result.get("data", [{}])[0] if result.get("data") else {}
def create_workflow(question: str) -> Optional[str]: """Create a new workflow for the given question""" workflow_id = f"streamlit-{int(time.time())}" # Create workflow node workflow_result, _ = call_mcp("write_graph", { "action": "create_node", "label": "Workflow", "properties": { "id": workflow_id, "name": f"Streamlit Query: {question[:50]}...", "description": f"Query from Streamlit: {question}", "status": "active", "created_at": datetime.now().isoformat(), "source": "streamlit" } }) if "error" in workflow_result: st.error(f"Failed to create workflow: {workflow_result['error']}") return None # Create instruction sequence instructions = [ { "id": f"{workflow_id}-inst-1", "type": "discover_schema", "sequence": 1, "description": "Discover database schema", "status": "pending", "pause_duration": 5, # Short pause for testing "parameters": "{}" }, { "id": f"{workflow_id}-inst-2", "type": "generate_sql", "sequence": 2, "description": f"Generate SQL for: {question}", "status": "pending", "pause_duration": 5, "parameters": json.dumps({"question": question}) }, { "id": f"{workflow_id}-inst-3", "type": "review_results", "sequence": 3, "description": "Review and format results", "status": "pending", "pause_duration": 0, "parameters": "{}" } ] # Create instruction nodes for inst in instructions: inst_result, _ = call_mcp("write_graph", { "action": "create_node", "label": "Instruction", "properties": inst }) if "error" in inst_result: st.error(f"Failed to create instruction: {inst_result['error']}") return None # Link instruction to workflow link_result, _ = call_mcp("query_graph", { "query": """ MATCH (w:Workflow {id: $workflow_id}), (i:Instruction {id: $inst_id}) CREATE (w)-[:HAS_INSTRUCTION]->(i) """, "parameters": {"workflow_id": workflow_id, "inst_id": inst["id"]} }) # Create instruction chain for i in range(len(instructions) - 1): chain_result, _ = call_mcp("query_graph", { "query": """ MATCH (i1:Instruction {id: $id1}), (i2:Instruction {id: $id2}) CREATE (i1)-[:NEXT_INSTRUCTION]->(i2) """, "parameters": {"id1": instructions[i]["id"], "id2": instructions[i + 1]["id"]} }) return workflow_id
def get_workflow_status(workflow_id: str) -> Dict[str, Any]: """Get workflow execution status""" result, _ = call_mcp("query_graph", { "query": """ MATCH (w:Workflow {id: $id})-[:HAS_INSTRUCTION]->(i:Instruction) RETURN w.status as workflow_status, collect(i.status) as instruction_statuses, collect(i.type) as instruction_types, collect(i.sequence) as sequences """, "parameters": {"id": workflow_id} }) if "error" in result or not result.get("data"): return {"error": "Workflow not found"} return result["data"][0]
def get_workflow_results(workflow_id: str) -> Dict[str, Any]: """Get workflow execution results""" result, _ = call_mcp("query_graph", { "query": """ MATCH (w:Workflow {id: $id})-[:HAS_INSTRUCTION]->(i:Instruction)-[:EXECUTED_AS]->(e:Execution) RETURN i.sequence as sequence, i.type as type, i.description as description, e.result as result, e.started_at as started_at, e.completed_at as completed_at ORDER BY i.sequence """, "parameters": {"id": workflow_id} }) if "error" in result: return {"error": result["error"]} return {"executions": result.get("data", [])}
def get_schema_context() -> str: """Get database schema context for display""" result, _ = call_mcp("query_graph", { "query": """ MATCH (t:Table)-[:HAS_COLUMN]->(c:Column) RETURN t.name as table_name, collect({name: c.name, type: c.data_type, nullable: c.nullable}) as columns ORDER BY t.name """ }) if "error" in result: return f"Error fetching schema: {result['error']}" schema_text = "Database Schema:\n" for record in result.get("data", []): table_name = record["table_name"] columns = record["columns"] schema_text += f"\nTable: {table_name}\n" for col in columns: nullable = "NULL" if col["nullable"] else "NOT NULL" schema_text += f" - {col['name']}: {col['type']} {nullable}\n" return schema_text
def main(): st.title("π€ MCP Monitor & Query Tester") st.caption("Monitor agentic system health and test queries through MCP server") # Sidebar with st.sidebar: st.header("π§ Configuration") st.code(f"MCP URL: {MCP_URL}") st.code(f"API Key: {MCP_API_KEY[:10]}...") if st.button("π Refresh All", type="primary"): st.rerun() st.header("π Quick Stats") stats = get_performance_stats() if "error" not in stats: st.metric("Logs (1h)", stats.get("count", 0)) else: st.error(f"Stats error: {stats['error']}") # Main tabs tab1, tab2 = st.tabs(["π Connection Status", "π€ Query Tester"]) with tab1: st.header("Connection Status Monitor") st.caption("All database access goes through MCP server - no direct connections allowed") # Connection status in columns col1, col2, col3 = st.columns(3) with col1: st.subheader("Neo4j (via MCP)") neo4j_ok, neo4j_time, neo4j_msg = test_neo4j_connection() st.metric( label="Status", value="Online" if neo4j_ok else "Offline", delta=f"{neo4j_time}ms" ) if neo4j_ok: st.success(neo4j_msg) else: st.error(neo4j_msg) with col2: st.subheader("PostgreSQL (via MCP)") postgres_ok, postgres_time, postgres_msg = test_postgres_connection() st.metric( label="Status", value="Online" if postgres_ok else "Offline", delta=f"{postgres_time}ms" ) if postgres_ok: st.success(postgres_msg) else: st.error(postgres_msg) with col3: st.subheader("MCP Server") mcp_ok, mcp_time, mcp_msg = test_mcp_server() st.metric( label="Status", value="Online" if mcp_ok else "Offline", delta=f"{mcp_time}ms" ) if mcp_ok: st.success(mcp_msg) else: st.error(mcp_msg) # Performance stats st.subheader("Performance Statistics") stats = get_performance_stats() if "error" not in stats: st.info(f"Operations in last hour: {stats.get('count', 0)}") else: st.error(f"Cannot fetch stats: {stats['error']}") # Auto-refresh info st.session_state.last_refresh = datetime.now() st.caption(f"Last checked: {st.session_state.last_refresh.strftime('%H:%M:%S')}") # Auto-refresh every 5 seconds time.sleep(5) st.rerun() with tab2: st.header("Query Tester") st.caption("Test natural language queries through the agentic engine") # Query input question = st.text_area( "Enter your question:", height=100, placeholder="e.g., 'How many customers do we have?' or 'Show me all orders from last month'" ) col1, col2 = st.columns([1, 1]) with col1: if st.button("π Execute Query", type="primary", disabled=not question.strip()): if question.strip(): with st.spinner("Creating workflow..."): workflow_id = create_workflow(question.strip()) if workflow_id: st.session_state.workflow_id = workflow_id st.success(f"Workflow created: {workflow_id}") else: st.error("Failed to create workflow") with col2: if st.button("ποΈ Clear Results"): st.session_state.workflow_id = None st.rerun() # Workflow execution monitoring if st.session_state.workflow_id: st.subheader("Execution Progress") # Get workflow status status = get_workflow_status(st.session_state.workflow_id) if "error" in status: st.error(f"Status error: {status['error']}") else: workflow_status = status.get("workflow_status", "unknown") instruction_statuses = status.get("instruction_statuses", []) instruction_types = status.get("instruction_types", []) # Progress bar completed = sum(1 for s in instruction_statuses if s == "complete") total = len(instruction_statuses) progress = completed / total if total > 0 else 0 st.progress(progress) st.caption(f"Progress: {completed}/{total} instructions completed") # Status display status_cols = st.columns(len(instruction_types)) for i, (inst_type, inst_status) in enumerate(zip(instruction_types, instruction_statuses)): with status_cols[i]: if inst_status == "complete": st.success(f"β
{inst_type}") elif inst_status == "executing": st.warning(f"π {inst_type}") elif inst_status == "failed": st.error(f"β {inst_type}") else: st.info(f"β³ {inst_type}") # Get and display results if completed > 0: results = get_workflow_results(st.session_state.workflow_id) if "error" not in results: st.subheader("Execution Results") for execution in results.get("executions", []): with st.expander(f"Step {execution['sequence']}: {execution['type']}"): st.write(f"**Description:** {execution['description']}") if execution['started_at'] and execution['completed_at']: start = datetime.fromisoformat(execution['started_at'].replace('Z', '+00:00')) end = datetime.fromisoformat(execution['completed_at'].replace('Z', '+00:00')) duration = (end - start).total_seconds() st.write(f"**Duration:** {duration:.2f} seconds") if execution['result']: try: result_data = json.loads(execution['result']) if isinstance(execution['result'], str) else execution['result'] if execution['type'] == 'generate_sql' and 'generated_sql' in result_data: st.write("**Generated SQL:**") st.code(result_data['generated_sql'], language='sql') if 'data' in result_data and result_data['data']: st.write("**Query Results:**") df = pd.DataFrame(result_data['data']) st.dataframe(df) if 'error' in result_data: st.error(f"Error: {result_data['error']}") except Exception as e: st.write("**Raw Result:**") st.code(str(execution['result'])) else: st.error(f"Results error: {results['error']}") # Debug information with st.expander("π§ Debug Information"): st.write("**Last 5 MCP Requests:**") for entry in st.session_state.debug_log: status_icon = "β
" if entry["success"] else "β" st.write(f"{status_icon} {entry['timestamp']} - {entry['tool']} ({entry['response_time_ms']}ms)") if not entry["success"] and "error" in entry: st.error(f"Error: {entry['error']}") st.write("**Important:** All database operations go through MCP server. Direct database access is not permitted.")
if __name__ == "__main__": main()1234streamlit==1.28.0requests==2.31.0pandas==2.1.0python-dotenv==1.0.0Makefile+12-4
SYSTEM_OVERVIEW.md+5
app_requirements/6_feature_Streamlit.md β app_requirements/6_feature_Streamlit.txtRenamed
docker-compose.yml+15
streamlit/DockerfileAdded+19
streamlit/app.pyAdded+484
streamlit/requirements.txtAdded+4