FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.
C++ ai-agentsalgorithmic-tradingbloomberg-terminalcppfinancefinancial-marketsfintechgood-first-issueinvestmentinvestment-researchmachine-learningopensourcepythonqtquantitative-financestock-markettrading
mcp update
tilakpatel22a73966f04a60
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.toml b/fincept-terminal-desktop/src-tauri/Cargo.tomlindex 8dde4e01a..007f2a357 100644--- a/fincept-terminal-desktop/src-tauri/Cargo.toml+++ b/fincept-terminal-desktop/src-tauri/Cargo.toml@@ -21,7 +21,7 @@ crate-type = ["staticlib", "cdylib", "rlib"]tauri-build = { version = "2", features = [] }[dependencies]-tauri = { version = "2", features = [] }+tauri = { version = "2", features = ["devtools"] }tauri-plugin-opener = "2"tauri-plugin-cors-fetch = "4"tauri-plugin-sql = { version = "2", features = ["sqlite"] }diff --git a/fincept-terminal-desktop/src-tauri/src/commands/alphavantage.rs b/fincept-terminal-desktop/src-tauri/src/commands/alphavantage.rsindex 509959223..2de85ea51 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/alphavantage.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/alphavantage.rs@@ -1,6 +1,5 @@// Alpha Vantage data commands-use std::process::Command;-use crate::utils::python::{get_python_path, get_script_path};+use crate::utils::python::execute_python_command;/// Execute Alpha Vantage Python script command#[tauri::command]@@ -9,26 +8,12 @@ pub async fn execute_alphavantage_command(command: String,args: Vec<String>,) -> Result<String, String> {- let python_path = get_python_path(&app)?;- let script_path = get_script_path(&app, "alphavantage_data.py")?;-// Build command arguments- let mut cmd_args = vec![script_path.to_string_lossy().to_string(), command];+ let mut cmd_args = vec![command];cmd_args.extend(args);- // Execute Python script- let output = Command::new(&python_path)- .args(&cmd_args)- .output()- .map_err(|e| format!("Failed to execute Alpha Vantage command: {}", e))?;-- if output.status.success() {- let stdout = String::from_utf8_lossy(&output.stdout);- Ok(stdout.to_string())- } else {- let stderr = String::from_utf8_lossy(&output.stderr);- Err(format!("Alpha Vantage command failed: {}", stderr))- }+ // Execute Python script with console window hidden on Windows+ execute_python_command(&app, "alphavantage_data.py", &cmd_args)}/// Get quote for a single symboldiff --git a/fincept-terminal-desktop/src-tauri/src/commands/bea.rs b/fincept-terminal-desktop/src-tauri/src/commands/bea.rsindex 36bd22f48..39f655540 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/bea.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/bea.rs@@ -1,11 +1,10 @@use tauri::command;-use std::process::Command;// ==================== METADATA COMMANDS ====================#[command]pub async fn bea_get_dataset_list() -> Result<String, String> {- let output = Command::new("python")+ let output = crate::utils::python::python_command().arg("resources/scripts/bea_data.py").arg("dataset_list").output()@@ -22,7 +21,7 @@ pub async fn bea_get_dataset_list() -> Result<String, String> {#[command]pub async fn bea_get_parameter_list(dataset_name: String) -> Result<String, String> {- let output = Command::new("python")+ let output = crate::utils::python::python_command().arg("resources/scripts/bea_data.py").arg("parameter_list").arg(&dataset_name)@@ -40,7 +39,7 @@ pub async fn bea_get_parameter_list(dataset_name: String) -> Result<String, Stri#[command]pub async fn bea_get_parameter_values(dataset_name: String, parameter_name: String) -> Result<String, String> {- let output = Command::new("python")+ let output = crate::utils::python::python_command().arg("resources/scripts/bea_data.py").arg("parameter_values").arg(&dataset_name)@@ -63,7 +62,7 @@ pub async fn bea_get_parameter_values_filtered(parameter_name: String,target_parameter: String) -> Result<String, String> {- let output = Command::new("python")+ let output = crate::utils::python::python_command().arg("resources/scripts/bea_data.py").arg("parameter_values_filtered").arg(&dataset_name)@@ -85,7 +84,7 @@ pub async fn bea_get_parameter_values_filtered(#[command]pub async fn bea_get_nipa_data(table_name: String, frequency: Option<String>, year: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/bea_data.py").arg("nipa").arg(&table_name);@@ -118,7 +117,7 @@ pub async fn bea_get_ni_underlying_detail(frequency: Option<String>,year: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/bea_data.py").arg("ni_underlying").arg(&table_name);@@ -147,7 +146,7 @@ pub async fn bea_get_ni_underlying_detail(#[command]pub async fn bea_get_fixed_assets(table_name: String, year: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/bea_data.py").arg("fixed_assets").arg(&table_name);@@ -180,7 +179,7 @@ pub async fn bea_get_mne_data(nonbank_affiliates_only: Option<String>,get_footnotes: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/bea_data.py").arg("mne").arg(&direction);@@ -240,7 +239,7 @@ pub async fn bea_get_gdp_by_industry(frequency: Option<String>,industry: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/bea_data.py").arg("gdp_by_industry").arg(&table_id);@@ -280,7 +279,7 @@ pub async fn bea_get_international_transactions(frequency: Option<String>,year: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/bea_data.py").arg("international_transactions");@@ -323,7 +322,7 @@ pub async fn bea_get_international_investment_position(frequency: Option<String>,year: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/bea_data.py").arg("international_investment");@@ -359,7 +358,7 @@ pub async fn bea_get_international_investment_position(#[command]pub async fn bea_get_input_output(table_id: String, year: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/bea_data.py").arg("input_output").arg(&table_id);@@ -387,7 +386,7 @@ pub async fn bea_get_underlying_gdp_by_industry(frequency: Option<String>,industry: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/bea_data.py").arg("underlying_gdp_industry").arg(&table_id);@@ -428,7 +427,7 @@ pub async fn bea_get_international_services_trade(area_or_country: Option<String>,year: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/bea_data.py").arg("international_services");@@ -473,7 +472,7 @@ pub async fn bea_get_regional_data(geo_fips: Option<String>,year: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/bea_data.py").arg("regional").arg(&table_name);@@ -510,7 +509,7 @@ pub async fn bea_get_regional_data(#[command]pub async fn bea_get_economic_overview(year: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/bea_data.py").arg("economic_overview");@@ -535,7 +534,7 @@ pub async fn bea_get_regional_snapshot(geo_fips: Option<String>,year: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/bea_data.py").arg("regional_snapshot");diff --git a/fincept-terminal-desktop/src-tauri/src/commands/fred.rs b/fincept-terminal-desktop/src-tauri/src/commands/fred.rsindex 51433fa88..509dd08d0 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/fred.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/fred.rs@@ -1,6 +1,5 @@// FRED (Federal Reserve Economic Data) commands-use std::process::Command;-use crate::utils::python::{get_python_path, get_script_path};+use crate::utils::python::execute_python_command;/// Execute FRED Python script command#[tauri::command]@@ -9,31 +8,12 @@ pub async fn execute_fred_command(command: String,args: Vec<String>,) -> Result<String, String> {- let python_path = get_python_path(&app)?;- let script_path = get_script_path(&app, "fred_data.py")?;-- if !script_path.exists() {- return Err(format!(- "FRED script not found at: {}",- script_path.display()- ));- }-- let mut cmd_args = vec![script_path.to_string_lossy().to_string(), command];+ // Build command arguments+ let mut cmd_args = vec![command];cmd_args.extend(args);- let output = Command::new(&python_path)- .args(&cmd_args)- .output()- .map_err(|e| format!("Failed to execute FRED command: {}", e))?;-- if output.status.success() {- let stdout = String::from_utf8_lossy(&output.stdout);- Ok(stdout.to_string())- } else {- let stderr = String::from_utf8_lossy(&output.stderr);- Err(format!("FRED command failed: {}", stderr))- }+ // Execute Python script with console window hidden on Windows+ execute_python_command(&app, "fred_data.py", &cmd_args)}/// Get FRED series datadiff --git a/fincept-terminal-desktop/src-tauri/src/commands/oscar.rs b/fincept-terminal-desktop/src-tauri/src/commands/oscar.rsindex 22ff93f4f..3406f31b0 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/oscar.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/oscar.rs@@ -1,5 +1,4 @@use tauri::command;-use std::process::Command;// ==================== INSTRUMENTS ENDPOINTS ====================@@ -11,7 +10,7 @@ pub async fn oscar_get_instruments(filter_on: Option<String>,filter_value: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/oscar_data.py").arg("instruments");@@ -57,7 +56,7 @@ pub async fn oscar_get_instruments(#[command]pub async fn oscar_get_instrument_by_slug(slug: String) -> Result<String, String> {- let output = Command::new("python")+ let output = crate::utils::python::python_command().arg("resources/scripts/oscar_data.py").arg("instrument").arg(&slug)@@ -78,7 +77,7 @@ pub async fn oscar_search_instruments_by_type(instrument_type: String,page: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/oscar_data.py").arg("search_instruments_type").arg(&instrument_type);@@ -104,7 +103,7 @@ pub async fn oscar_search_instruments_by_agency(agency: String,page: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/oscar_data.py").arg("search_instruments_agency").arg(&agency);@@ -131,7 +130,7 @@ pub async fn oscar_search_instruments_by_year_range(end_year: i32,page: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/oscar_data.py").arg("search_instruments_year").arg(start_year.to_string())@@ -155,7 +154,7 @@ pub async fn oscar_search_instruments_by_year_range(#[command]pub async fn oscar_get_instrument_classifications() -> Result<String, String> {- let output = Command::new("python")+ let output = crate::utils::python::python_command().arg("resources/scripts/oscar_data.py").arg("instrument_classifications").output()@@ -180,7 +179,7 @@ pub async fn oscar_get_satellites(filter_on: Option<String>,filter_value: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/oscar_data.py").arg("satellites");@@ -226,7 +225,7 @@ pub async fn oscar_get_satellites(#[command]pub async fn oscar_get_satellite_by_slug(slug: String) -> Result<String, String> {- let output = Command::new("python")+ let output = crate::utils::python::python_command().arg("resources/scripts/oscar_data.py").arg("satellite").arg(&slug)@@ -247,7 +246,7 @@ pub async fn oscar_search_satellites_by_orbit(orbit_type: String,page: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/oscar_data.py").arg("search_satellites_orbit").arg(&orbit_type);@@ -273,7 +272,7 @@ pub async fn oscar_search_satellites_by_agency(agency: String,page: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/oscar_data.py").arg("search_satellites_agency").arg(&agency);@@ -304,7 +303,7 @@ pub async fn oscar_get_variables(filter_on: Option<String>,filter_value: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/oscar_data.py").arg("variables");@@ -350,7 +349,7 @@ pub async fn oscar_get_variables(#[command]pub async fn oscar_get_variable_by_slug(slug: String) -> Result<String, String> {- let output = Command::new("python")+ let output = crate::utils::python::python_command().arg("resources/scripts/oscar_data.py").arg("variable").arg(&slug)@@ -371,7 +370,7 @@ pub async fn oscar_search_variables_by_instrument(instrument: String,page: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/oscar_data.py").arg("search_variables_instrument").arg(&instrument);@@ -394,7 +393,7 @@ pub async fn oscar_search_variables_by_instrument(#[command]pub async fn oscar_get_ecv_variables(page: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/oscar_data.py").arg("ecv_variables");@@ -418,7 +417,7 @@ pub async fn oscar_get_ecv_variables(page: Option<i32>) -> Result<String, String#[command]pub async fn oscar_get_space_agencies() -> Result<String, String> {- let output = Command::new("python")+ let output = crate::utils::python::python_command().arg("resources/scripts/oscar_data.py").arg("space_agencies").output()@@ -435,7 +434,7 @@ pub async fn oscar_get_space_agencies() -> Result<String, String> {#[command]pub async fn oscar_get_instrument_types() -> Result<String, String> {- let output = Command::new("python")+ let output = crate::utils::python::python_command().arg("resources/scripts/oscar_data.py").arg("instrument_types").output()@@ -452,7 +451,7 @@ pub async fn oscar_get_instrument_types() -> Result<String, String> {#[command]pub async fn oscar_search_weather_instruments(page: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/oscar_data.py").arg("weather_instruments");@@ -474,7 +473,7 @@ pub async fn oscar_search_weather_instruments(page: Option<i32>) -> Result<Strin#[command]pub async fn oscar_get_climate_monitoring_instruments(page: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/oscar_data.py").arg("climate_instruments");@@ -496,7 +495,7 @@ pub async fn oscar_get_climate_monitoring_instruments(page: Option<i32>) -> Resu#[command]pub async fn oscar_get_overview_statistics() -> Result<String, String> {- let output = Command::new("python")+ let output = crate::utils::python::python_command().arg("resources/scripts/oscar_data.py").arg("overview_statistics").output()diff --git a/fincept-terminal-desktop/src-tauri/src/commands/polygon.rs b/fincept-terminal-desktop/src-tauri/src/commands/polygon.rsindex 05e5b6fc5..3a08a58c6 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/polygon.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/polygon.rs@@ -1,7 +1,6 @@// Polygon.io data commandsuse serde::{Deserialize, Serialize};-use crate::utils::python::{get_python_path, get_script_path};-use std::process::Command;+use crate::utils::python::execute_python_command;#[derive(Debug, Serialize, Deserialize)]pub struct PolygonResponse {@@ -17,33 +16,10 @@ pub async fn execute_polygon_command(command: String,args: Vec<String>,) -> Result<String, String> {- // Get the Python script path - use CARGO_MANIFEST_DIR for correct path resolution- let python_path = get_python_path(&app)?;- let script_path = get_script_path(&app, "polygon_data.py")?;-- // Verify script exists- if !script_path.exists() {- return Err(format!(- "Polygon script not found at: {}",- script_path.display()- ));- }-// Build command arguments- let mut cmd_args = vec![script_path.to_string_lossy().to_string(), command];+ let mut cmd_args = vec![command];cmd_args.extend(args);- // Execute Python script- let output = Command::new(&python_path)- .args(&cmd_args)- .output()- .map_err(|e| format!("Failed to execute command: {}", e))?;-- if output.status.success() {- let stdout = String::from_utf8_lossy(&output.stdout);- Ok(stdout.to_string())- } else {- let stderr = String::from_utf8_lossy(&output.stderr);- Err(format!("Command failed: {}", stderr))- }+ // Execute Python script with console window hidden on Windows+ execute_python_command(&app, "polygon_data.py", &cmd_args)}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/unesco.rs b/fincept-terminal-desktop/src-tauri/src/commands/unesco.rsindex eca919c5f..4f29e5a35 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/unesco.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/unesco.rs@@ -1,5 +1,4 @@use tauri::command;-use std::process::Command;// ==================== DATA ENDPOINTS ====================@@ -14,7 +13,7 @@ pub async fn unesco_get_indicator_data(indicator_metadata: Option<bool>,version: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/unesco_data.py").arg("indicator_data");@@ -86,7 +85,7 @@ pub async fn unesco_export_indicator_data(indicator_metadata: Option<bool>,version: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/unesco_data.py").arg("export_indicator_data").arg(&format_type);@@ -151,7 +150,7 @@ pub async fn unesco_export_indicator_data(#[command]pub async fn unesco_list_geo_units(version: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/unesco_data.py").arg("list_geo_units");@@ -173,7 +172,7 @@ pub async fn unesco_list_geo_units(version: Option<String>) -> Result<String, St#[command]pub async fn unesco_export_geo_units(format_type: String, version: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/unesco_data.py").arg("export_geo_units").arg(&format_type);@@ -200,7 +199,7 @@ pub async fn unesco_list_indicators(disaggregations: Option<bool>,version: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/unesco_data.py").arg("list_indicators");@@ -240,7 +239,7 @@ pub async fn unesco_export_indicators(disaggregations: Option<bool>,version: Option<String>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/unesco_data.py").arg("export_indicators").arg(&format_type);@@ -278,7 +277,7 @@ pub async fn unesco_export_indicators(#[command]pub async fn unesco_get_default_version() -> Result<String, String> {- let output = Command::new("python")+ let output = crate::utils::python::python_command().arg("resources/scripts/unesco_data.py").arg("get_default_version").output()@@ -295,7 +294,7 @@ pub async fn unesco_get_default_version() -> Result<String, String> {#[command]pub async fn unesco_list_versions() -> Result<String, String> {- let output = Command::new("python")+ let output = crate::utils::python::python_command().arg("resources/scripts/unesco_data.py").arg("list_versions").output()@@ -318,7 +317,7 @@ pub async fn unesco_get_education_overview(start_year: Option<i32>,end_year: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/unesco_data.py").arg("education_overview");@@ -356,7 +355,7 @@ pub async fn unesco_get_global_education_trends(start_year: Option<i32>,end_year: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/unesco_data.py").arg("global_trends");@@ -393,7 +392,7 @@ pub async fn unesco_get_country_comparison(start_year: Option<i32>,end_year: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/unesco_data.py").arg("country_comparison").arg(&indicator_code);@@ -429,7 +428,7 @@ pub async fn unesco_search_indicators_by_theme(theme: String,limit: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/unesco_data.py").arg("search_by_theme").arg(&theme);@@ -457,7 +456,7 @@ pub async fn unesco_get_regional_education_data(start_year: Option<i32>,end_year: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/unesco_data.py").arg("regional_data").arg(®ion_id);@@ -496,7 +495,7 @@ pub async fn unesco_get_science_technology_data(start_year: Option<i32>,end_year: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/unesco_data.py").arg("sti_data");@@ -534,7 +533,7 @@ pub async fn unesco_get_culture_data(start_year: Option<i32>,end_year: Option<i32>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/unesco_data.py").arg("culture_data");@@ -572,7 +571,7 @@ pub async fn unesco_export_country_dataset(format_type: String,include_metadata: Option<bool>) -> Result<String, String> {- let mut cmd = Command::new("python");+ let mut cmd = crate::utils::python::python_command();cmd.arg("resources/scripts/unesco_data.py").arg("export_country_dataset").arg(&country_code)diff --git a/fincept-terminal-desktop/src-tauri/src/commands/yfinance.rs b/fincept-terminal-desktop/src-tauri/src/commands/yfinance.rsindex c0a9147a7..56d0909e7 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/yfinance.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/yfinance.rs@@ -1,6 +1,5 @@// Yahoo Finance data commands-use std::process::Command;-use crate::utils::python::{get_python_path, get_script_path};+use crate::utils::python::execute_python_command;/// Execute Yahoo Finance Python script command#[tauri::command]@@ -9,24 +8,10 @@ pub async fn execute_yfinance_command(command: String,args: Vec<String>,) -> Result<String, String> {- let python_path = get_python_path(&app)?;- let script_path = get_script_path(&app, "yfinance_data.py")?;-// Build command arguments- let mut cmd_args = vec![script_path.to_string_lossy().to_string(), command];+ let mut cmd_args = vec![command];cmd_args.extend(args);- // Execute Python script- let output = Command::new(&python_path)- .args(&cmd_args)- .output()- .map_err(|e| format!("Failed to execute command: {}", e))?;-- if output.status.success() {- let stdout = String::from_utf8_lossy(&output.stdout);- Ok(stdout.to_string())- } else {- let stderr = String::from_utf8_lossy(&output.stderr);- Err(format!("Command failed: {}", stderr))- }+ // Execute Python script with console window hidden on Windows+ execute_python_command(&app, "yfinance_data.py", &cmd_args)}diff --git a/fincept-terminal-desktop/src-tauri/src/data_sources/yfinance.rs b/fincept-terminal-desktop/src-tauri/src/data_sources/yfinance.rsindex 9cdb15ed1..c2bd327b4 100644--- a/fincept-terminal-desktop/src-tauri/src/data_sources/yfinance.rs+++ b/fincept-terminal-desktop/src-tauri/src/data_sources/yfinance.rs@@ -6,6 +6,13 @@ use anyhow::{Result, Context};use std::process::Command;use std::path::PathBuf;+// Windows-specific imports to hide console windows+#[cfg(target_os = "windows")]+use std::os::windows::process::CommandExt;++#[cfg(target_os = "windows")]+const CREATE_NO_WINDOW: u32 = 0x08000000;+#[derive(Debug, Clone, Serialize, Deserialize)]pub struct QuoteData {pub symbol: String,@@ -81,6 +88,10 @@ impl YFinanceProvider {cmd.arg(symbol);}+ // Hide console window on Windows+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+let output = cmd.output().context("Failed to execute Python script")?;@@ -99,10 +110,16 @@ impl YFinanceProvider {/// Internal fetch method - calls Python yfinance scriptasync fn fetch_quote(&self, symbol: &str) -> Result<QuoteData> {- let output = Command::new(&self.python_path)- .arg(&self.script_path)+ let mut cmd = Command::new(&self.python_path);+ cmd.arg(&self.script_path).arg("quote")- .arg(symbol)+ .arg(symbol);++ // Hide console window on Windows+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);++ let output = cmd.output().context("Failed to execute Python script")?;@@ -142,12 +159,18 @@ impl YFinanceProvider {start_date: &str,end_date: &str,) -> Result<Vec<HistoricalData>> {- let output = Command::new(&self.python_path)- .arg(&self.script_path)+ let mut cmd = Command::new(&self.python_path);+ cmd.arg(&self.script_path).arg("historical").arg(symbol).arg(start_date)- .arg(end_date)+ .arg(end_date);++ // Hide console window on Windows+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);++ let output = cmd.output().context("Failed to execute Python script")?;@@ -215,10 +238,16 @@ impl YFinanceProvider {/// Internal info fetch method - calls Python yfinance scriptasync fn fetch_info(&self, symbol: &str) -> Result<serde_json::Value> {- let output = Command::new(&self.python_path)- .arg(&self.script_path)+ let mut cmd = Command::new(&self.python_path);+ cmd.arg(&self.script_path).arg("info")- .arg(symbol)+ .arg(symbol);++ // Hide console window on Windows+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);++ let output = cmd.output().context("Failed to execute Python script")?;@@ -244,10 +273,16 @@ impl YFinanceProvider {/// Internal financials fetch method - calls Python yfinance scriptasync fn fetch_financials(&self, symbol: &str) -> Result<serde_json::Value> {- let output = Command::new(&self.python_path)- .arg(&self.script_path)+ let mut cmd = Command::new(&self.python_path);+ cmd.arg(&self.script_path).arg("financials")- .arg(symbol)+ .arg(symbol);++ // Hide console window on Windows+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);++ let output = cmd.output().context("Failed to execute Python script")?;diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rsindex 5b22a19a0..4cccfe320 100644--- a/fincept-terminal-desktop/src-tauri/src/lib.rs+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs@@ -1,9 +1,12 @@// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/use std::collections::HashMap;-use std::process::{Child, Command, Stdio};-use std::sync::Mutex;+use std::process::{Child, Command, Stdio, ChildStdout, ChildStdin};+use std::sync::{Arc, Mutex};use std::io::{BufRead, BufReader, Write};+use std::thread;+use std::time::Duration;+use std::sync::mpsc::{channel, Sender, Receiver};use serde::Serialize;use sha2::{Sha256, Digest};@@ -12,9 +15,16 @@ mod data_sources;mod commands;mod utils;+// MCP Server Process with communication channels+struct MCPProcess {+ child: Child,+ stdin: Arc<Mutex<ChildStdin>>,+ response_rx: Receiver<String>,+}+// Global state to manage MCP server processesstruct MCPState {- processes: Mutex<HashMap<String, Child>>,+ processes: Mutex<HashMap<String, MCPProcess>>,}#[derive(Debug, Serialize)]@@ -29,9 +39,10 @@ fn greet(name: &str) -> String {format!("Hello, {}! You've been greeted from Rust!", name)}-// Spawn an MCP server process+// Spawn an MCP server process with background stdout reader#[tauri::command]fn spawn_mcp_server(+ app: tauri::AppHandle,state: tauri::State<MCPState>,server_id: String,command: String,@@ -40,9 +51,47 @@ fn spawn_mcp_server() -> Result<SpawnResult, String> {println!("[Tauri] Spawning MCP server: {} with command: {} {:?}", server_id, command, args);+ // Determine if we should use bundled Bun (for npx/bunx commands)+ let (fixed_command, fixed_args) = if command == "npx" || command == "bunx" {+ // Try to get bundled Bun path+ match utils::python::get_bundled_bun_path(&app) {+ Ok(bun_path) => {+ println!("[Tauri] Using bundled Bun: {:?}", bun_path);+ // Use 'bun x' which is equivalent to 'bunx' or 'npx'+ let mut new_args = vec!["x".to_string()];+ new_args.extend(args.clone());+ (bun_path.to_string_lossy().to_string(), new_args)+ }+ Err(e) => {+ println!("[Tauri] Bundled Bun not found, falling back to system npx: {}", e);+ // Fall back to system npx+ #[cfg(target_os = "windows")]+ let cmd = "npx.cmd".to_string();+ #[cfg(not(target_os = "windows"))]+ let cmd = "npx".to_string();+ (cmd, args.clone())+ }+ }+ } else {+ // Fix command for Windows - node/python need .exe extension+ #[cfg(target_os = "windows")]+ let cmd = if command == "node" {+ "node.exe".to_string()+ } else if command == "python" {+ "python.exe".to_string()+ } else {+ command.clone()+ };++ #[cfg(not(target_os = "windows"))]+ let cmd = command.clone();++ (cmd, args.clone())+ };+// Build command- let mut cmd = Command::new(&command);- cmd.args(&args)+ let mut cmd = Command::new(&fixed_command);+ cmd.args(&fixed_args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());@@ -52,15 +101,74 @@ fn spawn_mcp_server(cmd.env(key, value);}+ // Hide console window on Windows+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+// Spawn processmatch cmd.spawn() {- Ok(child) => {+ Ok(mut child) => {let pid = child.id();println!("[Tauri] MCP server spawned successfully with PID: {}", pid);- // Store process+ // Extract stdin and stdout+ let stdin = child.stdin.take().ok_or("Failed to get stdin")?;+ let stdout = child.stdout.take().ok_or("Failed to get stdout")?;+ let stderr = child.stderr.take();++ // Create channel for responses+ let (response_tx, response_rx): (Sender<String>, Receiver<String>) = channel();++ // Spawn background thread to read stdout+ let server_id_clone = server_id.clone();+ thread::spawn(move || {+ let reader = BufReader::new(stdout);+ println!("[Tauri] Started stdout reader thread for {}", server_id_clone);++ for line in reader.lines() {+ match line {+ Ok(content) => {+ if !content.trim().is_empty() {+ println!("[Tauri] Received from {}: {}", server_id_clone, content);+ if response_tx.send(content).is_err() {+ eprintln!("[Tauri] Response channel closed for {}", server_id_clone);+ break;+ }+ }+ }+ Err(e) => {+ eprintln!("[Tauri] Error reading stdout for {}: {}", server_id_clone, e);+ break;+ }+ }+ }+ println!("[Tauri] Stdout reader thread exiting for {}", server_id_clone);+ });++ // Spawn background thread to read stderr (for debugging)+ if let Some(stderr) = stderr {+ let server_id_clone = server_id.clone();+ thread::spawn(move || {+ let reader = BufReader::new(stderr);+ for line in reader.lines() {+ if let Ok(content) = line {+ if !content.trim().is_empty() {+ eprintln!("[Tauri] STDERR from {}: {}", server_id_clone, content);+ }+ }+ }+ });+ }++ // Store process with communication channels+ let mcp_process = MCPProcess {+ child,+ stdin: Arc::new(Mutex::new(stdin)),+ response_rx,+ };+let mut processes = state.processes.lock().unwrap();- processes.insert(server_id.clone(), child);+ processes.insert(server_id.clone(), mcp_process);Ok(SpawnResult {pid,@@ -79,7 +187,7 @@ fn spawn_mcp_server(}}-// Send JSON-RPC request to MCP server+// Send JSON-RPC request to MCP server with timeout#[tauri::command]fn send_mcp_request(state: tauri::State<MCPState>,@@ -90,35 +198,35 @@ fn send_mcp_request(let mut processes = state.processes.lock().unwrap();- if let Some(child) = processes.get_mut(&server_id) {- // Get stdin handle- if let Some(ref mut stdin) = child.stdin {- // Write request- if let Err(e) = writeln!(stdin, "{}", request) {- return Err(format!("Failed to write to stdin: {}", e));- }+ if let Some(mcp_process) = processes.get_mut(&server_id) {+ // Write request to stdin+ {+ let mut stdin = mcp_process.stdin.lock().unwrap();+ writeln!(stdin, "{}", request)+ .map_err(|e| format!("Failed to write to stdin: {}", e))?;+ stdin.flush()+ .map_err(|e| format!("Failed to flush stdin: {}", e))?;+ }- if let Err(e) = stdin.flush() {- return Err(format!("Failed to flush stdin: {}", e));- }+ println!("[Tauri] Request sent, waiting for response...");- // Read response from stdout- if let Some(ref mut stdout) = child.stdout {- let reader = BufReader::new(stdout);- if let Some(Ok(line)) = reader.lines().next() {- println!("[Tauri] Received response: {}", line);- return Ok(line);- } else {- return Err("No response from server".to_string());- }- } else {- return Err("No stdout available".to_string());+ // Wait for response with timeout (30 seconds for initial package download)+ match mcp_process.response_rx.recv_timeout(Duration::from_secs(30)) {+ Ok(response) => {+ println!("[Tauri] Received response: {}", response);+ Ok(response)+ }+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {+ eprintln!("[Tauri] Timeout waiting for response from {}", server_id);+ Err("Timeout: No response from server within 30 seconds".to_string())+ }+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {+ eprintln!("[Tauri] Response channel disconnected for {}", server_id);+ Err("Server process has terminated unexpectedly".to_string())}- } else {- return Err("No stdin available".to_string());}} else {- return Err(format!("Server {} not found", server_id));+ Err(format!("Server {} not found", server_id))}}@@ -133,16 +241,13 @@ fn send_mcp_notification(let mut processes = state.processes.lock().unwrap();- if let Some(child) = processes.get_mut(&server_id) {- if let Some(ref mut stdin) = child.stdin {- writeln!(stdin, "{}", notification)- .map_err(|e| format!("Failed to write notification: {}", e))?;- stdin.flush()- .map_err(|e| format!("Failed to flush: {}", e))?;- Ok(())- } else {- Err("No stdin available".to_string())- }+ if let Some(mcp_process) = processes.get_mut(&server_id) {+ let mut stdin = mcp_process.stdin.lock().unwrap();+ writeln!(stdin, "{}", notification)+ .map_err(|e| format!("Failed to write notification: {}", e))?;+ stdin.flush()+ .map_err(|e| format!("Failed to flush: {}", e))?;+ Ok(())} else {Err(format!("Server {} not found", server_id))}@@ -156,9 +261,9 @@ fn ping_mcp_server() -> Result<bool, String> {let mut processes = state.processes.lock().unwrap();- if let Some(child) = processes.get_mut(&server_id) {+ if let Some(mcp_process) = processes.get_mut(&server_id) {// Check if process is still running- match child.try_wait() {+ match mcp_process.child.try_wait() {Ok(Some(_)) => Ok(false), // Process has exitedOk(None) => Ok(true), // Process is still runningErr(_) => Ok(false), // Error checking status@@ -178,8 +283,8 @@ fn kill_mcp_server(let mut processes = state.processes.lock().unwrap();- if let Some(mut child) = processes.remove(&server_id) {- match child.kill() {+ if let Some(mut mcp_process) = processes.remove(&server_id) {+ match mcp_process.child.kill() {Ok(_) => {println!("[Tauri] Server {} killed successfully", server_id);Ok(())@@ -200,6 +305,14 @@ fn sha256_hash(input: String) -> String {format!("{:x}", result)}+// Windows-specific imports to hide console windows+#[cfg(target_os = "windows")]+use std::os::windows::process::CommandExt;++// Windows creation flags to hide console window+#[cfg(target_os = "windows")]+const CREATE_NO_WINDOW: u32 = 0x08000000;+// Execute Python script with arguments and environment variables#[tauri::command]fn execute_python_script(@@ -234,6 +347,10 @@ fn execute_python_script(}}+ // Hide console window on Windows+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+match cmd.output() {Ok(output) => {if output.status.success() {diff --git a/fincept-terminal-desktop/src-tauri/src/utils/python.rs b/fincept-terminal-desktop/src-tauri/src/utils/python.rsindex 966a21f6d..d353a99d3 100644--- a/fincept-terminal-desktop/src-tauri/src/utils/python.rs+++ b/fincept-terminal-desktop/src-tauri/src/utils/python.rs@@ -1,7 +1,16 @@// Utility module for Python execution path resolutionuse std::path::PathBuf;+use std::process::Command;use tauri::Manager;+// Windows-specific imports to hide console windows+#[cfg(target_os = "windows")]+use std::os::windows::process::CommandExt;++// Windows creation flags to hide console window+#[cfg(target_os = "windows")]+const CREATE_NO_WINDOW: u32 = 0x08000000;+/// Get the Python executable path at runtimepub fn get_python_path(app: &tauri::AppHandle) -> Result<PathBuf, String> {let resource_dir = app@@ -21,6 +30,32 @@ pub fn get_python_path(app: &tauri::AppHandle) -> Result<PathBuf, String> {.join(python_exe))}+/// Get the bundled Bun executable path at runtime+pub fn get_bundled_bun_path(app: &tauri::AppHandle) -> Result<PathBuf, String> {+ let resource_dir = app+ .path()+ .resource_dir()+ .map_err(|e| format!("Failed to get resource directory: {}", e))?;++ let bun_exe = if cfg!(target_os = "windows") {+ "bun.exe"+ } else {+ "bun"+ };++ let bun_path = resource_dir+ .join("resources")+ .join("bun")+ .join(bun_exe);++ // Verify Bun exists+ if !bun_path.exists() {+ return Err(format!("Bundled Bun not found at: {}", bun_path.display()));+ }++ Ok(bun_path)+}+/// Get a Python script path at runtimepub fn get_script_path(app: &tauri::AppHandle, script_name: &str) -> Result<PathBuf, String> {let resource_dir = app@@ -33,3 +68,55 @@ pub fn get_script_path(app: &tauri::AppHandle, script_name: &str) -> Result<Path.join("scripts").join(script_name))}++/// Create a Command that hides console windows on Windows+/// Use this instead of Command::new("python") to prevent terminal windows+pub fn python_command() -> Command {+ let mut cmd = Command::new("python");++ // Hide console window on Windows+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);++ cmd+}++/// Execute a Python script with arguments and return the output+/// This function automatically hides console windows on Windows+pub fn execute_python_command(+ app: &tauri::AppHandle,+ script_name: &str,+ args: &[String],+) -> Result<String, String> {+ let python_path = get_python_path(app)?;+ let script_path = get_script_path(app, script_name)?;++ // Verify script exists+ if !script_path.exists() {+ return Err(format!(+ "Script not found at: {}",+ script_path.display()+ ));+ }++ // Build command+ let mut cmd = Command::new(&python_path);+ cmd.arg(&script_path).args(args);++ // Hide console window on Windows+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);++ // Execute and capture output+ let output = cmd+ .output()+ .map_err(|e| format!("Failed to execute command: {}", e))?;++ if output.status.success() {+ let stdout = String::from_utf8_lossy(&output.stdout);+ Ok(stdout.to_string())+ } else {+ let stderr = String::from_utf8_lossy(&output.stderr);+ Err(format!("Command failed: {}", stderr))+ }+}diff --git a/fincept-terminal-desktop/src-tauri/tauri.conf.json b/fincept-terminal-desktop/src-tauri/tauri.conf.jsonindex 5227b00b4..c743b6c50 100644--- a/fincept-terminal-desktop/src-tauri/tauri.conf.json+++ b/fincept-terminal-desktop/src-tauri/tauri.conf.json@@ -45,7 +45,8 @@"longDescription": "FinceptTerminal is an AI-Powered Finance Terminal For Investment Research. Access real-time market data, advanced analytics, and institutional-grade tools for informed investment decisions.","resources": ["resources/scripts",- "resources/python"+ "resources/python",+ "resources/bun"],"externalBin": [],"windows": {diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsxindex de87e5126..b6554f765 100644--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx@@ -20,7 +20,6 @@ import FixedIncomeTab from '@/components/tabs/FixedIncomeTab';import OptionsTab from '@/components/tabs/OptionsTab';import EconomicCalendarTab from '@/components/tabs/EconomicCalendarTab';import ScreenerTab from '@/components/tabs/ScreenerTab';-import AlertsTab from '@/components/tabs/AlertsTab';import DBnomicsTab from '@/components/tabs/DBnomicsTab';import EconomicsTab from '@/components/tabs/EconomicsTab';import CodeEditorTab from '@/components/tabs/CodeEditorTab';@@ -636,12 +635,6 @@ export default function FinxeptTerminal() {>Screener</TabsTrigger>- <TabsTrigger- value="alerts"- style={activeTab === 'alerts' ? tabStyles.active : tabStyles.default}- >- Alerts- </TabsTrigger><TabsTriggervalue="dbnomics"style={activeTab === 'dbnomics' ? tabStyles.active : tabStyles.default}@@ -825,9 +818,6 @@ export default function FinxeptTerminal() {<TabsContent value="screener" className="h-full m-0 p-0"><ScreenerTab /></TabsContent>- <TabsContent value="alerts" className="h-full m-0 p-0">- <AlertsTab />- </TabsContent><TabsContent value="dbnomics" className="h-full m-0 p-0"><DBnomicsTab /></TabsContent>diff --git a/fincept-terminal-desktop/src/components/tabs/AlertsTab.tsx b/fincept-terminal-desktop/src/components/tabs/AlertsTab.tsxdeleted file mode 100644index 94994885d..000000000--- a/fincept-terminal-desktop/src/components/tabs/AlertsTab.tsx+++ /dev/null@@ -1,634 +0,0 @@-import React, { useState, useEffect } from 'react';--interface Alert {- id: string;- type: 'PRICE' | 'VOLUME' | 'INDICATOR' | 'NEWS' | 'EARNING';- symbol: string;- condition: string;- trigger: string;- status: 'ACTIVE' | 'TRIGGERED' | 'EXPIRED' | 'DISABLED';- priority: 'HIGH' | 'MEDIUM' | 'LOW';- created: string;- lastTriggered?: string;- triggerCount: number;-}--interface Notification {- id: string;- time: string;- symbol: string;- type: string;- message: string;- priority: 'HIGH' | 'MEDIUM' | 'LOW';- read: boolean;-}--const AlertsTab: React.FC = () => {- const [currentTime, setCurrentTime] = useState(new Date());- const [selectedType, setSelectedType] = useState('ALL');- const [selectedStatus, setSelectedStatus] = useState('ALL');- const [showCreateModal, setShowCreateModal] = useState(false);-- const COLOR_ORANGE = '#FFA500';- const COLOR_WHITE = '#FFFFFF';- const COLOR_RED = '#FF0000';- const COLOR_GREEN = '#00C800';- const COLOR_YELLOW = '#FFFF00';- const COLOR_GRAY = '#787878';- const COLOR_BLUE = '#6496FA';- const COLOR_PURPLE = '#C864FF';- const COLOR_CYAN = '#00FFFF';- const COLOR_DARK_BG = '#000000';- const COLOR_PANEL_BG = '#0a0a0a';-- useEffect(() => {- const timer = setInterval(() => setCurrentTime(new Date()), 1000);- return () => clearInterval(timer);- }, []);-- const alerts: Alert[] = [- {- id: 'ALT001',- type: 'PRICE',- symbol: 'AAPL',- condition: 'Price Above',- trigger: '$180.00',- status: 'ACTIVE',- priority: 'HIGH',- created: '2025-03-10 09:30',- triggerCount: 0- },- {- id: 'ALT002',- type: 'PRICE',- symbol: 'TSLA',- condition: 'Price Below',- trigger: '$185.00',- status: 'TRIGGERED',- priority: 'HIGH',- created: '2025-03-12 14:20',- lastTriggered: '2025-03-15 11:34',- triggerCount: 3- },- {- id: 'ALT003',- type: 'VOLUME',- symbol: 'NVDA',- condition: 'Volume Above',- trigger: '50M shares',- status: 'ACTIVE',- priority: 'MEDIUM',- created: '2025-03-14 10:15',- triggerCount: 0- },- {- id: 'ALT004',- type: 'INDICATOR',- symbol: 'SPY',- condition: 'RSI Below',- trigger: '30',- status: 'ACTIVE',- priority: 'MEDIUM',- created: '2025-03-13 15:45',- triggerCount: 0- },- {- id: 'ALT005',- type: 'NEWS',- symbol: 'MSFT',- condition: 'News Sentiment',- trigger: 'Negative < -0.5',- status: 'DISABLED',- priority: 'LOW',- created: '2025-03-11 08:00',- triggerCount: 0- },- {- id: 'ALT006',- type: 'EARNING',- symbol: 'GOOGL',- condition: 'Earnings Date',- trigger: '2025-04-23',- status: 'ACTIVE',- priority: 'HIGH',- created: '2025-03-01 12:00',- triggerCount: 0- },- {- id: 'ALT007',- type: 'PRICE',- symbol: 'JPM',- condition: '% Change Above',- trigger: '+5%',- status: 'TRIGGERED',- priority: 'HIGH',- created: '2025-03-08 09:45',- lastTriggered: '2025-03-15 10:23',- triggerCount: 1- },- {- id: 'ALT008',- type: 'INDICATOR',- symbol: 'QQQ',- condition: 'MACD Cross',- trigger: 'Bullish',- status: 'ACTIVE',- priority: 'MEDIUM',- created: '2025-03-09 13:30',- triggerCount: 0- }- ];-- const notifications: Notification[] = [- {- id: 'NOT001',- time: '11:34:23',- symbol: 'TSLA',- type: 'PRICE ALERT',- message: 'TSLA dropped below $185.00 - Current: $183.45',- priority: 'HIGH',- read: false- },- {- id: 'NOT002',- time: '10:23:45',- symbol: 'JPM',- type: 'PRICE ALERT',- message: 'JPM gained +5.2% in last hour - Current: $187.23',- priority: 'HIGH',- read: false- },- {- id: 'NOT003',- time: '09:15:12',- symbol: 'NVDA',- type: 'VOLUME ALERT',- message: 'NVDA volume spike: 52.3M shares traded (above 50M threshold)',- priority: 'MEDIUM',- read: true- },- {- id: 'NOT004',- time: '08:45:33',- symbol: 'AAPL',- type: 'NEWS ALERT',- message: 'Breaking news: AAPL announces new product launch event',- priority: 'HIGH',- read: true- },- {- id: 'NOT005',- time: 'Yesterday',- symbol: 'SPY',- type: 'INDICATOR',- message: 'SPY RSI dropped to 28.4 (oversold territory)',- priority: 'MEDIUM',- read: true- }- ];-- const watchedSymbols = [- { symbol: 'AAPL', price: 178.45, change: 1.33, alerts: 2, status: 'NORMAL' },- { symbol: 'TSLA', price: 183.45, change: -2.34, alerts: 3, status: 'TRIGGERED' },- { symbol: 'NVDA', price: 878.34, change: 1.44, alerts: 1, status: 'NORMAL' },- { symbol: 'MSFT', price: 412.34, change: 1.39, alerts: 1, status: 'DISABLED' },- { symbol: 'GOOGL', price: 145.67, change: -0.84, alerts: 1, status: 'NORMAL' },- { symbol: 'JPM', price: 187.23, change: 5.21, alerts: 2, status: 'TRIGGERED' }- ];-- const filteredAlerts = alerts.filter(a =>- (selectedType === 'ALL' || a.type === selectedType) &&- (selectedStatus === 'ALL' || a.status === selectedStatus)- );-- const getTypeColor = (type: string) => {- switch(type) {- case 'PRICE': return COLOR_GREEN;- case 'VOLUME': return COLOR_BLUE;- case 'INDICATOR': return COLOR_PURPLE;- case 'NEWS': return COLOR_CYAN;- case 'EARNING': return COLOR_YELLOW;- default: return COLOR_WHITE;- }- };-- const getStatusColor = (status: string) => {- switch(status) {- case 'ACTIVE': return COLOR_GREEN;- case 'TRIGGERED': return COLOR_ORANGE;- case 'EXPIRED': return COLOR_GRAY;- case 'DISABLED': return COLOR_RED;- default: return COLOR_WHITE;- }- };-- const getPriorityColor = (priority: string) => {- switch(priority) {- case 'HIGH': return COLOR_RED;- case 'MEDIUM': return COLOR_ORANGE;- case 'LOW': return COLOR_YELLOW;- default: return COLOR_GRAY;- }- };-- return (- <div style={{- height: '100%',- backgroundColor: COLOR_DARK_BG,- color: COLOR_WHITE,- fontFamily: 'Consolas, monospace',- overflow: 'hidden',- display: 'flex',- flexDirection: 'column',- fontSize: '12px'- }}>- {/* Header */}- <div style={{- backgroundColor: COLOR_PANEL_BG,- borderBottom: `2px solid ${COLOR_GRAY}`,- padding: '8px 16px',- flexShrink: 0- }}>- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>- <span style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '16px' }}>- ALERTS & MONITORING- </span>- <span style={{ color: COLOR_GRAY }}>|</span>- <span style={{ color: COLOR_CYAN }}>REAL-TIME NOTIFICATIONS • CUSTOM TRIGGERS</span>- </div>- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>- <button- onClick={() => setShowCreateModal(!showCreateModal)}- style={{- padding: '6px 16px',- backgroundColor: COLOR_GREEN,- border: 'none',- color: COLOR_DARK_BG,- fontSize: '11px',- fontWeight: 'bold',- cursor: 'pointer',- fontFamily: 'Consolas, monospace'- }}>- + CREATE ALERT- </button>- <span style={{ color: COLOR_GRAY, fontSize: '11px' }}>- {currentTime.toLocaleTimeString()}- </span>- </div>- </div>- </div>-- {/* Main Content */}- <div style={{ flex: 1, overflow: 'auto', display: 'flex', gap: '12px', padding: '12px' }}>- {/* Left Panel - Notifications & Watched */}- <div style={{ width: '340px', display: 'flex', flexDirection: 'column', gap: '12px' }}>- {/* Recent Notifications */}- <div style={{- backgroundColor: COLOR_PANEL_BG,- border: `2px solid ${COLOR_GRAY}`,- borderLeft: `6px solid ${COLOR_ORANGE}`,- padding: '12px',- maxHeight: '400px',- overflow: 'auto'- }}>- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>- RECENT NOTIFICATIONS- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>- {notifications.map((notif, index) => (- <div key={index} style={{- padding: '10px',- backgroundColor: notif.read ? 'rgba(255,255,255,0.02)' : 'rgba(255,165,0,0.1)',- border: `1px solid ${notif.read ? COLOR_GRAY : COLOR_ORANGE}`,- borderLeft: `4px solid ${getPriorityColor(notif.priority)}`- }}>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>- <span style={{ color: COLOR_CYAN, fontWeight: 'bold', fontSize: '11px' }}>- {notif.symbol}- </span>- <span style={{ color: COLOR_GRAY, fontSize: '9px' }}>- {notif.time}- </span>- </div>- <div style={{ color: getPriorityColor(notif.priority), fontSize: '9px', fontWeight: 'bold', marginBottom: '4px' }}>- {notif.type}- </div>- <div style={{ color: COLOR_WHITE, fontSize: '10px', lineHeight: '1.4' }}>- {notif.message}- </div>- </div>- ))}- </div>- </div>-- {/* Watched Symbols */}- <div style={{- backgroundColor: COLOR_PANEL_BG,- border: `2px solid ${COLOR_GRAY}`,- borderLeft: `6px solid ${COLOR_CYAN}`,- padding: '12px'- }}>- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>- WATCHED SYMBOLS- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>- {watchedSymbols.map((watch, index) => (- <div key={index} style={{- padding: '10px',- backgroundColor: watch.status === 'TRIGGERED' ? 'rgba(255,165,0,0.1)' : 'rgba(255,255,255,0.02)',- border: `1px solid ${watch.status === 'TRIGGERED' ? COLOR_ORANGE : COLOR_GRAY}`,- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center'- }}>- <div>- <div style={{ color: COLOR_CYAN, fontWeight: 'bold', fontSize: '12px', marginBottom: '2px' }}>- {watch.symbol}- </div>- <div style={{ color: watch.change > 0 ? COLOR_GREEN : COLOR_RED, fontSize: '10px' }}>- ${watch.price.toFixed(2)} ({watch.change > 0 ? '+' : ''}{watch.change.toFixed(2)}%)- </div>- </div>- <div style={{ textAlign: 'right' }}>- <div style={{- color: getStatusColor(watch.status),- fontSize: '9px',- fontWeight: 'bold',- marginBottom: '4px'- }}>- {watch.status}- </div>- <div style={{ color: COLOR_GRAY, fontSize: '9px' }}>- {watch.alerts} alert{watch.alerts !== 1 ? 's' : ''}- </div>- </div>- </div>- ))}- </div>- </div>-- {/* Alert Statistics */}- <div style={{- backgroundColor: COLOR_PANEL_BG,- border: `2px solid ${COLOR_GRAY}`,- borderLeft: `6px solid ${COLOR_PURPLE}`,- padding: '12px'- }}>- <div style={{ color: COLOR_ORANGE, fontSize: '13px', fontWeight: 'bold', marginBottom: '12px' }}>- ALERT STATISTICS- </div>- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>- <div style={{- padding: '10px',- backgroundColor: 'rgba(0,200,0,0.05)',- border: `1px solid ${COLOR_GREEN}`,- textAlign: 'center'- }}>- <div style={{ color: COLOR_GRAY, fontSize: '9px', marginBottom: '4px' }}>ACTIVE</div>- <div style={{ color: COLOR_GREEN, fontSize: '20px', fontWeight: 'bold' }}>5</div>- </div>- <div style={{- padding: '10px',- backgroundColor: 'rgba(255,165,0,0.05)',- border: `1px solid ${COLOR_ORANGE}`,- textAlign: 'center'- }}>- <div style={{ color: COLOR_GRAY, fontSize: '9px', marginBottom: '4px' }}>TRIGGERED</div>- <div style={{ color: COLOR_ORANGE, fontSize: '20px', fontWeight: 'bold' }}>2</div>- </div>- <div style={{- padding: '10px',- backgroundColor: 'rgba(255,0,0,0.05)',- border: `1px solid ${COLOR_RED}`,- textAlign: 'center'- }}>- <div style={{ color: COLOR_GRAY, fontSize: '9px', marginBottom: '4px' }}>DISABLED</div>- <div style={{ color: COLOR_RED, fontSize: '20px', fontWeight: 'bold' }}>1</div>- </div>- <div style={{- padding: '10px',- backgroundColor: 'rgba(120,120,120,0.05)',- border: `1px solid ${COLOR_GRAY}`,- textAlign: 'center'- }}>- <div style={{ color: COLOR_GRAY, fontSize: '9px', marginBottom: '4px' }}>TOTAL</div>- <div style={{ color: COLOR_CYAN, fontSize: '20px', fontWeight: 'bold' }}>8</div>- </div>- </div>- </div>- </div>-- {/* Right Panel - Alerts List */}- <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>- {/* Filters */}- <div style={{- backgroundColor: COLOR_PANEL_BG,- border: `2px solid ${COLOR_GRAY}`,- padding: '12px',- marginBottom: '12px'- }}>- <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>- <span style={{ color: COLOR_GRAY, fontSize: '11px' }}>TYPE:</span>- {['ALL', 'PRICE', 'VOLUME', 'INDICATOR', 'NEWS', 'EARNING'].map((type) => (- <button key={type}- onClick={() => setSelectedType(type)}- style={{- padding: '6px 12px',- backgroundColor: selectedType === type ? getTypeColor(type) : COLOR_DARK_BG,- border: `2px solid ${selectedType === type ? getTypeColor(type) : COLOR_GRAY}`,- color: selectedType === type ? COLOR_DARK_BG : COLOR_WHITE,- fontSize: '10px',- fontWeight: 'bold',- cursor: 'pointer',- fontFamily: 'Consolas, monospace'- }}>- {type}- </button>- ))}- <span style={{ color: COLOR_GRAY, marginLeft: '16px' }}>|</span>- <span style={{ color: COLOR_GRAY, fontSize: '11px' }}>STATUS:</span>- {['ALL', 'ACTIVE', 'TRIGGERED', 'DISABLED'].map((status) => (- <button key={status}- onClick={() => setSelectedStatus(status)}- style={{- padding: '6px 12px',- backgroundColor: selectedStatus === status ? getStatusColor(status) : COLOR_DARK_BG,- border: `2px solid ${selectedStatus === status ? getStatusColor(status) : COLOR_GRAY}`,- color: selectedStatus === status ? COLOR_DARK_BG : COLOR_WHITE,- fontSize: '10px',- fontWeight: 'bold',- cursor: 'pointer',- fontFamily: 'Consolas, monospace'- }}>- {status}- </button>- ))}- </div>- </div>-- {/* Alerts Table */}- <div style={{- backgroundColor: COLOR_PANEL_BG,- border: `2px solid ${COLOR_GRAY}`,- flex: 1,- overflow: 'auto'- }}>- {/* Table Header */}- <div style={{- display: 'grid',- gridTemplateColumns: '80px 80px 80px 200px 120px 100px 80px 140px 80px 80px',- padding: '10px 12px',- backgroundColor: 'rgba(255,165,0,0.1)',- borderBottom: `2px solid ${COLOR_ORANGE}`,- position: 'sticky',- top: 0,- zIndex: 10,- fontSize: '10px'- }}>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>ID</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>TYPE</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>SYMBOL</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>CONDITION</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>TRIGGER</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>STATUS</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>PRIORITY</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>CREATED</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>TRIGGERS</div>- <div style={{ color: COLOR_ORANGE, fontWeight: 'bold' }}>ACTIONS</div>- </div>-- {/* Table Body */}- {filteredAlerts.map((alert, index) => (- <div key={index}- style={{- display: 'grid',- gridTemplateColumns: '80px 80px 80px 200px 120px 100px 80px 140px 80px 80px',- padding: '12px',- backgroundColor: alert.status === 'TRIGGERED' ? 'rgba(255,165,0,0.05)' : (index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent'),- borderBottom: `1px solid ${COLOR_GRAY}`,- borderLeft: `4px solid ${getPriorityColor(alert.priority)}`,- cursor: 'pointer',- fontSize: '11px'- }}- onMouseEnter={(e) => {- e.currentTarget.style.backgroundColor = 'rgba(255,165,0,0.1)';- }}- onMouseLeave={(e) => {- e.currentTarget.style.backgroundColor = alert.status === 'TRIGGERED' ? 'rgba(255,165,0,0.05)' : (index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent');- }}>- <div style={{ color: COLOR_GRAY }}>{alert.id}</div>- <div>- <span style={{- padding: '4px 6px',- backgroundColor: `rgba(${alert.type === 'PRICE' ? '0,200,0' : alert.type === 'VOLUME' ? '100,150,250' : alert.type === 'INDICATOR' ? '200,100,255' : alert.type === 'NEWS' ? '0,255,255' : '255,255,0'},0.2)`,- border: `1px solid ${getTypeColor(alert.type)}`,- color: getTypeColor(alert.type),- fontSize: '9px',- fontWeight: 'bold'- }}>- {alert.type}- </span>- </div>- <div style={{ color: COLOR_CYAN, fontWeight: 'bold' }}>{alert.symbol}</div>- <div style={{ color: COLOR_WHITE }}>{alert.condition}</div>- <div style={{ color: COLOR_YELLOW, fontWeight: 'bold' }}>{alert.trigger}</div>- <div>- <span style={{- padding: '4px 8px',- backgroundColor: `rgba(${alert.status === 'ACTIVE' ? '0,200,0' : alert.status === 'TRIGGERED' ? '255,165,0' : alert.status === 'DISABLED' ? '255,0,0' : '120,120,120'},0.2)`,- border: `1px solid ${getStatusColor(alert.status)}`,- color: getStatusColor(alert.status),- fontSize: '9px',- fontWeight: 'bold'- }}>- {alert.status}- </span>- </div>- <div style={{ color: getPriorityColor(alert.priority), fontWeight: 'bold' }}>- {alert.priority}- </div>- <div style={{ color: COLOR_GRAY, fontSize: '10px' }}>{alert.created}</div>- <div style={{ color: alert.triggerCount > 0 ? COLOR_ORANGE : COLOR_GRAY }}>- {alert.triggerCount}x- </div>- <div style={{ display: 'flex', gap: '4px' }}>- <button style={{- padding: '4px 8px',- backgroundColor: COLOR_BLUE,- border: 'none',- color: COLOR_DARK_BG,- fontSize: '9px',- fontWeight: 'bold',- cursor: 'pointer',- fontFamily: 'Consolas, monospace'- }}>- EDIT- </button>- <button style={{- padding: '4px 8px',- backgroundColor: COLOR_RED,- border: 'none',- color: COLOR_DARK_BG,- fontSize: '9px',- fontWeight: 'bold',- cursor: 'pointer',- fontFamily: 'Consolas, monospace'- }}>- DEL- </button>- </div>- </div>- ))}- </div>- </div>- </div>-- {/* Footer */}- <div style={{- borderTop: `3px solid ${COLOR_ORANGE}`,- backgroundColor: COLOR_PANEL_BG,- padding: '12px 16px',- fontSize: '11px',- color: COLOR_WHITE,- flexShrink: 0- }}>- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>- <span style={{ color: COLOR_ORANGE, fontWeight: 'bold', fontSize: '13px' }}>- ALERTS & MONITORING v1.0- </span>- <span style={{ color: COLOR_GRAY }}>|</span>- <span style={{ color: COLOR_CYAN }}>- Real-time market alerts & notifications- </span>- <span style={{ color: COLOR_GRAY }}>|</span>- <span style={{ color: COLOR_GREEN }}>- {filteredAlerts.length} alerts shown- </span>- </div>- </div>- <div style={{- display: 'flex',- justifyContent: 'space-between',- fontSize: '10px',- paddingTop: '8px',- borderTop: `1px solid ${COLOR_GRAY}`- }}>- <div style={{ display: 'flex', gap: '16px' }}>- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F1</span> Help</span>- <span style={{ color: COLOR_GRAY }}>|</span>- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F2</span> Create Alert</span>- <span style={{ color: COLOR_GRAY }}>|</span>- <span style={{ color: COLOR_GRAY }}><span style={{ color: COLOR_BLUE }}>F3</span> Test Alert</span>- </div>- <div style={{ color: COLOR_GRAY }}>- © 2025 Fincept Labs • All Rights Reserved- </div>- </div>- </div>- </div>- );-};--export default AlertsTab;\ No newline at end of filediff --git a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx b/fincept-terminal-desktop/src/components/tabs/ChatTab.tsxindex c34399ab6..1d94f0616 100644--- a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx@@ -318,14 +318,14 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {content: msg.content}));- // Get MCP tools if available+ // Get MCP tools if available using the unified servicelet mcpTools: any[] = [];try {- const { mcpManager } = await import('../../services/mcpManager');- mcpTools = await mcpManager.getAllTools();+ const { mcpToolService } = await import('../../services/mcpToolService');+ mcpTools = await mcpToolService.getAllTools();console.log(`[Chat] Found ${mcpTools.length} MCP tools`);} catch (error) {- console.log('[Chat] No MCP tools available');+ console.log('[Chat] No MCP tools available:', error);}// Call LLM API with tools if availablediff --git a/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx b/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsxindex 9daee1760..205da0e9f 100644--- a/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx@@ -1,4 +1,4 @@-import React, { useState, useCallback, useMemo } from 'react';+import React, { useState, useCallback, useMemo, useEffect } from 'react';import ReactFlow, {Node,Edge,@@ -31,6 +31,8 @@ import {Edit3,X} from 'lucide-react';+import MCPToolNode from './node-editor/MCPToolNode';+import { generateMCPNodeConfigs, MCPNodeConfig } from './node-editor/mcpNodeConfigs';// Custom Node Componentconst CustomNode = ({ data, id, selected }: any) => {@@ -249,6 +251,22 @@ const NODE_CONFIGS = [];export default function NodeEditorTab() {+ const [mcpNodeConfigs, setMcpNodeConfigs] = useState<MCPNodeConfig[]>([]);++ // Load MCP node configurations on mount+ useEffect(() => {+ const loadMCPNodes = async () => {+ try {+ const configs = await generateMCPNodeConfigs();+ setMcpNodeConfigs(configs);+ console.log('[NodeEditor] Loaded MCP node configs:', configs.length);+ } catch (error) {+ console.error('[NodeEditor] Failed to load MCP configs:', error);+ }+ };+ loadMCPNodes();+ }, []);+const [nodes, setNodes, onNodesChange] = useNodesState([{id: '1',@@ -355,7 +373,10 @@ export default function NodeEditorTab() {const [selectedNodes, setSelectedNodes] = useState<string[]>([]);const [showNodeMenu, setShowNodeMenu] = useState(false);- const nodeTypes: NodeTypes = useMemo(() => ({ custom: CustomNode }), []);+ const nodeTypes: NodeTypes = useMemo(() => ({+ custom: CustomNode,+ 'mcp-tool': MCPToolNode+ }), []);// Handle label changefunction handleLabelChange(nodeId: string, newLabel: string) {@@ -389,13 +410,26 @@ export default function NodeEditorTab() {[setEdges]);- // Add new node+ // Add new node (handles both regular nodes and MCP tool nodes)const addNode = (config: any) => {+ const isMCPNode = config.type === 'mcp-tool';+const newNode: Node = {id: `node_${Date.now()}`,- type: 'custom',+ type: isMCPNode ? 'mcp-tool' : 'custom',position: { x: Math.random() * 400 + 100, y: Math.random() * 300 + 100 },- data: {+ data: isMCPNode ? {+ serverId: config.serverId,+ toolName: config.toolName,+ label: config.label,+ parameters: {},+ onParameterChange: (params: Record<string, any>) => {+ console.log('[NodeEditor] MCP tool parameters changed:', params);+ },+ onExecute: (result: any) => {+ console.log('[NodeEditor] MCP tool executed with result:', result);+ },+ } : {label: config.label,nodeType: config.type,color: config.color,@@ -783,6 +817,60 @@ export default function NodeEditorTab() {))}</div>))}++ {/* MCP Tools Section */}+ {mcpNodeConfigs.length > 0 && (+ <div style={{ marginBottom: '12px' }}>+ <div+ style={{+ color: '#FFA500',+ fontSize: '10px',+ marginBottom: '6px',+ textTransform: 'uppercase',+ letterSpacing: '0.5px',+ fontWeight: 'bold',+ }}+ >+ ⚡ MCP TOOLS ({mcpNodeConfigs.length})+ </div>+ {mcpNodeConfigs.map((config) => (+ <button+ key={config.id}+ onClick={() => addNode(config)}+ style={{+ backgroundColor: '#0a0a0a',+ color: '#FFA500',+ border: '1px solid #FFA50040',+ padding: '8px 12px',+ fontSize: '11px',+ cursor: 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ width: '100%',+ marginBottom: '6px',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = '#FFA50020';+ e.currentTarget.style.borderColor = '#FFA500';+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = '#0a0a0a';+ e.currentTarget.style.borderColor = '#FFA50040';+ }}+ >+ <span style={{ fontSize: '14px' }}>{config.icon}</span>+ <div style={{ flex: 1, textAlign: 'left' }}>+ <div>{config.label}</div>+ <div style={{ fontSize: '9px', color: '#787878' }}>+ {config.serverId}+ </div>+ </div>+ </button>+ ))}+ </div>+ )}</div>)}diff --git a/fincept-terminal-desktop/src/components/tabs/WatchlistTab.tsx b/fincept-terminal-desktop/src/components/tabs/WatchlistTab.tsxindex 90278b023..aca7eafc9 100644--- a/fincept-terminal-desktop/src/components/tabs/WatchlistTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/WatchlistTab.tsx@@ -1,43 +1,59 @@import React, { useState, useEffect } from 'react';--interface WatchlistStock {- ticker: string;- name: string;- price: number;- change: number;- changePercent: number;- volume: number;- high: number;- low: number;- open: number;- prevClose: number;- marketCap: string;- pe: number;- yield: number;- week52High: number;- week52Low: number;- avgVolume: string;-}+import { RefreshCw, Download } from 'lucide-react';+import {+ watchlistService,+ Watchlist,+ WatchlistStockWithQuote+} from '../../services/watchlistService';+import WatchlistSidebar from './watchlist/WatchlistSidebar';+import StockListView from './watchlist/StockListView';+import StockDetailPanel from './watchlist/StockDetailPanel';+import CreateWatchlistModal from './watchlist/CreateWatchlistModal';+import AddStockModal from './watchlist/AddStockModal';+import { BLOOMBERG_COLORS, SortCriteria, sortStocks, getNextWatchlistColor } from './watchlist/utils';const WatchlistTab: React.FC = () => {const [currentTime, setCurrentTime] = useState(new Date());- const [selectedList, setSelectedList] = useState('PRIMARY');- const [sortBy, setSortBy] = useState('CHANGE');- const [viewMode, setViewMode] = useState('DETAILED');-- // Bloomberg color scheme- const BLOOMBERG_ORANGE = '#FFA500';- const BLOOMBERG_WHITE = '#FFFFFF';- const BLOOMBERG_RED = '#FF0000';- const BLOOMBERG_GREEN = '#00C800';- const BLOOMBERG_YELLOW = '#FFFF00';- const BLOOMBERG_GRAY = '#787878';- const BLOOMBERG_BLUE = '#6496FA';- const BLOOMBERG_PURPLE = '#C864FF';- const BLOOMBERG_CYAN = '#00FFFF';- const BLOOMBERG_DARK_BG = '#000000';- const BLOOMBERG_PANEL_BG = '#0a0a0a';+ const [watchlists, setWatchlists] = useState<Array<Watchlist & { stock_count: number }>>([]);+ const [selectedWatchlist, setSelectedWatchlist] = useState<(Watchlist & { stock_count: number }) | null>(null);+ const [stocks, setStocks] = useState<WatchlistStockWithQuote[]>([]);+ const [selectedStock, setSelectedStock] = useState<WatchlistStockWithQuote | null>(null);+ const [loading, setLoading] = useState(false);+ const [refreshing, setRefreshing] = useState(false);++ // Sort and view states+ const [sortBy, setSortBy] = useState<SortCriteria>('CHANGE');++ // Modal states+ const [showCreateWatchlist, setShowCreateWatchlist] = useState(false);+ const [showAddStock, setShowAddStock] = useState(false);++ // Market data+ const [marketMovers, setMarketMovers] = useState<{+ gainers: WatchlistStockWithQuote[];+ losers: WatchlistStockWithQuote[];+ } | null>(null);+ const [volumeLeaders, setVolumeLeaders] = useState<WatchlistStockWithQuote[]>([]);+ const { ORANGE, WHITE, RED, GREEN, GRAY, DARK_BG, PANEL_BG, CYAN, YELLOW } = BLOOMBERG_COLORS;++ // Initialize service and load watchlists+ useEffect(() => {+ const initService = async () => {+ setLoading(true);+ try {+ await watchlistService.initialize();+ await loadWatchlists();+ } catch (error) {+ console.error('[WatchlistTab] Initialization error:', error);+ } finally {+ setLoading(false);+ }+ };+ initService();+ }, []);++ // Update timeuseEffect(() => {const timer = setInterval(() => {setCurrentTime(new Date());@@ -45,628 +61,412 @@ const WatchlistTab: React.FC = () => {return () => clearInterval(timer);}, []);- const watchlistStocks: WatchlistStock[] = [- {- ticker: 'AAPL',- name: 'Apple Inc.',- price: 184.92,- change: 1.87,- changePercent: 1.02,- volume: 48234567,- high: 186.45,- low: 182.30,- open: 183.50,- prevClose: 183.05,- marketCap: '2.87T',- pe: 29.8,- yield: 0.52,- week52High: 198.23,- week52Low: 164.08,- avgVolume: '52.3M'- },- {- ticker: 'MSFT',- name: 'Microsoft Corporation',- price: 378.45,- change: 3.82,- changePercent: 1.02,- volume: 23456789,- high: 380.12,- low: 374.56,- open: 375.20,- prevClose: 374.63,- marketCap: '2.81T',- pe: 35.2,- yield: 0.78,- week52High: 398.45,- week52Low: 309.45,- avgVolume: '26.8M'- },- {- ticker: 'NVDA',- name: 'NVIDIA Corporation',- price: 501.23,- change: 5.12,- changePercent: 1.03,- volume: 35678901,- high: 505.67,- low: 495.34,- open: 497.80,- prevClose: 496.11,- marketCap: '1.24T',- pe: 67.2,- yield: 0.03,- week52High: 502.66,- week52Low: 108.13,- avgVolume: '41.2M'- },- {- ticker: 'GOOGL',- name: 'Alphabet Inc.',- price: 134.56,- change: -1.23,- changePercent: -0.91,- volume: 28901234,- high: 136.78,- low: 133.45,- open: 135.90,- prevClose: 135.79,- marketCap: '1.68T',- pe: 25.4,- yield: 0.00,- week52High: 153.78,- week52Low: 83.34,- avgVolume: '31.5M'- },- {- ticker: 'TSLA',- name: 'Tesla Inc.',- price: 251.78,- change: -2.54,- changePercent: -1.00,- volume: 89012345,- high: 256.45,- low: 249.12,- open: 254.30,- prevClose: 254.32,- marketCap: '798.4B',- pe: 68.4,- yield: 0.00,- week52High: 299.29,- week52Low: 101.81,- avgVolume: '112.5M'- },- {- ticker: 'AMZN',- name: 'Amazon.com Inc.',- price: 151.94,- change: 1.45,- changePercent: 0.96,- volume: 45678901,- high: 153.23,- low: 150.12,- open: 150.50,- prevClose: 150.49,- marketCap: '1.57T',- pe: 58.9,- yield: 0.00,- week52High: 161.72,- week52Low: 81.43,- avgVolume: '51.8M'- },- {- ticker: 'META',- name: 'Meta Platforms Inc.',- price: 389.67,- change: 3.21,- changePercent: 0.83,- volume: 18234567,- high: 392.45,- low: 385.34,- open: 386.50,- prevClose: 386.46,- marketCap: '987.3B',- pe: 28.7,- yield: 0.44,- week52High: 401.82,- week52Low: 88.09,- avgVolume: '21.3M'- },- {- ticker: 'BRK.B',- name: 'Berkshire Hathaway Inc.',- price: 389.45,- change: 0.87,- changePercent: 0.22,- volume: 3456789,- high: 391.23,- low: 387.89,- open: 388.60,- prevClose: 388.58,- marketCap: '854.2B',- pe: 21.3,- yield: 0.00,- week52High: 404.52,- week52Low: 298.45,- avgVolume: '4.2M'+ // Auto-refresh data+ useEffect(() => {+ if (selectedWatchlist) {+ const refreshTimer = setInterval(() => {+ refreshWatchlistData();+ }, 60000); // Refresh every minute+ return () => clearInterval(refreshTimer);+ }+ }, [selectedWatchlist]);++ // Load watchlists+ const loadWatchlists = async () => {+ try {+ const result = await watchlistService.getWatchlistsWithCounts();+ setWatchlists(result);++ // Select first watchlist if none selected+ if (result.length > 0 && !selectedWatchlist) {+ setSelectedWatchlist(result[0]);+ }+ } catch (error) {+ console.error('[WatchlistTab] Error loading watchlists:', error);+ }+ };++ // Load watchlist stocks+ const loadWatchlistStocks = async (watchlistId: string) => {+ try {+ setRefreshing(true);+ const stocksData = await watchlistService.getWatchlistStocksWithQuotes(watchlistId);+ setStocks(stocksData);++ // Update selected stock if it exists+ if (selectedStock) {+ const updated = stocksData.find(s => s.symbol === selectedStock.symbol);+ if (updated) {+ setSelectedStock(updated);+ }+ }+ } catch (error) {+ console.error('[WatchlistTab] Error loading stocks:', error);+ } finally {+ setRefreshing(false);+ }+ };++ // Load market movers and volume leaders+ const loadMarketData = async () => {+ try {+ const [movers, leaders] = await Promise.all([+ watchlistService.getMarketMovers(5),+ watchlistService.getVolumeLeaders(5)+ ]);+ setMarketMovers(movers);+ setVolumeLeaders(leaders);+ } catch (error) {+ console.error('[WatchlistTab] Error loading market data:', error);+ }+ };++ // Refresh watchlist data+ const refreshWatchlistData = () => {+ if (selectedWatchlist) {+ loadWatchlistStocks(selectedWatchlist.id);+ loadMarketData();+ }+ };++ // Handle watchlist selection+ useEffect(() => {+ if (selectedWatchlist) {+ loadWatchlistStocks(selectedWatchlist.id);+ loadMarketData();+ }+ }, [selectedWatchlist]);++ // Create new watchlist+ const handleCreateWatchlist = async (name: string, description: string, color: string) => {+ try {+ const newWatchlist = await watchlistService.createWatchlist(name, description, color);+ await loadWatchlists();++ // Find and select the newly created watchlist+ const updated = await watchlistService.getWatchlistsWithCounts();+ const created = updated.find(w => w.id === newWatchlist.id);+ if (created) {+ setSelectedWatchlist(created);+ }+ } catch (error) {+ console.error('[WatchlistTab] Error creating watchlist:', error);+ throw error;}- ];-- const watchlistGroups = [- { name: 'PRIMARY', count: 8, color: BLOOMBERG_ORANGE },- { name: 'TECH', count: 12, color: BLOOMBERG_BLUE },- { name: 'ENERGY', count: 6, color: BLOOMBERG_GREEN },- { name: 'FINANCE', count: 9, color: BLOOMBERG_CYAN },- { name: 'HEALTHCARE', count: 7, color: BLOOMBERG_PURPLE }- ];-- const marketStats = {- gainers: 234,- losers: 156,- unchanged: 45,- highVolume: 89,- allTimeHigh: 12,- allTimeLow: 8};+ // Delete watchlist+ const handleDeleteWatchlist = async (watchlistId: string) => {+ if (!confirm('Are you sure you want to delete this watchlist? This action cannot be undone.')) {+ return;+ }++ try {+ await watchlistService.deleteWatchlist(watchlistId);+ await loadWatchlists();++ if (selectedWatchlist?.id === watchlistId) {+ setSelectedWatchlist(watchlists.length > 1 ? watchlists[0] : null);+ setStocks([]);+ setSelectedStock(null);+ }+ } catch (error) {+ console.error('[WatchlistTab] Error deleting watchlist:', error);+ alert('Failed to delete watchlist');+ }+ };++ // Add stock to watchlist+ const handleAddStock = async (symbol: string, notes: string) => {+ if (!selectedWatchlist) return;++ try {+ await watchlistService.addStock(selectedWatchlist.id, symbol, notes);+ await loadWatchlistStocks(selectedWatchlist.id);+ await loadWatchlists(); // Update counts+ } catch (error) {+ console.error('[WatchlistTab] Error adding stock:', error);+ throw error;+ }+ };++ // Remove stock from watchlist+ const handleRemoveStock = async (symbol: string) => {+ if (!selectedWatchlist) return;++ try {+ await watchlistService.removeStock(selectedWatchlist.id, symbol);+ await loadWatchlistStocks(selectedWatchlist.id);+ await loadWatchlists(); // Update counts++ if (selectedStock?.symbol === symbol) {+ setSelectedStock(null);+ }+ } catch (error) {+ console.error('[WatchlistTab] Error removing stock:', error);+ alert('Failed to remove stock');+ }+ };++ // Export watchlist to CSV+ const handleExportCSV = async () => {+ if (!selectedWatchlist) return;++ try {+ const csv = await watchlistService.exportWatchlistCSV(selectedWatchlist.id);+ const blob = new Blob([csv], { type: 'text/csv' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = `${selectedWatchlist.name.replace(/\s+/g, '_')}_${new Date().toISOString().split('T')[0]}.csv`;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(url);+ } catch (error) {+ console.error('[WatchlistTab] Error exporting CSV:', error);+ alert('Failed to export CSV');+ }+ };++ // Get sorted stocks+ const sortedStocks = sortStocks(stocks, sortBy);+return (<div style={{height: '100%',- backgroundColor: BLOOMBERG_DARK_BG,- color: BLOOMBERG_WHITE,+ backgroundColor: DARK_BG,+ color: WHITE,fontFamily: 'Consolas, monospace',overflow: 'hidden',display: 'flex',- flexDirection: 'column',- fontSize: '12px'+ flexDirection: 'column'}}>- {/* Header */}+ <style>{`+ *::-webkit-scrollbar { width: 8px; height: 8px; }+ *::-webkit-scrollbar-track { background: #1a1a1a; }+ *::-webkit-scrollbar-thumb { background: #404040; border-radius: 4px; }+ *::-webkit-scrollbar-thumb:hover { background: #525252; }+ `}</style>++ {/* Header Bar */}<div style={{- backgroundColor: BLOOMBERG_PANEL_BG,- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,- padding: '4px 8px',+ backgroundColor: PANEL_BG,+ borderBottom: `1px solid ${GRAY}`,+ padding: '8px 12px',flexShrink: 0}}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', marginBottom: '2px' }}>- <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>FINCEPT WATCHLIST MONITOR</span>- <span style={{ color: BLOOMBERG_WHITE }}>|</span>- <span style={{ color: BLOOMBERG_GREEN }}>● LIVE QUOTES</span>- <span style={{ color: BLOOMBERG_WHITE }}>|</span>- <span style={{ color: BLOOMBERG_CYAN }}>STOCKS TRACKED: {watchlistStocks.length}</span>- <span style={{ color: BLOOMBERG_WHITE }}>|</span>- <span style={{ color: BLOOMBERG_YELLOW }}>LISTS: {watchlistGroups.length}</span>- <span style={{ color: BLOOMBERG_WHITE }}>|</span>- <span style={{ color: BLOOMBERG_WHITE }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span>- </div>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <span style={{ color: ORANGE, fontWeight: 'bold', fontSize: '14px' }}>+ FINCEPT WATCHLIST MONITOR+ </span>+ <span style={{ color: WHITE }}>|</span>+ <span style={{ color: refreshing ? ORANGE : GREEN, fontSize: '10px' }}>+ ● {refreshing ? 'UPDATING' : 'LIVE'}+ </span>+ <span style={{ color: WHITE }}>|</span>+ <span style={{ color: CYAN, fontSize: '11px' }}>+ {currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC+ </span>+ </div>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px' }}>- <span style={{ color: BLOOMBERG_GRAY }}>MARKET:</span>- <span style={{ color: BLOOMBERG_GREEN }}>GAINERS {marketStats.gainers}</span>- <span style={{ color: BLOOMBERG_RED }}>LOSERS {marketStats.losers}</span>- <span style={{ color: BLOOMBERG_YELLOW }}>UNCHANGED {marketStats.unchanged}</span>- <span style={{ color: BLOOMBERG_WHITE }}>|</span>- <span style={{ color: BLOOMBERG_GRAY }}>ALERTS:</span>- <span style={{ color: BLOOMBERG_CYAN }}>HIGH VOL {marketStats.highVolume}</span>- <span style={{ color: BLOOMBERG_GREEN }}>52W HIGH {marketStats.allTimeHigh}</span>- <span style={{ color: BLOOMBERG_RED }}>52W LOW {marketStats.allTimeLow}</span>+ <div style={{ display: 'flex', gap: '8px' }}>+ <button+ onClick={refreshWatchlistData}+ disabled={!selectedWatchlist || refreshing}+ style={{+ background: selectedWatchlist && !refreshing ? GREEN : GRAY,+ color: 'black',+ border: 'none',+ padding: '4px 12px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: selectedWatchlist && !refreshing ? 'pointer' : 'not-allowed',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ opacity: selectedWatchlist && !refreshing ? 1 : 0.5+ }}+ >+ <RefreshCw size={12} />+ REFRESH+ </button>+ <button+ onClick={handleExportCSV}+ disabled={!selectedWatchlist}+ style={{+ background: selectedWatchlist ? CYAN : GRAY,+ color: 'black',+ border: 'none',+ padding: '4px 12px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: selectedWatchlist ? 'pointer' : 'not-allowed',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ opacity: selectedWatchlist ? 1 : 0.5+ }}+ >+ <Download size={12} />+ EXPORT CSV+ </button>+ </div></div>++ {/* Summary Bar */}+ {selectedWatchlist && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px', fontSize: '11px', marginTop: '8px' }}>+ <span style={{ color: GRAY }}>WATCHLIST:</span>+ <span style={{ color: YELLOW, fontWeight: 'bold' }}>+ {selectedWatchlist.name}+ </span>+ <span style={{ color: WHITE }}>|</span>+ <span style={{ color: GRAY }}>STOCKS:</span>+ <span style={{ color: CYAN }}>{stocks.length}</span>+ </div>+ )}</div>- {/* Function Keys */}+ {/* Function Keys Bar */}<div style={{- backgroundColor: BLOOMBERG_PANEL_BG,- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,- padding: '2px 4px',+ backgroundColor: PANEL_BG,+ borderBottom: `1px solid ${GRAY}`,+ padding: '4px 8px',flexShrink: 0}}>- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: '2px' }}>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: '4px' }}>{[- { key: "F1", label: "DETAILED", view: "DETAILED" },- { key: "F2", label: "COMPACT", view: "COMPACT" },- { key: "F3", label: "CHARTS", view: "CHARTS" },- { key: "F4", label: "ADD", view: "ADD" },- { key: "F5", label: "REMOVE", view: "REMOVE" },- { key: "F6", label: "ALERTS", view: "ALERTS" },- { key: "F7", label: "SORT", view: "SORT" },- { key: "F8", label: "FILTER", view: "FILTER" },- { key: "F9", label: "IMPORT", view: "IMPORT" },- { key: "F10", label: "EXPORT", view: "EXPORT" },- { key: "F11", label: "SETTINGS", view: "SETTINGS" },- { key: "F12", label: "REFRESH", view: "REFRESH" }+ { key: "F1", label: "ADD STOCK", action: () => setShowAddStock(true) },+ { key: "F2", label: "REFRESH", action: refreshWatchlistData },+ { key: "F3", label: "EXPORT", action: handleExportCSV },+ { key: "F4", label: "SORT", action: () => setSortBy('CHANGE') },+ { key: "F5", label: "CREATE", action: () => setShowCreateWatchlist(true) },+ { key: "F6", label: "TICKER", action: () => setSortBy('TICKER') },+ { key: "F7", label: "PRICE", action: () => setSortBy('PRICE') },+ { key: "F8", label: "VOLUME", action: () => setSortBy('VOLUME') },+ { key: "F9", label: "UNUSED", action: () => {} },+ { key: "F10", label: "UNUSED", action: () => {} },+ { key: "F11", label: "UNUSED", action: () => {} },+ { key: "F12", label: "HELP", action: () => {} }].map(item => (- <button key={item.key}- onClick={() => setViewMode(item.view)}+ <button+ key={item.key}+ onClick={() => {+ if (item.label === "ADD STOCK" || item.label === "CREATE") {+ item.action();+ } else if (selectedWatchlist) {+ item.action();+ }+ }}+ disabled={!selectedWatchlist && item.label !== "CREATE"}style={{- backgroundColor: viewMode === item.view ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,- border: `1px solid ${BLOOMBERG_GRAY}`,- color: viewMode === item.view ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,- padding: '2px 4px',+ backgroundColor: DARK_BG,+ border: `1px solid ${GRAY}`,+ color: WHITE,+ padding: '4px 6px',fontSize: '9px',- height: '16px',+ cursor: (selectedWatchlist || item.label === "CREATE") ? 'pointer' : 'not-allowed',display: 'flex',alignItems: 'center',justifyContent: 'center',- fontWeight: viewMode === item.view ? 'bold' : 'normal',- cursor: 'pointer'- }}>- <span style={{ color: BLOOMBERG_YELLOW }}>{item.key}:</span>- <span style={{ marginLeft: '2px' }}>{item.label}</span>+ gap: '2px',+ opacity: (!selectedWatchlist && item.label !== "CREATE") ? 0.5 : 1+ }}+ >+ <span style={{ color: YELLOW }}>{item.key}:</span>+ <span>{item.label}</span></button>))}</div></div>{/* Main Content */}- <div style={{ flex: 1, overflow: 'auto', padding: '4px', backgroundColor: '#050505' }}>- <div style={{ display: 'flex', gap: '4px', height: '100%' }}>-- {/* Left Panel - Watchlist Groups */}- <div style={{- width: '280px',- backgroundColor: BLOOMBERG_PANEL_BG,- border: `1px solid ${BLOOMBERG_GRAY}`,- padding: '4px',- overflow: 'auto'- }}>- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>- WATCHLIST GROUPS- </div>- <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '8px' }}></div>-- {watchlistGroups.map((group, index) => (- <button key={index}- onClick={() => setSelectedList(group.name)}- style={{- width: '100%',- display: 'flex',- justifyContent: 'space-between',- padding: '6px',- marginBottom: '3px',- backgroundColor: selectedList === group.name ? 'rgba(255,165,0,0.1)' : 'rgba(255,255,255,0.02)',- border: `1px solid ${selectedList === group.name ? BLOOMBERG_ORANGE : 'transparent'}`,- textAlign: 'left',- cursor: 'pointer',- fontSize: '10px'- }}>- <span style={{ color: group.color, fontWeight: 'bold' }}>{group.name}</span>- <span style={{ color: BLOOMBERG_CYAN }}>{group.count} stocks</span>- </button>- ))}-- <div style={{ borderTop: `1px solid ${BLOOMBERG_GRAY}`, marginTop: '12px', paddingTop: '8px' }}>- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>- MARKET MOVERS- </div>- {[- { ticker: 'NVDA', change: '+5.12%', type: 'GAINER', color: BLOOMBERG_GREEN },- { ticker: 'META', change: '+3.21%', type: 'GAINER', color: BLOOMBERG_GREEN },- { ticker: 'TSLA', change: '-2.54%', type: 'LOSER', color: BLOOMBERG_RED },- { ticker: 'GOOGL', change: '-1.23%', type: 'LOSER', color: BLOOMBERG_RED }- ].map((mover, index) => (- <div key={index} style={{- display: 'flex',- justifyContent: 'space-between',- padding: '3px',- marginBottom: '2px',- backgroundColor: 'rgba(255,255,255,0.02)',- fontSize: '9px'- }}>- <div>- <span style={{ color: BLOOMBERG_CYAN }}>{mover.ticker}</span>- <span style={{ color: BLOOMBERG_GRAY, marginLeft: '4px', fontSize: '8px' }}>[{mover.type}]</span>- </div>- <span style={{ color: mover.color, fontWeight: 'bold' }}>{mover.change}</span>- </div>- ))}- </div>-- <div style={{ borderTop: `1px solid ${BLOOMBERG_GRAY}`, marginTop: '12px', paddingTop: '8px' }}>- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>- VOLUME LEADERS- </div>- {[- { ticker: 'TSLA', volume: '89.0M', pctAvg: '+179%' },- { ticker: 'AAPL', volume: '48.2M', pctAvg: '-8%' },- { ticker: 'AMZN', volume: '45.7M', pctAvg: '-12%' },- { ticker: 'NVDA', volume: '35.7M', pctAvg: '-13%' }- ].map((stock, index) => (- <div key={index} style={{- display: 'flex',- justifyContent: 'space-between',- padding: '3px',- marginBottom: '2px',- backgroundColor: 'rgba(255,255,255,0.02)',- fontSize: '9px'- }}>- <span style={{ color: BLOOMBERG_CYAN }}>{stock.ticker}</span>- <div style={{ textAlign: 'right' }}>- <div style={{ color: BLOOMBERG_WHITE }}>{stock.volume}</div>- <div style={{ color: stock.pctAvg.startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED, fontSize: '8px' }}>- {stock.pctAvg}- </div>- </div>- </div>- ))}- </div>-- <div style={{ borderTop: `1px solid ${BLOOMBERG_GRAY}`, marginTop: '12px', paddingTop: '8px' }}>- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>- QUICK ACTIONS- </div>- {[- { label: 'Add Stock', color: BLOOMBERG_GREEN },- { label: 'Create List', color: BLOOMBERG_BLUE },- { label: 'Set Alert', color: BLOOMBERG_YELLOW },- { label: 'Import CSV', color: BLOOMBERG_CYAN },- { label: 'Export Data', color: BLOOMBERG_PURPLE }- ].map((action, index) => (- <button key={index} style={{- width: '100%',- padding: '4px',- marginBottom: '2px',- backgroundColor: 'rgba(255,255,255,0.02)',- border: `1px solid ${BLOOMBERG_GRAY}`,- color: action.color,- fontSize: '9px',- cursor: 'pointer',- textAlign: 'left'- }}>- {action.label}- </button>- ))}- </div>- </div>+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>+ {/* Left Sidebar - Watchlist Groups */}+ <WatchlistSidebar+ watchlists={watchlists}+ selectedWatchlistId={selectedWatchlist?.id || null}+ onSelectWatchlist={(id) => {+ const wl = watchlists.find(w => w.id === id);+ if (wl) setSelectedWatchlist(wl);+ }}+ onCreateWatchlist={() => setShowCreateWatchlist(true)}+ onDeleteWatchlist={handleDeleteWatchlist}+ marketMovers={marketMovers || undefined}+ volumeLeaders={volumeLeaders}+ />- {/* Center Panel - Stock List */}+ {/* Center Panel - Stock List */}+ {!selectedWatchlist ? (<div style={{flex: 1,- backgroundColor: BLOOMBERG_PANEL_BG,- border: `1px solid ${BLOOMBERG_GRAY}`,- padding: '4px',- overflow: 'auto'+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '16px'}}>- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>- WATCHLIST: {selectedList}- </div>- <div style={{ display: 'flex', gap: '4px', fontSize: '9px' }}>- <button onClick={() => setSortBy('TICKER')} style={{- padding: '2px 6px',- backgroundColor: sortBy === 'TICKER' ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,- color: sortBy === 'TICKER' ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,- border: `1px solid ${BLOOMBERG_GRAY}`,- cursor: 'pointer'- }}>TICKER</button>- <button onClick={() => setSortBy('CHANGE')} style={{- padding: '2px 6px',- backgroundColor: sortBy === 'CHANGE' ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,- color: sortBy === 'CHANGE' ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,- border: `1px solid ${BLOOMBERG_GRAY}`,- cursor: 'pointer'- }}>CHANGE</button>- <button onClick={() => setSortBy('VOLUME')} style={{- padding: '2px 6px',- backgroundColor: sortBy === 'VOLUME' ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,- color: sortBy === 'VOLUME' ? BLOOMBERG_DARK_BG : BLOOMBERG_WHITE,- border: `1px solid ${BLOOMBERG_GRAY}`,- cursor: 'pointer'- }}>VOLUME</button>- </div>+ <div style={{ color: GRAY, fontSize: '14px' }}>+ Select a watchlist or create a new one to get started</div>- <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '8px' }}></div>-- {/* Table Header */}- <div style={{- display: 'grid',- gridTemplateColumns: '80px 200px 90px 90px 90px 90px 90px 90px',- gap: '4px',- padding: '4px',- backgroundColor: 'rgba(255,255,255,0.05)',- fontSize: '9px',- fontWeight: 'bold',- marginBottom: '2px'- }}>- <div style={{ color: BLOOMBERG_GRAY }}>TICKER</div>- <div style={{ color: BLOOMBERG_GRAY }}>NAME</div>- <div style={{ color: BLOOMBERG_GRAY }}>PRICE</div>- <div style={{ color: BLOOMBERG_GRAY }}>CHANGE</div>- <div style={{ color: BLOOMBERG_GRAY }}>VOLUME</div>- <div style={{ color: BLOOMBERG_GRAY }}>HIGH/LOW</div>- <div style={{ color: BLOOMBERG_GRAY }}>MKT CAP</div>- <div style={{ color: BLOOMBERG_GRAY }}>P/E</div>- </div>-- {/* Stock Rows */}- {watchlistStocks.map((stock, index) => (- <div key={index} style={{- display: 'grid',- gridTemplateColumns: '80px 200px 90px 90px 90px 90px 90px 90px',- gap: '4px',- padding: '6px 4px',- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',- borderLeft: `3px solid ${stock.change >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED}`,- fontSize: '10px',- marginBottom: '1px'- }}>- <div style={{ color: BLOOMBERG_CYAN, fontWeight: 'bold' }}>{stock.ticker}</div>- <div style={{ color: BLOOMBERG_WHITE, overflow: 'hidden', textOverflow: 'ellipsis' }}>{stock.name}</div>- <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>${stock.price.toFixed(2)}</div>- <div>- <div style={{ color: stock.change >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED }}>- {stock.change >= 0 ? '+' : ''}{stock.change.toFixed(2)}- </div>- <div style={{ color: stock.change >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED, fontSize: '8px' }}>- ({stock.changePercent >= 0 ? '+' : ''}{stock.changePercent.toFixed(2)}%)- </div>- </div>- <div style={{ color: BLOOMBERG_YELLOW }}>{(stock.volume / 1000000).toFixed(1)}M</div>- <div style={{ fontSize: '9px' }}>- <div style={{ color: BLOOMBERG_GREEN }}>${stock.high.toFixed(2)}</div>- <div style={{ color: BLOOMBERG_RED }}>${stock.low.toFixed(2)}</div>- </div>- <div style={{ color: BLOOMBERG_CYAN }}>{stock.marketCap}</div>- <div style={{ color: BLOOMBERG_WHITE }}>{stock.pe.toFixed(1)}</div>- </div>- ))}</div>+ ) : (+ <StockListView+ stocks={sortedStocks}+ watchlistName={selectedWatchlist.name}+ sortBy={sortBy}+ onSortChange={setSortBy}+ onStockClick={setSelectedStock}+ onRemoveStock={handleRemoveStock}+ selectedSymbol={selectedStock?.symbol}+ />+ )}- {/* Right Panel - Stock Details */}- <div style={{- width: '320px',- backgroundColor: BLOOMBERG_PANEL_BG,- border: `1px solid ${BLOOMBERG_GRAY}`,- padding: '4px',- overflow: 'auto'- }}>- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>- STOCK DETAIL: {watchlistStocks[0].ticker}- </div>- <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '8px' }}></div>-- {/* Price Info */}- <div style={{ marginBottom: '12px' }}>- <div style={{ padding: '6px', backgroundColor: 'rgba(255,165,0,0.1)', marginBottom: '4px' }}>- <div style={{ color: BLOOMBERG_GRAY, fontSize: '9px', marginBottom: '2px' }}>LAST PRICE</div>- <div style={{ color: BLOOMBERG_WHITE, fontSize: '20px', fontWeight: 'bold' }}>- ${watchlistStocks[0].price.toFixed(2)}- </div>- <div style={{ color: watchlistStocks[0].change >= 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED, fontSize: '12px' }}>- {watchlistStocks[0].change >= 0 ? '+' : ''}{watchlistStocks[0].change.toFixed(2)} (- {watchlistStocks[0].changePercent >= 0 ? '+' : ''}{watchlistStocks[0].changePercent.toFixed(2)}%)- </div>- </div>- </div>-- {/* Trading Stats */}- <div style={{ fontSize: '9px', lineHeight: '1.5', marginBottom: '12px' }}>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>- <span style={{ color: BLOOMBERG_GRAY }}>Open:</span>- <span style={{ color: BLOOMBERG_WHITE }}>${watchlistStocks[0].open.toFixed(2)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>- <span style={{ color: BLOOMBERG_GRAY }}>Prev Close:</span>- <span style={{ color: BLOOMBERG_WHITE }}>${watchlistStocks[0].prevClose.toFixed(2)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>- <span style={{ color: BLOOMBERG_GRAY }}>Day High:</span>- <span style={{ color: BLOOMBERG_GREEN }}>${watchlistStocks[0].high.toFixed(2)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>- <span style={{ color: BLOOMBERG_GRAY }}>Day Low:</span>- <span style={{ color: BLOOMBERG_RED }}>${watchlistStocks[0].low.toFixed(2)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>- <span style={{ color: BLOOMBERG_GRAY }}>52W High:</span>- <span style={{ color: BLOOMBERG_GREEN }}>${watchlistStocks[0].week52High.toFixed(2)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>- <span style={{ color: BLOOMBERG_GRAY }}>52W Low:</span>- <span style={{ color: BLOOMBERG_RED }}>${watchlistStocks[0].week52Low.toFixed(2)}</span>- </div>- <div style={{ borderTop: `1px solid ${BLOOMBERG_GRAY}`, marginTop: '4px', paddingTop: '4px' }}>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>- <span style={{ color: BLOOMBERG_GRAY }}>Volume:</span>- <span style={{ color: BLOOMBERG_YELLOW }}>{(watchlistStocks[0].volume / 1000000).toFixed(1)}M</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: BLOOMBERG_GRAY }}>Avg Volume:</span>- <span style={{ color: BLOOMBERG_CYAN }}>{watchlistStocks[0].avgVolume}</span>- </div>- </div>- </div>-- <div style={{ borderTop: `1px solid ${BLOOMBERG_GRAY}`, paddingTop: '8px', marginBottom: '8px' }}>- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>- FUNDAMENTAL DATA- </div>- <div style={{ fontSize: '9px', lineHeight: '1.5' }}>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>- <span style={{ color: BLOOMBERG_GRAY }}>Market Cap:</span>- <span style={{ color: BLOOMBERG_WHITE }}>{watchlistStocks[0].marketCap}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>- <span style={{ color: BLOOMBERG_GRAY }}>P/E Ratio:</span>- <span style={{ color: BLOOMBERG_CYAN }}>{watchlistStocks[0].pe.toFixed(2)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>- <span style={{ color: BLOOMBERG_GRAY }}>Dividend Yield:</span>- <span style={{ color: BLOOMBERG_GREEN }}>{watchlistStocks[0].yield.toFixed(2)}%</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '2px' }}>- <span style={{ color: BLOOMBERG_GRAY }}>EPS (TTM):</span>- <span style={{ color: BLOOMBERG_WHITE }}>$6.42</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: BLOOMBERG_GRAY }}>Beta:</span>- <span style={{ color: BLOOMBERG_YELLOW }}>1.23</span>- </div>- </div>- </div>-- <div style={{ borderTop: `1px solid ${BLOOMBERG_GRAY}`, paddingTop: '8px' }}>- <div style={{ color: BLOOMBERG_YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>- PRICE ALERTS- </div>- {[- { type: 'ABOVE', price: 190.00, status: 'ACTIVE', color: BLOOMBERG_GREEN },- { type: 'BELOW', price: 175.00, status: 'ACTIVE', color: BLOOMBERG_RED },- { type: 'TARGET', price: 200.00, status: 'PENDING', color: BLOOMBERG_YELLOW }- ].map((alert, index) => (- <div key={index} style={{- marginBottom: '4px',- padding: '4px',- backgroundColor: 'rgba(255,255,255,0.02)',- borderLeft: `2px solid ${alert.color}`,- fontSize: '9px'- }}>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>- <span style={{ color: alert.color, fontWeight: 'bold' }}>[{alert.type}]</span>- <span style={{ color: BLOOMBERG_GRAY }}>{alert.status}</span>- </div>- <div style={{ color: BLOOMBERG_WHITE }}>Target: ${alert.price.toFixed(2)}</div>- </div>- ))}-- <button style={{- width: '100%',- marginTop: '6px',- padding: '4px',- backgroundColor: 'rgba(255,165,0,0.1)',- border: `1px solid ${BLOOMBERG_ORANGE}`,- color: BLOOMBERG_ORANGE,- fontSize: '9px',- cursor: 'pointer'- }}>- + CREATE NEW ALERT- </button>- </div>- </div>- </div>+ {/* Right Panel - Stock Details */}+ <StockDetailPanel stock={selectedStock} /></div>{/* Status Bar */}<div style={{- borderTop: `1px solid ${BLOOMBERG_GRAY}`,- backgroundColor: BLOOMBERG_PANEL_BG,- padding: '2px 8px',- fontSize: '10px',- color: BLOOMBERG_GRAY,+ borderTop: `1px solid ${GRAY}`,+ backgroundColor: PANEL_BG,+ padding: '4px 12px',+ fontSize: '9px',+ color: GRAY,flexShrink: 0}}><div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>- <div style={{ display: 'flex', gap: '16px' }}>- <span>Fincept Watchlist Monitor v1.8.2 | Real-time market data</span>- <span>Tracking: {watchlistStocks.length} stocks | Lists: {watchlistGroups.length}</span>- </div>- <div style={{ display: 'flex', gap: '16px' }}>- <span>List: {selectedList}</span>- <span>Sort: {sortBy}</span>- <span style={{ color: BLOOMBERG_GREEN }}>QUOTES: LIVE</span>- </div>+ <span>Fincept Watchlist Monitor v2.0.0 | Real-time tracking with yfinance integration</span>+ {selectedWatchlist && (+ <span>+ Watchlist: {selectedWatchlist.name} | Stocks: {stocks.length} |+ Status: <span style={{ color: GREEN }}>CONNECTED</span>+ </span>+ )}</div></div>++ {/* Create Watchlist Modal */}+ {showCreateWatchlist && (+ <CreateWatchlistModal+ onClose={() => setShowCreateWatchlist(false)}+ onCreate={handleCreateWatchlist}+ existingColors={watchlists.map(w => w.color)}+ />+ )}++ {/* Add Stock Modal */}+ {showAddStock && selectedWatchlist && (+ <AddStockModal+ onClose={() => setShowAddStock(false)}+ onAdd={handleAddStock}+ existingSymbols={stocks.map(s => s.symbol)}+ />+ )}</div>);};-export default WatchlistTab;\ No newline at end of file+export default WatchlistTab;diff --git a/fincept-terminal-desktop/src/components/tabs/agents/AgentsTab.tsx b/fincept-terminal-desktop/src/components/tabs/agents/AgentsTab.tsxindex a2e623a9a..792cbc854 100644--- a/fincept-terminal-desktop/src/components/tabs/agents/AgentsTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/agents/AgentsTab.tsx@@ -31,6 +31,7 @@ import {} from 'lucide-react';import { AGENT_CONFIGS, AGENT_CATEGORIES, getAgentConfig } from './agentConfigs';import { AgentConfig, AgentStatus, AgentCategory } from './types';+import { AgentMCPConfig } from './agentMCPExecutor';// Custom Agent Node Component with Dynamic Handlesconst AgentNode = ({ data, id, selected }: any) => {@@ -254,6 +255,24 @@ const AgentNode = ({ data, id, selected }: any) => {<div>Status: <span style={{ color: getStatusColor(data.status) }}>{data.status}</span></div>+ {data.mcpConfig && data.mcpConfig.enabled && (+ <div style={{+ backgroundColor: '#FFA50020',+ border: '1px solid #FFA500',+ borderRadius: '3px',+ padding: '4px 6px',+ fontSize: '9px',+ color: '#FFA500',+ fontWeight: 'bold',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ marginTop: '4px'+ }}>+ <span>⚡</span>+ <span>MCP: {data.mcpConfig.allowedServers.length} servers</span>+ </div>+ )}{data.hasInput && data.hasOutput && (<div style={{ display: 'flex', gap: '10px', fontSize: '9px', marginTop: '4px' }}><div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>@@ -476,6 +495,14 @@ export default function AgentsTab() {// Add new agent nodeconst addAgentNode = (config: AgentConfig) => {+ // Default MCP configuration+ const defaultMCPConfig: AgentMCPConfig = {+ enabled: false,+ allowedServers: [],+ autonomousMode: true,+ maxToolCalls: 10+ };+const newNode: Node = {id: `agent_${Date.now()}`,type: 'agent',@@ -495,6 +522,7 @@ export default function AgentsTab() {status: 'idle' as AgentStatus,connectedInputs: 0,connectedOutputs: 0,+ mcpConfig: defaultMCPConfig,onLabelChange: handleLabelChange,onParameterChange: handleParameterChange,},@@ -567,11 +595,55 @@ export default function AgentsTab() {// Execute workflowconst executeWorkflow = async () => {setIsExecuting(true);- // Mock execution - in production this would call the actual agent execution engine- setTimeout(() => {++ try {+ console.log('[AgentsTab] Starting workflow execution with', nodes.length, 'agents');++ // Find starting nodes (nodes with no inputs or connected inputs)+ const startingNodes = nodes.filter(node => {+ const hasInputConnections = edges.some(edge => edge.target === node.id);+ return !node.data.hasInput || !hasInputConnections;+ });++ console.log('[AgentsTab] Starting nodes:', startingNodes.map(n => n.data.label));++ // Execute agents with MCP support if enabled+ for (const node of startingNodes) {+ if (node.data.mcpConfig && node.data.mcpConfig.enabled) {+ console.log(`[AgentsTab] Agent ${node.data.label} has MCP enabled with ${node.data.mcpConfig.allowedServers.length} servers`);++ // Update node status+ setNodes((nds) =>+ nds.map((n) =>+ n.id === node.id+ ? { ...n, data: { ...n.data, status: 'running' as AgentStatus } }+ : n+ )+ );++ // Execute agent with MCP (simplified for demonstration)+ // In production, this would call executeAgentWithMCP+ await new Promise(resolve => setTimeout(resolve, 1000));++ // Update node status to completed+ setNodes((nds) =>+ nds.map((n) =>+ n.id === node.id+ ? { ...n, data: { ...n.data, status: 'completed' as AgentStatus, lastRun: Date.now() } }+ : n+ )+ );+ }+ }+setIsExecuting(false);- alert('Workflow execution completed! (Mock implementation)');- }, 2000);+ console.log('[AgentsTab] Workflow execution completed');+ alert('Workflow execution completed!\n\nAgents with MCP enabled can now use external tools autonomously.');+ } catch (error) {+ console.error('[AgentsTab] Workflow execution failed:', error);+ setIsExecuting(false);+ alert('Workflow execution failed: ' + (error instanceof Error ? error.message : 'Unknown error'));+ }};// Filtered agent configsdiff --git a/fincept-terminal-desktop/src/components/tabs/agents/agentMCPExecutor.ts b/fincept-terminal-desktop/src/components/tabs/agents/agentMCPExecutor.tsnew file mode 100644index 000000000..f75986b9f--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/agents/agentMCPExecutor.ts@@ -0,0 +1,241 @@+// Agent MCP Executor - Enables agents to autonomously use MCP tools+// Integrates LLM decision-making with MCP tool execution++import { mcpToolService, MCPTool } from '../../../services/mcpToolService';+import { llmApiService, ChatMessage } from '../../../services/llmApi';++export interface AgentMCPConfig {+ enabled: boolean;+ allowedServers: string[]; // Which MCP servers this agent can use+ autonomousMode: boolean; // Agent decides when to use tools vs user explicitly triggers+ maxToolCalls: number; // Maximum tool calls per execution to prevent infinite loops+}++export interface AgentExecutionContext {+ objective: string; // What the agent is trying to accomplish+ inputs: Record<string, any>; // Inputs from connected nodes+ conversationHistory: ChatMessage[]; // Previous messages in the workflow+}++export interface AgentExecutionResult {+ success: boolean;+ output: string;+ toolCallsMade: ToolCallRecord[];+ error?: string;+ tokensUsed?: number;+}++export interface ToolCallRecord {+ toolName: string;+ serverId: string;+ arguments: Record<string, any>;+ result: any;+ executionTime: number;+ success: boolean;+ error?: string;+}++/**+ * Execute an MCP-enabled agent workflow+ * The agent uses LLM to decide which tools to call and when+ */+export async function executeAgentWithMCP(+ config: AgentMCPConfig,+ context: AgentExecutionContext,+ onProgress?: (message: string) => void+): Promise<AgentExecutionResult> {+ const toolCallRecords: ToolCallRecord[] = [];++ try {+ onProgress?.('Initializing agent with MCP tools...');++ // Get available MCP tools filtered by allowed servers+ let availableTools = await mcpToolService.getAllTools();++ if (config.allowedServers.length > 0) {+ availableTools = availableTools.filter(tool =>+ config.allowedServers.includes(tool.serverId)+ );+ }++ if (availableTools.length === 0) {+ return {+ success: false,+ output: '',+ toolCallsMade: [],+ error: 'No MCP tools available for this agent'+ };+ }++ onProgress?.(`Agent has access to ${availableTools.length} MCP tools`);++ // Format context into initial prompt+ const systemPrompt = `You are an AI agent with access to external tools. Your objective is: ${context.objective}++Available inputs: ${JSON.stringify(context.inputs, null, 2)}++You can use the following MCP tools to accomplish your objective. Use them wisely and only when necessary.+When you're done, provide a final summary of your work.`;++ // Build conversation history+ const conversationHistory: ChatMessage[] = [+ ...context.conversationHistory,+ {+ role: 'user',+ content: systemPrompt+ }+ ];++ // Call LLM with tools (tool execution happens inside chatWithTools)+ // The onToolCall callback tracks all tool executions+ let toolExecutionCount = 0;++ onProgress?.('Calling LLM with available tools...');++ const response = await llmApiService.chatWithTools(+ context.objective, // User's objective+ conversationHistory,+ availableTools,+ undefined, // No streaming for agent execution+ (toolName: string, args: any, result?: any) => {+ if (!result) {+ onProgress?.(`Agent is calling tool: ${toolName}`);+ toolExecutionCount++;+ } else {+ onProgress?.(`Tool ${toolName} completed`);++ // Parse tool name to get serverId and toolName+ const parsed = mcpToolService.parseOpenAIFunctionName(toolName);+ if (parsed) {+ toolCallRecords.push({+ toolName: parsed.toolName,+ serverId: parsed.serverId,+ arguments: args,+ result: result,+ executionTime: 0, // Not tracked in callback+ success: true,+ error: undefined+ });+ }+ }+ }+ );++ if (response.error) {+ return {+ success: false,+ output: '',+ toolCallsMade: toolCallRecords,+ error: response.error+ };+ }++ onProgress?.('Agent execution completed');++ return {+ success: true,+ output: response.content,+ toolCallsMade: toolCallRecords,+ tokensUsed: response.usage?.totalTokens+ };+ } catch (error: any) {+ return {+ success: false,+ output: '',+ toolCallsMade: toolCallRecords,+ error: error.message || 'Unknown error during agent execution'+ };+ }+}++/**+ * Execute a single MCP tool directly without LLM+ * Used when agent workflow has explicit tool nodes+ */+export async function executeToolDirectly(+ serverId: string,+ toolName: string,+ params: Record<string, any>,+ onProgress?: (message: string) => void+): Promise<AgentExecutionResult> {+ try {+ onProgress?.(`Executing ${serverId}.${toolName}...`);++ const result = await mcpToolService.executeToolDirect(serverId, toolName, params);++ const toolCallRecord: ToolCallRecord = {+ toolName,+ serverId,+ arguments: params,+ result: result.data,+ executionTime: result.executionTime || 0,+ success: result.success,+ error: result.error+ };++ if (result.success) {+ onProgress?.('Tool executed successfully');+ return {+ success: true,+ output: JSON.stringify(result.data, null, 2),+ toolCallsMade: [toolCallRecord]+ };+ } else {+ return {+ success: false,+ output: '',+ toolCallsMade: [toolCallRecord],+ error: result.error+ };+ }+ } catch (error: any) {+ return {+ success: false,+ output: '',+ toolCallsMade: [],+ error: error.message || 'Unknown error during tool execution'+ };+ }+}++/**+ * Get available MCP tools for an agent based on its configuration+ */+export async function getAgentAvailableTools(config: AgentMCPConfig): Promise<MCPTool[]> {+ try {+ let tools = await mcpToolService.getAllTools();++ if (config.allowedServers.length > 0) {+ tools = tools.filter(tool => config.allowedServers.includes(tool.serverId));+ }++ return tools;+ } catch (error) {+ console.error('[AgentMCPExecutor] Failed to get available tools:', error);+ return [];+ }+}++/**+ * Validate agent MCP configuration+ */+export function validateAgentMCPConfig(config: AgentMCPConfig): { valid: boolean; errors: string[] } {+ const errors: string[] = [];++ if (config.maxToolCalls <= 0) {+ errors.push('maxToolCalls must be greater than 0');+ }++ if (config.maxToolCalls > 20) {+ errors.push('maxToolCalls cannot exceed 20 (to prevent infinite loops)');+ }++ if (config.enabled && config.allowedServers.length === 0) {+ errors.push('At least one MCP server must be allowed when MCP is enabled');+ }++ return {+ valid: errors.length === 0,+ errors+ };+}diff --git a/fincept-terminal-desktop/src/components/tabs/agents/types.ts b/fincept-terminal-desktop/src/components/tabs/agents/types.tsindex 191b79803..9b394e5af 100644--- a/fincept-terminal-desktop/src/components/tabs/agents/types.ts+++ b/fincept-terminal-desktop/src/components/tabs/agents/types.ts@@ -4,6 +4,14 @@ export type AgentCategory = 'hedge-fund' | 'trader' | 'analysis' | 'data' | 'exeexport type AgentStatus = 'idle' | 'running' | 'completed' | 'error' | 'paused';+// MCP Integration Types+export interface AgentMCPConfig {+ enabled: boolean;+ allowedServers: string[]; // Which MCP servers this agent can use+ autonomousMode: boolean; // Agent decides when to use tools vs user explicitly triggers+ maxToolCalls: number; // Maximum tool calls per execution to prevent infinite loops+}+export interface AgentConfig {id: string;name: string;@@ -46,6 +54,7 @@ export interface AgentNode {status: AgentStatus;lastRun?: string;error?: string;+ mcpConfig?: AgentMCPConfig; // MCP integration configurationonLabelChange: (nodeId: string, newLabel: string) => void;onParameterChange: (nodeId: string, paramName: string, value: any) => void;};diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/MCPAddServerModal.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/MCPAddServerModal.tsxindex c05272f5a..7cde5ab19 100644--- a/fincept-terminal-desktop/src/components/tabs/mcp/MCPAddServerModal.tsx+++ b/fincept-terminal-desktop/src/components/tabs/mcp/MCPAddServerModal.tsx@@ -13,7 +13,7 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })const [formData, setFormData] = useState({name: '',description: '',- command: 'npx',+ command: 'bunx',args: '',envVars: '',category: 'custom',@@ -194,7 +194,7 @@ const MCPAddServerModal: React.FC<MCPAddServerModalProps> = ({ onClose, onAdd })type="text"value={formData.command}onChange={(e) => setFormData({ ...formData, command: e.target.value })}- placeholder="npx, node, python, etc."+ placeholder="bunx, node, python, etc."requiredstyle={{width: '100%',diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/MCPMarketplace.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/MCPMarketplace.tsxdeleted file mode 100644index 83d8a7019..000000000--- a/fincept-terminal-desktop/src/components/tabs/mcp/MCPMarketplace.tsx+++ /dev/null@@ -1,303 +0,0 @@-// MCP Marketplace Component-// Browse and install curated MCP servers--import React, { useState } from 'react';-import { Search, Download } from 'lucide-react';--interface MCPMarketplaceProps {- onInstall: (serverConfig: any) => void;-}--// Curated MCP servers from the ecosystem-const MARKETPLACE_SERVERS = [- {- id: 'postgres',- name: 'PostgreSQL',- description: 'Connect to PostgreSQL databases for queries and analysis',- category: 'data',- icon: '📊',- command: 'npx',- args: ['-y', '@modelcontextprotocol/server-postgres'],- env: { DATABASE_URL: '' },- tools: ['query', 'describe_table', 'list_tables', 'explain_query', 'get_indexes']- },- {- id: 'fetch',- name: 'Web Fetch',- description: 'Fetch and extract content from any URL',- category: 'web',- icon: '🌐',- command: 'npx',- args: ['-y', '@modelcontextprotocol/server-fetch'],- env: {},- tools: ['fetch']- },- {- id: 'brave-search',- name: 'Brave Search',- description: 'Web search using Brave Search API',- category: 'web',- icon: '🔍',- command: 'npx',- args: ['-y', '@modelcontextprotocol/server-brave-search'],- env: { BRAVE_API_KEY: '' },- tools: ['brave_web_search', 'brave_local_search']- },- {- id: 'filesystem',- name: 'FileSystem',- description: 'Read and write files on your system',- category: 'productivity',- icon: '📁',- command: 'npx',- args: ['-y', '@modelcontextprotocol/server-filesystem'],- env: { ALLOWED_DIRECTORIES: '' },- tools: ['read_file', 'write_file', 'list_directory', 'search_files']- },- {- id: 'sqlite',- name: 'SQLite',- description: 'Query and manage SQLite databases',- category: 'data',- icon: '💾',- command: 'npx',- args: ['-y', '@modelcontextprotocol/server-sqlite'],- env: { SQLITE_DB_PATH: '' },- tools: ['query', 'list_tables', 'describe_table']- },- {- id: 'github',- name: 'GitHub',- description: 'Interact with GitHub repositories and issues',- category: 'dev',- icon: '🐙',- command: 'npx',- args: ['-y', '@modelcontextprotocol/server-github'],- env: { GITHUB_TOKEN: '' },- tools: ['create_issue', 'create_pr', 'search_repos', 'get_file_contents']- },- {- id: 'puppeteer',- name: 'Puppeteer',- description: 'Browser automation for web scraping',- category: 'web',- icon: '🎭',- command: 'npx',- args: ['-y', '@modelcontextprotocol/server-puppeteer'],- env: {},- tools: ['puppeteer_navigate', 'puppeteer_screenshot', 'puppeteer_click', 'puppeteer_fill']- },- {- id: 'slack',- name: 'Slack',- description: 'Send messages and interact with Slack',- category: 'productivity',- icon: '💬',- command: 'npx',- args: ['-y', '@modelcontextprotocol/server-slack'],- env: { SLACK_BOT_TOKEN: '' },- tools: ['post_message', 'list_channels', 'get_channel_history']- }-];--const MCPMarketplace: React.FC<MCPMarketplaceProps> = ({ onInstall }) => {- const [searchQuery, setSearchQuery] = useState('');- const [selectedCategory, setSelectedCategory] = useState<string>('all');-- const BLOOMBERG_ORANGE = '#FFA500';- const BLOOMBERG_WHITE = '#FFFFFF';- const BLOOMBERG_GRAY = '#787878';- const BLOOMBERG_DARK_BG = '#000000';- const BLOOMBERG_PANEL_BG = '#0a0a0a';- const BLOOMBERG_YELLOW = '#FFFF00';-- const filteredServers = MARKETPLACE_SERVERS.filter(server => {- const matchesSearch = server.name.toLowerCase().includes(searchQuery.toLowerCase()) ||- server.description.toLowerCase().includes(searchQuery.toLowerCase());- const matchesCategory = selectedCategory === 'all' || server.category === selectedCategory;- return matchesSearch && matchesCategory;- });-- const categories = ['all', 'data', 'web', 'productivity', 'dev'];- const categoryLabels = {- all: 'ALL',- data: 'DATA',- web: 'WEB',- productivity: 'TOOLS',- dev: 'DEV'- };-- const hasRequiredEnv = (server: typeof MARKETPLACE_SERVERS[0]) => {- return Object.keys(server.env).length > 0;- };-- return (- <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>- {/* Header */}- <div style={{- padding: '8px 12px',- backgroundColor: BLOOMBERG_PANEL_BG,- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,- flexShrink: 0- }}>- <span style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>- MARKETPLACE- </span>- </div>-- {/* Search and Filters */}- <div style={{ padding: '8px', flexShrink: 0 }}>- <div style={{ position: 'relative', marginBottom: '8px' }}>- <Search- size={12}- color={BLOOMBERG_GRAY}- style={{ position: 'absolute', left: '6px', top: '6px' }}- />- <input- type="text"- placeholder="Search servers..."- value={searchQuery}- onChange={(e) => setSearchQuery(e.target.value)}- style={{- width: '100%',- backgroundColor: BLOOMBERG_DARK_BG,- border: `1px solid ${BLOOMBERG_GRAY}`,- color: BLOOMBERG_WHITE,- padding: '4px 4px 4px 24px',- fontSize: '10px',- fontFamily: 'Consolas, monospace'- }}- />- </div>-- {/* Categories */}- <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>- {categories.map(cat => (- <button- key={cat}- onClick={() => setSelectedCategory(cat)}- style={{- backgroundColor: selectedCategory === cat ? BLOOMBERG_ORANGE : BLOOMBERG_DARK_BG,- color: selectedCategory === cat ? 'black' : BLOOMBERG_WHITE,- border: `1px solid ${BLOOMBERG_GRAY}`,- padding: '3px 8px',- fontSize: '9px',- cursor: 'pointer',- fontWeight: selectedCategory === cat ? 'bold' : 'normal'- }}- >- {categoryLabels[cat as keyof typeof categoryLabels]}- </button>- ))}- </div>- </div>-- {/* Server List */}- <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>- {filteredServers.length === 0 ? (- <div style={{- textAlign: 'center',- color: BLOOMBERG_GRAY,- padding: '40px 20px',- fontSize: '10px'- }}>- No servers found matching your search.- </div>- ) : (- filteredServers.map(server => (- <div- key={server.id}- style={{- backgroundColor: BLOOMBERG_DARK_BG,- border: `1px solid ${BLOOMBERG_GRAY}`,- padding: '8px',- marginBottom: '6px'- }}- >- <div style={{- display: 'flex',- justifyContent: 'space-between',- alignItems: 'flex-start',- marginBottom: '4px'- }}>- <div style={{ flex: 1 }}>- <div style={{- display: 'flex',- alignItems: 'center',- gap: '6px',- marginBottom: '3px'- }}>- <span style={{ fontSize: '14px' }}>{server.icon}</span>- <span style={{- color: BLOOMBERG_WHITE,- fontSize: '11px',- fontWeight: 'bold'- }}>- {server.name}- </span>- <span style={{- color: BLOOMBERG_GRAY,- fontSize: '8px',- backgroundColor: BLOOMBERG_PANEL_BG,- padding: '2px 4px'- }}>- {server.tools.length} tools- </span>- </div>-- <div style={{- color: BLOOMBERG_GRAY,- fontSize: '9px',- marginBottom: '4px'- }}>- {server.description}- </div>-- {hasRequiredEnv(server) && (- <div style={{- color: BLOOMBERG_YELLOW,- fontSize: '8px',- marginBottom: '4px'- }}>- ⚠️ Requires: {Object.keys(server.env).join(', ')}- </div>- )}-- <div style={{- color: BLOOMBERG_GRAY,- fontSize: '8px',- fontFamily: 'Consolas, monospace'- }}>- {server.command} {server.args.join(' ')}- </div>- </div>- </div>-- <button- onClick={() => onInstall(server)}- style={{- backgroundColor: BLOOMBERG_ORANGE,- color: 'black',- border: 'none',- padding: '4px 10px',- fontSize: '9px',- fontWeight: 'bold',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '4px',- marginTop: '6px'- }}- >- <Download size={10} />- INSTALL- </button>- </div>- ))- )}- </div>- </div>- );-};--export default MCPMarketplace;diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/docs/MCP_TEMPLATE.ts b/fincept-terminal-desktop/src/components/tabs/mcp/docs/MCP_TEMPLATE.tsnew file mode 100644index 000000000..475a9c8fd--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/mcp/docs/MCP_TEMPLATE.ts@@ -0,0 +1,163 @@+/**+ * MCP Server Template+ *+ * Copy this template to add a new MCP server to the marketplace.+ * Replace all placeholder values marked with <...>+ */++import { MCPServerDefinition } from '../marketplace/serverDefinitions';++export const YOUR_MCP_TEMPLATE: MCPServerDefinition = {+ // Unique identifier (lowercase, hyphenated)+ id: '<your-mcp-id>',++ // Display name+ name: '<Your MCP Name>',++ // Brief description (shown in marketplace)+ description: '<What this MCP server does in one line>',++ // Category: 'data' | 'web' | 'productivity' | 'dev' | 'custom'+ category: 'data',++ // Emoji icon (single emoji)+ icon: '🔧',++ // Command to run (usually 'bunx' for npm packages)+ command: 'bunx',++ // Command arguments+ args: [+ '-y', // Force install without prompt+ '@<your-org>/<your-mcp-package>' // npm package name+ ],++ // Environment variables (optional)+ // Set to empty object {} if not needed+ env: {+ // 'API_KEY': '',+ // 'ENDPOINT_URL': ''+ },++ // CLI argument (optional)+ // Use this if server expects connection string as argument+ // Examples: 'DATABASE_URL', 'CONNECTION_STRING', 'API_ENDPOINT'+ // Leave undefined if not needed+ requiresArg: undefined, // or 'DATABASE_URL'++ // Whether this server needs configuration+ // true = shows configuration form before install+ // false = installs directly+ requiresConfig: true,++ // List of tools provided by this MCP server+ // Get this from the MCP server's documentation+ tools: [+ 'tool_name_1',+ 'tool_name_2',+ 'tool_name_3'+ ],++ // Link to MCP server documentation (optional)+ documentation: 'https://github.com/<your-org>/<your-mcp-repo>'+};++/**+ * Example 1: Simple MCP (no configuration)+ */+export const EXAMPLE_SIMPLE: MCPServerDefinition = {+ id: 'time-server',+ name: 'Time Server',+ description: 'Get current time in any timezone',+ category: 'productivity',+ icon: '⏰',+ command: 'bunx',+ args: ['-y', '@modelcontextprotocol/server-time'],+ env: {},+ requiresConfig: false, // No config needed+ tools: ['get_time', 'convert_timezone', 'list_timezones'],+ documentation: 'https://github.com/modelcontextprotocol/servers/tree/main/src/time'+};++/**+ * Example 2: API-based MCP (requires API key)+ */+export const EXAMPLE_API: MCPServerDefinition = {+ id: 'weather-api',+ name: 'Weather API',+ description: 'Get weather data and forecasts',+ category: 'web',+ icon: '🌤️',+ command: 'bunx',+ args: ['-y', '@example/weather-mcp'],+ env: {+ OPENWEATHER_API_KEY: '' // User will fill this in+ },+ requiresConfig: true, // Uses GenericForm+ tools: ['get_current_weather', 'get_forecast', 'get_historical'],+ documentation: 'https://docs.example.com/weather-mcp'+};++/**+ * Example 3: Database MCP (requires connection string)+ */+export const EXAMPLE_DATABASE: MCPServerDefinition = {+ id: 'mongodb',+ name: 'MongoDB',+ description: 'Connect to MongoDB databases for queries and updates',+ category: 'data',+ icon: '🍃',+ command: 'bunx',+ args: ['-y', '@example/mongodb-mcp'],+ requiresArg: 'MONGODB_URI', // Connection string as CLI argument+ requiresConfig: true, // Needs custom MongoDBForm+ tools: ['find', 'insert', 'update', 'delete', 'aggregate', 'list_collections'],+ documentation: 'https://docs.example.com/mongodb-mcp'+};++/**+ * Example 4: Complex MCP (mixed configuration)+ */+export const EXAMPLE_COMPLEX: MCPServerDefinition = {+ id: 'analytics',+ name: 'Analytics Platform',+ description: 'Connect to analytics platform for data insights',+ category: 'data',+ icon: '📊',+ command: 'bunx',+ args: ['-y', '@example/analytics-mcp'],+ env: {+ API_KEY: '',+ WORKSPACE_ID: ''+ },+ requiresArg: 'ENDPOINT_URL', // Also needs CLI argument+ requiresConfig: true, // Needs custom AnalyticsForm+ tools: [+ 'get_metrics',+ 'run_query',+ 'create_dashboard',+ 'export_data',+ 'list_datasets'+ ],+ documentation: 'https://docs.example.com/analytics-mcp'+};++/**+ * USAGE:+ *+ * 1. Copy one of the examples above that matches your needs+ * 2. Customize all fields+ * 3. Add to MARKETPLACE_SERVERS array in serverDefinitions.ts:+ *+ * export const MARKETPLACE_SERVERS: MCPServerDefinition[] = [+ * // ... existing servers+ * YOUR_NEW_SERVER, // Add here+ * ];+ *+ * 4. If requiresConfig = true and you need a custom form:+ * - Create src/components/tabs/mcp/marketplace/forms/YourMCPForm.tsx+ * - Register in MCPMarketplace.tsx renderConfigForm() switch statement+ *+ * 5. Test:+ * npm run tauri dev+ */diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/index.tsxindex 308fffd80..fffa16b45 100644--- a/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx+++ b/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx@@ -2,30 +2,33 @@// Manage MCP servers and tools in Bloomberg-style interfaceimport React, { useState, useEffect } from 'react';-import { Plus, RefreshCw } from 'lucide-react';+import { Plus, RefreshCw, Search, Play, Square, Trash2, Settings, Zap, CheckCircle, XCircle, AlertCircle } from 'lucide-react';import { mcpManager, MCPServerWithStats } from '../../../services/mcpManager';import { sqliteService } from '../../../services/sqliteService';-import MCPServerCard from './MCPServerCard';-import MCPMarketplace from './MCPMarketplace';+import MCPMarketplace from './marketplace/MCPMarketplace';import MCPAddServerModal from './MCPAddServerModal';const MCPTab: React.FC = () => {+ const [view, setView] = useState<'marketplace' | 'installed'>('marketplace');const [servers, setServers] = useState<MCPServerWithStats[]>([]);const [tools, setTools] = useState<any[]>([]);const [isAddModalOpen, setIsAddModalOpen] = useState(false);const [isRefreshing, setIsRefreshing] = useState(false);const [statusMessage, setStatusMessage] = useState('Initializing...');+ const [searchTerm, setSearchTerm] = useState('');// Bloomberg colors- const BLOOMBERG_ORANGE = '#FFA500';- const BLOOMBERG_WHITE = '#FFFFFF';- const BLOOMBERG_GRAY = '#787878';- const BLOOMBERG_DARK_BG = '#000000';- const BLOOMBERG_PANEL_BG = '#0a0a0a';- const BLOOMBERG_GREEN = '#00C800';+ const ORANGE = '#FFA500';+ const WHITE = '#FFFFFF';+ const GRAY = '#787878';+ const DARK_BG = '#0a0a0a';+ const PANEL_BG = '#1a1a1a';+ const BORDER = '#2d2d2d';+ const GREEN = '#10b981';+ const RED = '#ef4444';+ const YELLOW = '#f59e0b';useEffect(() => {- // Auto-start servers on mountconst initializeServers = async () => {try {await mcpManager.startAutoStartServers();@@ -37,7 +40,6 @@ const MCPTab: React.FC = () => {initializeServers();- // Auto-refresh every 5 secondsconst interval = setInterval(() => {loadData(true);}, 5000);@@ -56,7 +58,7 @@ const MCPTab: React.FC = () => {setTools(toolsData);const runningCount = serversData.filter(s => s.status === 'running').length;- setStatusMessage(`${runningCount} servers connected | ${toolsData.length} tools available`);+ setStatusMessage(`${runningCount} running | ${toolsData.length} tools available`);} catch (error) {console.error('Failed to load MCP data:', error);setStatusMessage('Error loading data');@@ -75,6 +77,7 @@ const MCPTab: React.FC = () => {await mcpManager.installServer(config);await loadData();setStatusMessage('Server installed successfully');+ setView('installed');} catch (error) {console.error('Failed to install server:', error);setStatusMessage(`Installation failed: ${error instanceof Error ? error.message : 'Unknown error'}`);@@ -130,177 +133,478 @@ const MCPTab: React.FC = () => {}};+ const getStatusIcon = (status: string) => {+ switch (status) {+ case 'running':+ return <CheckCircle size={14} color={GREEN} />;+ case 'error':+ return <XCircle size={14} color={RED} />;+ default:+ return <AlertCircle size={14} color={GRAY} />;+ }+ };++ const getStatusColor = (status: string) => {+ switch (status) {+ case 'running':+ return GREEN;+ case 'error':+ return RED;+ default:+ return GRAY;+ }+ };+const runningServers = servers.filter(s => s.status === 'running').length;+ const filteredServers = servers.filter(s =>+ s.name.toLowerCase().includes(searchTerm.toLowerCase()) ||+ s.description.toLowerCase().includes(searchTerm.toLowerCase())+ );return (<div style={{+ width: '100%',height: '100%',- backgroundColor: BLOOMBERG_DARK_BG,- color: BLOOMBERG_WHITE,+ backgroundColor: DARK_BG,+ color: WHITE,fontFamily: 'Consolas, monospace',display: 'flex',flexDirection: 'column',- fontSize: '11px'+ fontSize: '11px',+ overflow: 'hidden'}}>{/* Header */}<div style={{- backgroundColor: BLOOMBERG_PANEL_BG,- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,- padding: '8px 12px',- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center',+ backgroundColor: PANEL_BG,+ borderBottom: `1px solid ${BORDER}`,+ padding: '12px 16px',flexShrink: 0}}>- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>- <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold', fontSize: '12px' }}>- MCP INTEGRATIONS- </span>- <span style={{ color: BLOOMBERG_GRAY }}>|</span>- <span style={{ color: runningServers > 0 ? BLOOMBERG_GREEN : BLOOMBERG_GRAY, fontSize: '10px' }}>- {runningServers} Running- </span>- <span style={{ color: BLOOMBERG_GRAY }}>|</span>- <span style={{ color: BLOOMBERG_WHITE, fontSize: '10px' }}>- {tools.length} Tools- </span>- </div>-- <div style={{ display: 'flex', gap: '6px' }}>- <button- onClick={handleRefresh}- disabled={isRefreshing}- style={{- backgroundColor: BLOOMBERG_DARK_BG,- border: `1px solid ${BLOOMBERG_GRAY}`,- color: BLOOMBERG_WHITE,- padding: '4px 10px',- fontSize: '10px',- cursor: isRefreshing ? 'not-allowed' : 'pointer',- display: 'flex',- alignItems: 'center',- gap: '4px',- opacity: isRefreshing ? 0.5 : 1- }}- >- <RefreshCw size={12} style={{ animation: isRefreshing ? 'spin 1s linear infinite' : 'none' }} />- REFRESH- </button>-- <button- onClick={() => setIsAddModalOpen(true)}- style={{- backgroundColor: BLOOMBERG_ORANGE,- color: 'black',- border: 'none',- padding: '4px 10px',- fontSize: '10px',+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <span style={{+ color: ORANGE,+ fontSize: '14px',fontWeight: 'bold',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '4px'- }}- >- <Plus size={12} />- ADD SERVER- </button>+ letterSpacing: '0.5px'+ }}>+ MCP MARKETPLACE+ </span>+ <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }}></div>+ <span style={{ color: GRAY, fontSize: '11px' }}>+ {servers.length} Installed | {runningServers} Running | {tools.length} Tools+ </span>+ </div>++ {/* View Switcher */}+ <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>+ <button+ onClick={handleRefresh}+ disabled={isRefreshing}+ style={{+ backgroundColor: 'transparent',+ border: `1px solid ${BORDER}`,+ color: WHITE,+ padding: '6px 12px',+ fontSize: '10px',+ cursor: isRefreshing ? 'not-allowed' : 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ opacity: isRefreshing ? 0.5 : 1,+ fontWeight: 'bold'+ }}+ >+ <RefreshCw size={12} style={{ animation: isRefreshing ? 'spin 1s linear infinite' : 'none' }} />+ REFRESH+ </button>++ <button+ onClick={() => setView('marketplace')}+ style={{+ backgroundColor: view === 'marketplace' ? ORANGE : 'transparent',+ color: view === 'marketplace' ? 'black' : WHITE,+ border: `1px solid ${view === 'marketplace' ? ORANGE : BORDER}`,+ padding: '6px 12px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '3px',+ fontWeight: 'bold'+ }}+ >+ MARKETPLACE+ </button>+ <button+ onClick={() => setView('installed')}+ style={{+ backgroundColor: view === 'installed' ? ORANGE : 'transparent',+ color: view === 'installed' ? 'black' : WHITE,+ border: `1px solid ${view === 'installed' ? ORANGE : BORDER}`,+ padding: '6px 12px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '3px',+ fontWeight: 'bold'+ }}+ >+ MY SERVERS ({servers.length})+ </button>++ <button+ onClick={() => setIsAddModalOpen(true)}+ style={{+ backgroundColor: GREEN,+ color: 'black',+ border: 'none',+ padding: '6px 12px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <Plus size={12} />+ CUSTOM+ </button>+ </div></div>- </div>- {/* Main Content */}- <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>- {/* Left Panel: Installed Servers */}- <div style={{- width: '50%',- borderRight: `1px solid ${BLOOMBERG_GRAY}`,- display: 'flex',- flexDirection: 'column',- overflow: 'hidden'- }}>- <div style={{- padding: '8px 12px',- backgroundColor: BLOOMBERG_PANEL_BG,- borderBottom: `1px solid ${BLOOMBERG_GRAY}`,- flexShrink: 0- }}>- <span style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>- INSTALLED SERVERS ({servers.length})- </span>+ {/* Search Bar (only for installed view) */}+ {view === 'installed' && servers.length > 0 && (+ <div style={{ position: 'relative' }}>+ <Search+ size={14}+ style={{+ position: 'absolute',+ left: '10px',+ top: '50%',+ transform: 'translateY(-50%)',+ color: GRAY,+ }}+ />+ <input+ type="text"+ placeholder="Search installed servers..."+ value={searchTerm}+ onChange={(e) => setSearchTerm(e.target.value)}+ style={{+ width: '100%',+ backgroundColor: DARK_BG,+ border: `1px solid ${BORDER}`,+ color: WHITE,+ padding: '8px 12px 8px 36px',+ fontSize: '11px',+ borderRadius: '4px',+ outline: 'none',+ }}+ /></div>+ )}+ </div>++ {/* Content Area */}+ <div style={{+ flex: 1,+ overflow: 'auto',+ padding: '16px',+ scrollbarWidth: 'none',+ msOverflowStyle: 'none',+ }}>+ <style>{`+ div::-webkit-scrollbar {+ display: none;+ }+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>- <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>- {servers.length === 0 ? (+ {view === 'marketplace' ? (+ /* Marketplace View */+ <MCPMarketplace onInstall={handleInstallServer} installedServers={servers} />+ ) : (+ /* Installed Servers View */+ <div>+ {filteredServers.length === 0 ? (<div style={{textAlign: 'center',- color: BLOOMBERG_GRAY,- padding: '40px 20px',- fontSize: '10px'+ padding: '60px 20px',+ color: GRAY,}}>- <div style={{ marginBottom: '8px' }}>No MCP servers installed.</div>- <div>Install from marketplace or add a custom server.</div>+ <Zap size={48} style={{ marginBottom: '16px', opacity: 0.3, color: ORANGE }} />+ <h3 style={{ fontSize: '14px', marginBottom: '8px', color: WHITE }}>+ {searchTerm ? 'No servers found' : 'No MCP servers installed'}+ </h3>+ <p style={{ fontSize: '11px', marginBottom: '16px' }}>+ {searchTerm ? 'Try a different search term' : 'Install your first MCP server from the marketplace'}+ </p>+ {!searchTerm && (+ <button+ onClick={() => setView('marketplace')}+ style={{+ backgroundColor: ORANGE,+ color: 'black',+ border: 'none',+ padding: '8px 16px',+ fontSize: '11px',+ cursor: 'pointer',+ borderRadius: '4px',+ fontWeight: 'bold',+ }}+ >+ BROWSE MARKETPLACE+ </button>+ )}</div>) : (- servers.map(server => {- const healthInfo = mcpManager.getServerHealthInfo(server.id);- return (- <MCPServerCard- key={server.id}- server={server}- onStart={() => handleStartServer(server.id)}- onStop={() => handleStopServer(server.id)}- onRemove={() => handleRemoveServer(server.id)}- onToggleAutoStart={(enabled) => handleToggleAutoStart(server.id, enabled)}- healthInfo={healthInfo}- />- );- })+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))',+ gap: '16px',+ }}>+ {filteredServers.map(server => {+ const healthInfo = mcpManager.getServerHealthInfo(server.id);+ return (+ <div+ key={server.id}+ style={{+ backgroundColor: PANEL_BG,+ border: `1px solid ${BORDER}`,+ borderRadius: '6px',+ padding: '16px',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = ORANGE;+ e.currentTarget.style.boxShadow = `0 0 12px ${ORANGE}40`;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = BORDER;+ e.currentTarget.style.boxShadow = 'none';+ }}+ >+ {/* Server Header */}+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px', marginBottom: '12px' }}>+ <span style={{ fontSize: '28px' }}>{server.icon}</span>+ <div style={{ flex: 1 }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>+ <h3 style={{+ color: WHITE,+ fontSize: '13px',+ fontWeight: 'bold',+ }}>+ {server.name}+ </h3>+ {getStatusIcon(server.status)}+ </div>+ <div style={{+ display: 'inline-block',+ backgroundColor: `${getStatusColor(server.status)}20`,+ color: getStatusColor(server.status),+ padding: '2px 8px',+ fontSize: '9px',+ borderRadius: '3px',+ textTransform: 'uppercase',+ fontWeight: 'bold',+ }}>+ {server.status}+ </div>+ </div>+ </div>++ {/* Description */}+ <p style={{+ color: GRAY,+ fontSize: '10px',+ lineHeight: '1.5',+ marginBottom: '12px',+ }}>+ {server.description}+ </p>++ {/* Stats */}+ <div style={{+ display: 'flex',+ gap: '16px',+ marginBottom: '12px',+ fontSize: '10px',+ color: GRAY,+ }}>+ <div>+ <span style={{ color: WHITE, fontWeight: 'bold' }}>{server.toolCount}</span> tools+ </div>+ <div>+ <span style={{ color: WHITE, fontWeight: 'bold' }}>{server.callsToday}</span> calls today+ </div>+ {server.auto_start && (+ <div style={{ color: GREEN }}>+ <Zap size={10} style={{ display: 'inline', marginRight: '4px' }} />+ Auto-start+ </div>+ )}+ </div>++ {/* Error Message */}+ {healthInfo && healthInfo.errorCount > 0 && (+ <div style={{+ padding: '8px',+ backgroundColor: `${RED}20`,+ border: `1px solid ${RED}`,+ borderRadius: '4px',+ fontSize: '9px',+ color: RED,+ marginBottom: '12px',+ }}>+ <strong>Errors: {healthInfo.errorCount}</strong>+ {healthInfo.lastError && (+ <div style={{ marginTop: '4px' }}>{healthInfo.lastError}</div>+ )}+ </div>+ )}++ {/* Actions */}+ <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>+ {server.status === 'running' ? (+ <button+ onClick={() => handleStopServer(server.id)}+ style={{+ backgroundColor: 'transparent',+ color: YELLOW,+ border: `1px solid ${YELLOW}`,+ padding: '6px 10px',+ fontSize: '9px',+ cursor: 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ fontWeight: 'bold',+ }}+ >+ <Square size={10} />+ STOP+ </button>+ ) : (+ <button+ onClick={() => handleStartServer(server.id)}+ style={{+ backgroundColor: 'transparent',+ color: GREEN,+ border: `1px solid ${GREEN}`,+ padding: '6px 10px',+ fontSize: '9px',+ cursor: 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ fontWeight: 'bold',+ }}+ >+ <Play size={10} />+ START+ </button>+ )}++ <button+ onClick={() => handleToggleAutoStart(server.id, !server.auto_start)}+ style={{+ backgroundColor: 'transparent',+ color: server.auto_start ? ORANGE : GRAY,+ border: `1px solid ${server.auto_start ? ORANGE : '#404040'}`,+ padding: '6px 10px',+ fontSize: '9px',+ cursor: 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ fontWeight: 'bold',+ }}+ >+ <Zap size={10} />+ AUTO+ </button>++ <button+ onClick={() => handleRemoveServer(server.id)}+ style={{+ backgroundColor: 'transparent',+ color: RED,+ border: `1px solid ${RED}`,+ padding: '6px 10px',+ fontSize: '9px',+ cursor: 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ fontWeight: 'bold',+ }}+ >+ <Trash2 size={10} />+ REMOVE+ </button>+ </div>+ </div>+ );+ })}+ </div>)}</div>- </div>-- {/* Right Panel: Marketplace */}- <div style={{ width: '50%', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>- <MCPMarketplace onInstall={handleInstallServer} />- </div>+ )}</div>- {/* Bottom Panel: Available Tools */}+ {/* Tools Footer */}<div style={{- height: '140px',- borderTop: `1px solid ${BLOOMBERG_GRAY}`,- backgroundColor: BLOOMBERG_PANEL_BG,+ height: '120px',+ borderTop: `1px solid ${BORDER}`,+ backgroundColor: PANEL_BG,overflow: 'auto',- padding: '8px',- flexShrink: 0+ padding: '12px 16px',+ flexShrink: 0,+ scrollbarWidth: 'none',+ msOverflowStyle: 'none',}}>- <div style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '6px' }}>+ <div style={{+ color: ORANGE,+ fontSize: '11px',+ fontWeight: 'bold',+ marginBottom: '8px',+ letterSpacing: '0.5px'+ }}>AVAILABLE TOOLS ({tools.length})</div>{tools.length === 0 ? (- <div style={{ color: BLOOMBERG_GRAY, fontSize: '10px', textAlign: 'center', padding: '20px' }}>+ <div style={{ color: GRAY, fontSize: '10px', textAlign: 'center', padding: '20px' }}>No tools available. Start an MCP server to see its tools.</div>) : (- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px' }}>+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '8px' }}>{tools.map(tool => (<divkey={tool.id}style={{- backgroundColor: BLOOMBERG_DARK_BG,- border: `1px solid ${BLOOMBERG_GRAY}`,- padding: '4px 6px',- fontSize: '9px'+ backgroundColor: DARK_BG,+ border: `1px solid ${BORDER}`,+ padding: '6px 8px',+ fontSize: '9px',+ borderRadius: '3px',}}>- <div style={{ display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '2px' }}>- <span style={{ color: BLOOMBERG_ORANGE }}>🔧</span>- <span style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>{tool.name}</span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '2px' }}>+ <Settings size={10} style={{ color: ORANGE }} />+ <span style={{ color: WHITE, fontWeight: 'bold' }}>{tool.name}</span></div>{tool.description && (- <div style={{ color: BLOOMBERG_GRAY, fontSize: '8px' }}>- {tool.description.substring(0, 60)}{tool.description.length > 60 ? '...' : ''}+ <div style={{ color: GRAY, fontSize: '8px', marginLeft: '16px' }}>+ {tool.description.substring(0, 50)}{tool.description.length > 50 ? '...' : ''}</div>)}</div>@@ -311,14 +615,18 @@ const MCPTab: React.FC = () => {{/* Status Bar */}<div style={{- backgroundColor: BLOOMBERG_PANEL_BG,- borderTop: `1px solid ${BLOOMBERG_GRAY}`,- padding: '4px 12px',+ backgroundColor: DARK_BG,+ borderTop: `1px solid ${BORDER}`,+ padding: '6px 16px',fontSize: '9px',- color: BLOOMBERG_GRAY,- flexShrink: 0+ color: GRAY,+ flexShrink: 0,+ display: 'flex',+ alignItems: 'center',+ gap: '8px'}}>- STATUS: {statusMessage}+ <span style={{ color: ORANGE }}>●</span>+ {statusMessage}</div>{/* Add Server Modal */}@@ -331,13 +639,6 @@ const MCPTab: React.FC = () => {}}/>)}-- <style>{`- @keyframes spin {- from { transform: rotate(0deg); }- to { transform: rotate(360deg); }- }- `}</style></div>);};diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/MCPMarketplace.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/MCPMarketplace.tsxnew file mode 100644index 000000000..269dd9f2b--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/MCPMarketplace.tsx@@ -0,0 +1,401 @@+// MCP Marketplace Component+// Browse and install curated MCP servers++import React, { useState } from 'react';+import { Search, Download, Zap, CheckCircle } from 'lucide-react';+import { MARKETPLACE_SERVERS, MCPServerDefinition } from './serverDefinitions';+import { MCPServerWithStats } from '../../../../services/mcpManager';+import PostgresForm from './forms/PostgresForm';+import QuestDBForm from './forms/QuestDBForm';+import GenericForm from './forms/GenericForm';++interface MCPMarketplaceProps {+ onInstall: (serverConfig: any) => void;+ installedServers: MCPServerWithStats[];+}++const MCPMarketplace: React.FC<MCPMarketplaceProps> = ({ onInstall, installedServers }) => {+ const [searchQuery, setSearchQuery] = useState('');+ const [selectedCategory, setSelectedCategory] = useState<string>('all');+ const [configureServer, setConfigureServer] = useState<MCPServerDefinition | null>(null);++ // Bloomberg colors+ const ORANGE = '#FFA500';+ const WHITE = '#FFFFFF';+ const GRAY = '#787878';+ const DARK_BG = '#0a0a0a';+ const PANEL_BG = '#1a1a1a';+ const BORDER = '#2d2d2d';+ const GREEN = '#10b981';+ const YELLOW = '#FFFF00';++ // Check if server is already installed+ const isServerInstalled = (serverId: string) => {+ return installedServers.some(s => s.id === serverId);+ };++ const filteredServers = MARKETPLACE_SERVERS.filter(server => {+ const matchesSearch = server.name.toLowerCase().includes(searchQuery.toLowerCase()) ||+ server.description.toLowerCase().includes(searchQuery.toLowerCase());+ const matchesCategory = selectedCategory === 'all' || server.category === selectedCategory;+ return matchesSearch && matchesCategory;+ });++ const categories = ['all', 'data', 'web', 'productivity', 'dev'];+ const categoryLabels = {+ all: 'ALL',+ data: 'DATA',+ web: 'WEB',+ productivity: 'TOOLS',+ dev: 'DEV'+ };++ const handleInstallClick = (server: MCPServerDefinition) => {+ if (server.requiresConfig) {+ setConfigureServer(server);+ } else {+ onInstall(server);+ }+ };++ const handleConfiguredInstall = (config: { args: string[]; env: Record<string, string> }) => {+ if (configureServer) {+ const serverWithConfig = {+ ...configureServer,+ args: [...configureServer.args, ...config.args],+ env: config.env+ };++ onInstall(serverWithConfig);+ setConfigureServer(null);+ }+ };++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>+ {/* Search and Filters */}+ <div style={{ marginBottom: '16px' }}>+ <div style={{ position: 'relative', marginBottom: '12px' }}>+ <Search+ size={14}+ style={{+ position: 'absolute',+ left: '10px',+ top: '50%',+ transform: 'translateY(-50%)',+ color: GRAY,+ }}+ />+ <input+ type="text"+ placeholder="Search marketplace..."+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ style={{+ width: '100%',+ backgroundColor: DARK_BG,+ border: `1px solid ${BORDER}`,+ color: WHITE,+ padding: '8px 12px 8px 36px',+ fontSize: '11px',+ borderRadius: '4px',+ outline: 'none',+ }}+ />+ </div>++ {/* Categories */}+ <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>+ {categories.map(cat => (+ <button+ key={cat}+ onClick={() => setSelectedCategory(cat)}+ style={{+ backgroundColor: selectedCategory === cat ? BORDER : 'transparent',+ color: selectedCategory === cat ? ORANGE : GRAY,+ border: `1px solid ${selectedCategory === cat ? ORANGE : BORDER}`,+ padding: '6px 12px',+ fontSize: '10px',+ cursor: 'pointer',+ borderRadius: '3px',+ textTransform: 'uppercase',+ fontWeight: selectedCategory === cat ? 'bold' : 'normal',+ }}+ >+ {categoryLabels[cat as keyof typeof categoryLabels]}+ </button>+ ))}+ </div>+ </div>++ {/* Server Grid */}+ <div style={{ flex: 1, overflow: 'auto', scrollbarWidth: 'none', msOverflowStyle: 'none' }}>+ {filteredServers.length === 0 ? (+ <div style={{+ textAlign: 'center',+ color: GRAY,+ padding: '60px 20px',+ fontSize: '11px'+ }}>+ <Zap size={48} style={{ marginBottom: '16px', opacity: 0.3, color: ORANGE }} />+ <div style={{ marginBottom: '8px' }}>No servers found matching your search.</div>+ <div>Try a different search term or category.</div>+ </div>+ ) : (+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',+ gap: '16px',+ }}>+ {filteredServers.map(server => {+ const installed = isServerInstalled(server.id);+ return (+ <div+ key={server.id}+ style={{+ backgroundColor: PANEL_BG,+ border: `1px solid ${BORDER}`,+ borderRadius: '6px',+ padding: '16px',+ cursor: installed ? 'default' : 'pointer',+ transition: 'all 0.2s',+ display: 'flex',+ flexDirection: 'column',+ minHeight: '280px',+ }}+ onMouseEnter={(e) => {+ if (!installed) {+ e.currentTarget.style.borderColor = ORANGE;+ e.currentTarget.style.boxShadow = `0 0 12px ${ORANGE}40`;+ }+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = BORDER;+ e.currentTarget.style.boxShadow = 'none';+ }}+ >+ {/* Server Header */}+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px', marginBottom: '12px' }}>+ <span style={{ fontSize: '32px' }}>{server.icon}</span>+ <div style={{ flex: 1 }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>+ <h3 style={{+ color: WHITE,+ fontSize: '13px',+ fontWeight: 'bold',+ }}>+ {server.name}+ </h3>+ {installed && <CheckCircle size={14} color={GREEN} />}+ </div>+ <div style={{+ display: 'inline-block',+ backgroundColor: `${ORANGE}20`,+ color: ORANGE,+ padding: '2px 8px',+ fontSize: '9px',+ borderRadius: '3px',+ textTransform: 'uppercase',+ fontWeight: 'bold',+ }}>+ {server.category}+ </div>+ </div>+ </div>++ {/* Description */}+ <p style={{+ color: GRAY,+ fontSize: '11px',+ lineHeight: '1.5',+ marginBottom: '12px',+ flex: 1,+ }}>+ {server.description}+ </p>++ {/* Fixed height container for badges and info */}+ <div style={{ marginBottom: '12px', minHeight: '60px' }}>+ {/* Requires Config Badge */}+ {server.requiresConfig && (+ <div style={{+ backgroundColor: `${YELLOW}20`,+ color: YELLOW,+ padding: '4px 8px',+ fontSize: '9px',+ borderRadius: '3px',+ marginBottom: '8px',+ display: 'inline-block',+ }}>+ ⚙️ Requires Configuration+ </div>+ )}++ {/* Tools Count */}+ <div style={{+ color: GRAY,+ fontSize: '10px',+ marginBottom: '8px',+ }}>+ <span style={{ color: WHITE, fontWeight: 'bold' }}>{server.tools.length}</span> tools available+ </div>++ {/* Command Preview */}+ <div style={{+ backgroundColor: DARK_BG,+ border: `1px solid ${BORDER}`,+ padding: '6px 8px',+ fontSize: '9px',+ borderRadius: '3px',+ color: GRAY,+ fontFamily: 'monospace',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}>+ {server.command} {server.args.join(' ')}+ </div>+ </div>++ {/* Install Button - Always at bottom */}+ {installed ? (+ <button+ disabled+ style={{+ width: '100%',+ backgroundColor: `${GREEN}30`,+ color: GREEN,+ border: `1px solid ${GREEN}`,+ padding: '8px 12px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: 'not-allowed',+ borderRadius: '4px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ }}+ >+ <CheckCircle size={12} />+ INSTALLED+ </button>+ ) : (+ <button+ onClick={() => handleInstallClick(server)}+ style={{+ width: '100%',+ backgroundColor: GREEN,+ color: 'black',+ border: 'none',+ padding: '8px 12px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: 'pointer',+ borderRadius: '4px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ }}+ >+ <Download size={12} />+ {server.requiresConfig ? 'CONFIGURE & INSTALL' : 'INSTALL NOW'}+ </button>+ )}++ {/* Documentation Link */}+ {server.documentation && (+ <div style={{ marginTop: '8px', textAlign: 'center' }}>+ <a+ href={server.documentation}+ target="_blank"+ rel="noopener noreferrer"+ style={{+ color: GRAY,+ fontSize: '9px',+ textDecoration: 'none',+ }}+ onClick={(e) => e.stopPropagation()}+ >+ View Documentation →+ </a>+ </div>+ )}+ </div>+ );+ })}+ </div>+ )}+ </div>++ {/* Configuration Modal */}+ {configureServer && (+ <div style={{+ position: 'fixed',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(0, 0, 0, 0.85)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 1000+ }}>+ <div style={{+ backgroundColor: PANEL_BG,+ border: `2px solid ${ORANGE}`,+ borderRadius: '8px',+ width: '90%',+ maxWidth: '600px',+ maxHeight: '80vh',+ overflow: 'auto',+ scrollbarWidth: 'none',+ msOverflowStyle: 'none',+ }}>+ {/* Modal Header */}+ <div style={{+ padding: '16px',+ borderBottom: `1px solid ${BORDER}`,+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ }}>+ <span style={{ fontSize: '32px' }}>{configureServer.icon}</span>+ <div>+ <h2 style={{ color: WHITE, fontSize: '16px', fontWeight: 'bold' }}>+ Configure {configureServer.name}+ </h2>+ <p style={{ color: GRAY, fontSize: '11px' }}>{configureServer.description}</p>+ </div>+ </div>++ {/* Form */}+ <div style={{ padding: '16px' }}>+ {configureServer.id === 'postgres' ? (+ <PostgresForm+ onSubmit={handleConfiguredInstall}+ onCancel={() => setConfigureServer(null)}+ />+ ) : configureServer.id === 'questdb' ? (+ <QuestDBForm+ onSubmit={handleConfiguredInstall}+ onCancel={() => setConfigureServer(null)}+ />+ ) : (+ <GenericForm+ server={configureServer}+ onSubmit={handleConfiguredInstall}+ onCancel={() => setConfigureServer(null)}+ />+ )}+ </div>+ </div>+ </div>+ )}+ </div>+ );+};++export default MCPMarketplace;diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/forms/GenericForm.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/forms/GenericForm.tsxnew file mode 100644index 000000000..6392b28c2--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/forms/GenericForm.tsx@@ -0,0 +1,157 @@+// Generic Configuration Form+// Fallback form for MCP servers that don't have custom forms+// Allows users to configure environment variables in KEY=VALUE format++import React, { useState } from 'react';+import { MCPServerDefinition } from '../serverDefinitions';++interface GenericFormProps {+ server: MCPServerDefinition;+ onSubmit: (config: { args: string[]; env: Record<string, string> }) => void;+ onCancel: () => void;+}++const GenericForm: React.FC<GenericFormProps> = ({ server, onSubmit, onCancel }) => {+ const [envValues, setEnvValues] = useState<Record<string, string>>(+ server.env || {}+ );++ const BLOOMBERG_ORANGE = '#FFA500';+ const BLOOMBERG_WHITE = '#FFFFFF';+ const BLOOMBERG_GRAY = '#787878';+ const BLOOMBERG_DARK_BG = '#000000';++ const handleSubmit = () => {+ // Check if all required env vars are filled+ const allFilled = Object.values(envValues).every(v => v.trim());++ if (!allFilled) {+ alert('Please fill in all required fields');+ return;+ }++ onSubmit({+ args: server.requiresArg && envValues[server.requiresArg]+ ? [envValues[server.requiresArg]]+ : [],+ env: server.requiresArg+ ? {}+ : envValues+ });+ };++ return (+ <div>+ <div style={{+ color: BLOOMBERG_WHITE,+ fontSize: '10px',+ marginBottom: '12px'+ }}>+ {server.description}+ </div>++ {server.env && Object.keys(server.env).length > 0 && (+ <>+ {Object.keys(server.env).map(key => (+ <div key={key} style={{ marginBottom: '12px' }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG_ORANGE,+ fontSize: '10px',+ marginBottom: '4px',+ fontWeight: 'bold'+ }}>+ {key}+ </label>+ <input+ type="text"+ value={envValues[key] || ''}+ onChange={(e) => setEnvValues({...envValues, [key]: e.target.value})}+ placeholder={`Enter ${key}`}+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>+ ))}+ </>+ )}++ {server.requiresArg && (+ <div style={{ marginBottom: '12px' }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG_ORANGE,+ fontSize: '10px',+ marginBottom: '4px',+ fontWeight: 'bold'+ }}>+ {server.requiresArg} *+ </label>+ <input+ type="text"+ value={envValues[server.requiresArg] || ''}+ onChange={(e) => setEnvValues({...envValues, [server.requiresArg!]: e.target.value})}+ placeholder={`Enter ${server.requiresArg}`}+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>+ )}++ {/* Actions */}+ <div style={{+ display: 'flex',+ gap: '8px',+ justifyContent: 'flex-end',+ marginTop: '16px',+ paddingTop: '12px',+ borderTop: `1px solid ${BLOOMBERG_GRAY}`+ }}>+ <button+ onClick={onCancel}+ style={{+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px 12px',+ fontSize: '10px',+ cursor: 'pointer'+ }}+ >+ CANCEL+ </button>+ <button+ onClick={handleSubmit}+ disabled={!Object.values(envValues).every(v => v.trim())}+ style={{+ backgroundColor: Object.values(envValues).every(v => v.trim()) ? BLOOMBERG_ORANGE : BLOOMBERG_GRAY,+ border: 'none',+ color: 'black',+ padding: '6px 12px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: Object.values(envValues).every(v => v.trim()) ? 'pointer' : 'not-allowed'+ }}+ >+ INSTALL+ </button>+ </div>+ </div>+ );+};++export default GenericForm;diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/forms/PostgresForm.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/forms/PostgresForm.tsxnew file mode 100644index 000000000..3e8b389f1--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/forms/PostgresForm.tsx@@ -0,0 +1,278 @@+// PostgreSQL Configuration Form+// Collects connection details and builds a PostgreSQL connection string++import React, { useState } from 'react';++interface PostgresFormProps {+ onSubmit: (config: { args: string[]; env: Record<string, string> }) => void;+ onCancel: () => void;+}++const PostgresForm: React.FC<PostgresFormProps> = ({ onSubmit, onCancel }) => {+ const [pgHost, setPgHost] = useState('localhost');+ const [pgPort, setPgPort] = useState('5432');+ const [pgUser, setPgUser] = useState('postgres');+ const [pgPassword, setPgPassword] = useState('');+ const [pgDatabase, setPgDatabase] = useState('postgres');+ const [pgSsl, setPgSsl] = useState(false);++ const BLOOMBERG_ORANGE = '#FFA500';+ const BLOOMBERG_WHITE = '#FFFFFF';+ const BLOOMBERG_GRAY = '#787878';+ const BLOOMBERG_DARK_BG = '#000000';+ const BLOOMBERG_YELLOW = '#FFFF00';++ const buildPostgresUrl = () => {+ const encodedPassword = encodeURIComponent(pgPassword);+ const sslParam = pgSsl ? '?sslmode=require' : '';+ return `postgresql://${pgUser}:${encodedPassword}@${pgHost}:${pgPort}/${pgDatabase}${sslParam}`;+ };++ const handleSubmit = () => {+ const dbUrl = buildPostgresUrl();+ onSubmit({+ args: [dbUrl],+ env: {}+ });+ };++ return (+ <div>+ <div style={{+ color: BLOOMBERG_WHITE,+ fontSize: '10px',+ marginBottom: '12px'+ }}>+ Configure your PostgreSQL database connection. The connection string will be passed securely to the MCP server.+ </div>++ {/* Host */}+ <div style={{ marginBottom: '12px' }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG_ORANGE,+ fontSize: '10px',+ marginBottom: '4px',+ fontWeight: 'bold'+ }}>+ HOST+ </label>+ <input+ type="text"+ value={pgHost}+ onChange={(e) => setPgHost(e.target.value)}+ placeholder="localhost"+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>++ {/* Port and Database */}+ <div style={{ display: 'flex', gap: '8px', marginBottom: '12px' }}>+ <div style={{ flex: 1 }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG_ORANGE,+ fontSize: '10px',+ marginBottom: '4px',+ fontWeight: 'bold'+ }}>+ PORT+ </label>+ <input+ type="text"+ value={pgPort}+ onChange={(e) => setPgPort(e.target.value)}+ placeholder="5432"+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>++ <div style={{ flex: 1 }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG_ORANGE,+ fontSize: '10px',+ marginBottom: '4px',+ fontWeight: 'bold'+ }}>+ DATABASE+ </label>+ <input+ type="text"+ value={pgDatabase}+ onChange={(e) => setPgDatabase(e.target.value)}+ placeholder="postgres"+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>+ </div>++ {/* Username */}+ <div style={{ marginBottom: '12px' }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG_ORANGE,+ fontSize: '10px',+ marginBottom: '4px',+ fontWeight: 'bold'+ }}>+ USERNAME+ </label>+ <input+ type="text"+ value={pgUser}+ onChange={(e) => setPgUser(e.target.value)}+ placeholder="postgres"+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>++ {/* Password */}+ <div style={{ marginBottom: '12px' }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG_ORANGE,+ fontSize: '10px',+ marginBottom: '4px',+ fontWeight: 'bold'+ }}>+ PASSWORD *+ </label>+ <input+ type="password"+ value={pgPassword}+ onChange={(e) => setPgPassword(e.target.value)}+ placeholder="Enter database password"+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${pgPassword ? BLOOMBERG_ORANGE : BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>++ {/* SSL */}+ <div style={{ marginBottom: '12px' }}>+ <label style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ color: BLOOMBERG_WHITE,+ fontSize: '10px',+ cursor: 'pointer'+ }}>+ <input+ type="checkbox"+ checked={pgSsl}+ onChange={(e) => setPgSsl(e.target.checked)}+ style={{ cursor: 'pointer' }}+ />+ Require SSL Connection+ </label>+ </div>++ {/* Connection String Preview */}+ <div style={{+ marginTop: '12px',+ padding: '8px',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ borderRadius: '2px'+ }}>+ <div style={{+ color: BLOOMBERG_GRAY,+ fontSize: '8px',+ marginBottom: '4px',+ fontWeight: 'bold'+ }}>+ CONNECTION STRING PREVIEW:+ </div>+ <div style={{+ color: BLOOMBERG_YELLOW,+ fontSize: '9px',+ fontFamily: 'Consolas, monospace',+ wordBreak: 'break-all'+ }}>+ {buildPostgresUrl()}+ </div>+ </div>++ {/* Actions */}+ <div style={{+ display: 'flex',+ gap: '8px',+ justifyContent: 'flex-end',+ marginTop: '16px',+ paddingTop: '12px',+ borderTop: `1px solid ${BLOOMBERG_GRAY}`+ }}>+ <button+ onClick={onCancel}+ style={{+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px 12px',+ fontSize: '10px',+ cursor: 'pointer'+ }}+ >+ CANCEL+ </button>+ <button+ onClick={handleSubmit}+ disabled={!pgPassword.trim()}+ style={{+ backgroundColor: pgPassword.trim() ? BLOOMBERG_ORANGE : BLOOMBERG_GRAY,+ border: 'none',+ color: 'black',+ padding: '6px 12px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: pgPassword.trim() ? 'pointer' : 'not-allowed'+ }}+ >+ INSTALL+ </button>+ </div>+ </div>+ );+};++export default PostgresForm;diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/forms/QuestDBForm.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/forms/QuestDBForm.tsxnew file mode 100644index 000000000..5e809bff4--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/forms/QuestDBForm.tsx@@ -0,0 +1,278 @@+// QuestDB Configuration Form+// Collects connection details for QuestDB time-series database++import React, { useState } from 'react';++interface QuestDBFormProps {+ onSubmit: (config: { args: string[]; env: Record<string, string> }) => void;+ onCancel: () => void;+}++const QuestDBForm: React.FC<QuestDBFormProps> = ({ onSubmit, onCancel }) => {+ const [qdbHost, setQdbHost] = useState('localhost');+ const [qdbPort, setQdbPort] = useState('8812'); // QuestDB default PostgreSQL wire protocol port+ const [qdbUser, setQdbUser] = useState('admin');+ const [qdbPassword, setQdbPassword] = useState('');+ const [qdbDatabase, setQdbDatabase] = useState('qdb');+ const [qdbSsl, setQdbSsl] = useState(false);++ const BLOOMBERG_ORANGE = '#FFA500';+ const BLOOMBERG_WHITE = '#FFFFFF';+ const BLOOMBERG_GRAY = '#787878';+ const BLOOMBERG_DARK_BG = '#000000';+ const BLOOMBERG_YELLOW = '#FFFF00';++ const buildQuestDBUrl = () => {+ const encodedPassword = encodeURIComponent(qdbPassword);+ const sslParam = qdbSsl ? '?sslmode=require' : '';+ return `postgresql://${qdbUser}:${encodedPassword}@${qdbHost}:${qdbPort}/${qdbDatabase}${sslParam}`;+ };++ const handleSubmit = () => {+ const dbUrl = buildQuestDBUrl();+ onSubmit({+ args: [dbUrl],+ env: {}+ });+ };++ return (+ <div>+ <div style={{+ color: BLOOMBERG_WHITE,+ fontSize: '10px',+ marginBottom: '12px'+ }}>+ Configure your QuestDB connection. QuestDB uses PostgreSQL wire protocol (default port 8812).+ </div>++ {/* Host */}+ <div style={{ marginBottom: '12px' }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG_ORANGE,+ fontSize: '10px',+ marginBottom: '4px',+ fontWeight: 'bold'+ }}>+ HOST+ </label>+ <input+ type="text"+ value={qdbHost}+ onChange={(e) => setQdbHost(e.target.value)}+ placeholder="localhost"+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>++ {/* Port and Database */}+ <div style={{ display: 'flex', gap: '8px', marginBottom: '12px' }}>+ <div style={{ flex: 1 }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG_ORANGE,+ fontSize: '10px',+ marginBottom: '4px',+ fontWeight: 'bold'+ }}>+ PORT+ </label>+ <input+ type="text"+ value={qdbPort}+ onChange={(e) => setQdbPort(e.target.value)}+ placeholder="8812"+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>++ <div style={{ flex: 1 }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG_ORANGE,+ fontSize: '10px',+ marginBottom: '4px',+ fontWeight: 'bold'+ }}>+ DATABASE+ </label>+ <input+ type="text"+ value={qdbDatabase}+ onChange={(e) => setQdbDatabase(e.target.value)}+ placeholder="qdb"+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>+ </div>++ {/* Username */}+ <div style={{ marginBottom: '12px' }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG_ORANGE,+ fontSize: '10px',+ marginBottom: '4px',+ fontWeight: 'bold'+ }}>+ USERNAME+ </label>+ <input+ type="text"+ value={qdbUser}+ onChange={(e) => setQdbUser(e.target.value)}+ placeholder="admin"+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>++ {/* Password */}+ <div style={{ marginBottom: '12px' }}>+ <label style={{+ display: 'block',+ color: BLOOMBERG_ORANGE,+ fontSize: '10px',+ marginBottom: '4px',+ fontWeight: 'bold'+ }}>+ PASSWORD *+ </label>+ <input+ type="password"+ value={qdbPassword}+ onChange={(e) => setQdbPassword(e.target.value)}+ placeholder="Enter database password"+ style={{+ width: '100%',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${qdbPassword ? BLOOMBERG_ORANGE : BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>++ {/* SSL */}+ <div style={{ marginBottom: '12px' }}>+ <label style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ color: BLOOMBERG_WHITE,+ fontSize: '10px',+ cursor: 'pointer'+ }}>+ <input+ type="checkbox"+ checked={qdbSsl}+ onChange={(e) => setQdbSsl(e.target.checked)}+ style={{ cursor: 'pointer' }}+ />+ Require SSL Connection+ </label>+ </div>++ {/* Connection String Preview */}+ <div style={{+ marginTop: '12px',+ padding: '8px',+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ borderRadius: '2px'+ }}>+ <div style={{+ color: BLOOMBERG_GRAY,+ fontSize: '8px',+ marginBottom: '4px',+ fontWeight: 'bold'+ }}>+ CONNECTION STRING PREVIEW:+ </div>+ <div style={{+ color: BLOOMBERG_YELLOW,+ fontSize: '9px',+ fontFamily: 'Consolas, monospace',+ wordBreak: 'break-all'+ }}>+ {buildQuestDBUrl()}+ </div>+ </div>++ {/* Actions */}+ <div style={{+ display: 'flex',+ gap: '8px',+ justifyContent: 'flex-end',+ marginTop: '16px',+ paddingTop: '12px',+ borderTop: `1px solid ${BLOOMBERG_GRAY}`+ }}>+ <button+ onClick={onCancel}+ style={{+ backgroundColor: BLOOMBERG_DARK_BG,+ border: `1px solid ${BLOOMBERG_GRAY}`,+ color: BLOOMBERG_WHITE,+ padding: '6px 12px',+ fontSize: '10px',+ cursor: 'pointer'+ }}+ >+ CANCEL+ </button>+ <button+ onClick={handleSubmit}+ disabled={!qdbPassword.trim()}+ style={{+ backgroundColor: qdbPassword.trim() ? BLOOMBERG_ORANGE : BLOOMBERG_GRAY,+ border: 'none',+ color: 'black',+ padding: '6px 12px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: qdbPassword.trim() ? 'pointer' : 'not-allowed'+ }}+ >+ INSTALL+ </button>+ </div>+ </div>+ );+};++export default QuestDBForm;diff --git a/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/serverDefinitions.ts b/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/serverDefinitions.tsnew file mode 100644index 000000000..d10c664fe--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/mcp/marketplace/serverDefinitions.ts@@ -0,0 +1,90 @@+// MCP Server Definitions+// Add new MCP servers here following the structure below++export interface MCPServerDefinition {+ id: string;+ name: string;+ description: string;+ category: 'data' | 'web' | 'productivity' | 'dev' | 'custom';+ icon: string;+ command: string;+ args: string[];+ env?: Record<string, string>;+ requiresArg?: string; // If the server needs a CLI argument instead of env var+ requiresConfig: boolean; // Whether it needs a custom configuration form+ tools: string[]; // List of available tools (for display purposes)+ documentation?: string; // Link to MCP server documentation+}++/**+ * Curated MCP servers available in the marketplace+ * Only PostgreSQL and QuestDB are currently implemented+ */+export const MARKETPLACE_SERVERS: MCPServerDefinition[] = [+ {+ id: 'postgres',+ name: 'PostgreSQL',+ description: 'Connect to PostgreSQL databases for SQL queries and analysis',+ category: 'data',+ icon: '🐘',+ command: 'bunx',+ args: ['-y', '@modelcontextprotocol/server-postgres'],+ requiresArg: 'DATABASE_URL', // Connection string passed as CLI argument+ requiresConfig: true, // Uses PostgresForm.tsx+ tools: ['query', 'describe_table', 'list_tables', 'explain_query', 'get_indexes'],+ documentation: 'https://github.com/modelcontextprotocol/servers/tree/main/src/postgres'+ },+ {+ id: 'questdb',+ name: 'QuestDB',+ description: 'Connect to QuestDB time-series databases for fast analytics',+ category: 'data',+ icon: '⚡',+ command: 'bunx',+ args: ['-y', '@questdb/mcp-server'],+ requiresArg: 'DATABASE_URL', // Connection string passed as CLI argument+ requiresConfig: true, // Uses QuestDBForm.tsx+ tools: ['query', 'list_tables', 'describe_table', 'insert_data', 'get_metrics'],+ documentation: 'https://questdb.io/docs/third-party-tools/mcp/'+ },+ {+ id: 'wikipedia',+ name: 'Wikipedia',+ description: 'Search and retrieve Wikipedia articles with summaries and key facts',+ category: 'web',+ icon: '📚',+ command: 'bunx',+ args: ['-y', 'wikipedia-mcp'],+ env: {},+ requiresConfig: false,+ tools: ['search_wikipedia', 'get_article', 'get_summary', 'get_sections', 'get_links', 'get_coordinates', 'get_related_topics', 'summarize_article_for_query', 'summarize_article_section', 'extract_key_facts'],+ documentation: 'https://github.com/Rudra-ravi/wikipedia-mcp'+ }+];++/**+ * Get server definition by ID+ */+export function getServerById(id: string): MCPServerDefinition | undefined {+ return MARKETPLACE_SERVERS.find(server => server.id === id);+}++/**+ * Filter servers by category+ */+export function getServersByCategory(category: string): MCPServerDefinition[] {+ if (category === 'all') return MARKETPLACE_SERVERS;+ return MARKETPLACE_SERVERS.filter(server => server.category === category);+}++/**+ * Search servers by name or description+ */+export function searchServers(query: string): MCPServerDefinition[] {+ const lowerQuery = query.toLowerCase();+ return MARKETPLACE_SERVERS.filter(+ server =>+ server.name.toLowerCase().includes(lowerQuery) ||+ server.description.toLowerCase().includes(lowerQuery)+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/MCPToolNode.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/MCPToolNode.tsxnew file mode 100644index 000000000..c28f4bb29--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/MCPToolNode.tsx@@ -0,0 +1,361 @@+// MCP Tool Node - Generic node component for MCP tools in Node Editor+// Dynamically renders based on tool schema++import React, { useState, useEffect } from 'react';+import { Handle, Position } from 'reactflow';+import { Zap, AlertCircle, CheckCircle, Loader } from 'lucide-react';+import { mcpToolService, MCPTool } from '../../../services/mcpToolService';++interface MCPToolNodeProps {+ data: {+ serverId: string;+ toolName: string;+ label: string;+ parameters?: Record<string, any>;+ onParameterChange?: (params: Record<string, any>) => void;+ onExecute?: (result: any) => void;+ inputs?: Record<string, any>; // Inputs from connected nodes+ };+ selected: boolean;+}++const MCPToolNode: React.FC<MCPToolNodeProps> = ({ data, selected }) => {+ const [parameters, setParameters] = useState<Record<string, any>>(data.parameters || {});+ const [tool, setTool] = useState<MCPTool | null>(null);+ const [isExecuting, setIsExecuting] = useState(false);+ const [lastResult, setLastResult] = useState<any>(null);+ const [error, setError] = useState<string | null>(null);++ // Bloomberg colors+ const ORANGE = '#FFA500';+ const WHITE = '#FFFFFF';+ const GRAY = '#787878';+ const DARK_BG = '#0a0a0a';+ const PANEL_BG = '#1a1a1a';+ const BORDER = '#2d2d2d';+ const GREEN = '#10b981';+ const RED = '#ef4444';+ const YELLOW = '#FFFF00';++ // Load tool schema on mount+ useEffect(() => {+ const loadTool = async () => {+ try {+ const toolData = await mcpToolService.getTool(data.serverId, data.toolName);+ setTool(toolData);+ } catch (err) {+ console.error('[MCPToolNode] Failed to load tool:', err);+ setError('Failed to load tool schema');+ }+ };+ loadTool();+ }, [data.serverId, data.toolName]);++ // Merge inputs from connected nodes with manual parameters+ const getMergedParameters = (): Record<string, any> => {+ return {+ ...parameters,+ ...(data.inputs || {})+ };+ };++ // Execute the tool+ const executeTool = async () => {+ if (!tool) return;++ setIsExecuting(true);+ setError(null);++ try {+ const mergedParams = getMergedParameters();+ const result = await mcpToolService.executeToolDirect(+ data.serverId,+ data.toolName,+ mergedParams+ );++ if (result.success) {+ setLastResult(result.data);+ data.onExecute?.(result.data);+ } else {+ setError(result.error || 'Unknown error');+ }+ } catch (err: any) {+ setError(err.message || 'Execution failed');+ } finally {+ setIsExecuting(false);+ }+ };++ // Handle parameter change+ const handleParameterChange = (key: string, value: any) => {+ const newParams = { ...parameters, [key]: value };+ setParameters(newParams);+ data.onParameterChange?.(newParams);+ };++ // Get required parameters from schema+ const getRequiredParams = (): string[] => {+ if (!tool?.inputSchema?.required) return [];+ return tool.inputSchema.required;+ };++ // Render parameter input based on type+ const renderParameterInput = (key: string, propSchema: any) => {+ const isRequired = getRequiredParams().includes(key);+ const value = parameters[key] || '';+ const type = propSchema.type || 'string';++ // Check if parameter is provided by connected node+ const isProvidedByConnection = data.inputs && key in data.inputs;++ return (+ <div key={key} style={{ marginBottom: '8px' }}>+ <label style={{+ color: isRequired ? YELLOW : GRAY,+ fontSize: '9px',+ display: 'block',+ marginBottom: '2px',+ fontWeight: isRequired ? 'bold' : 'normal'+ }}>+ {key}{isRequired ? ' *' : ''}+ {isProvidedByConnection && (+ <span style={{ color: GREEN, marginLeft: '4px' }}>+ [Connected]+ </span>+ )}+ </label>+ {type === 'boolean' ? (+ <input+ type="checkbox"+ checked={value || false}+ onChange={(e) => handleParameterChange(key, e.target.checked)}+ disabled={isProvidedByConnection}+ style={{+ cursor: isProvidedByConnection ? 'not-allowed' : 'pointer',+ opacity: isProvidedByConnection ? 0.5 : 1+ }}+ />+ ) : type === 'number' ? (+ <input+ type="number"+ value={value}+ onChange={(e) => handleParameterChange(key, parseFloat(e.target.value))}+ disabled={isProvidedByConnection}+ style={{+ width: '100%',+ backgroundColor: DARK_BG,+ border: `1px solid ${BORDER}`,+ color: WHITE,+ padding: '4px',+ fontSize: '9px',+ fontFamily: 'monospace',+ opacity: isProvidedByConnection ? 0.5 : 1,+ cursor: isProvidedByConnection ? 'not-allowed' : 'text'+ }}+ />+ ) : (+ <textarea+ value={value}+ onChange={(e) => handleParameterChange(key, e.target.value)}+ disabled={isProvidedByConnection}+ placeholder={propSchema.description || ''}+ style={{+ width: '100%',+ backgroundColor: DARK_BG,+ border: `1px solid ${BORDER}`,+ color: WHITE,+ padding: '4px',+ fontSize: '9px',+ fontFamily: 'monospace',+ resize: 'vertical',+ minHeight: '40px',+ opacity: isProvidedByConnection ? 0.5 : 1,+ cursor: isProvidedByConnection ? 'not-allowed' : 'text'+ }}+ />+ )}+ </div>+ );+ };++ // Check if tool is ready to execute+ const isReadyToExecute = (): boolean => {+ if (!tool) return false;+ const mergedParams = getMergedParameters();+ const validation = mcpToolService.validateToolParams(tool, mergedParams);+ return validation.valid;+ };++ return (+ <div style={{+ backgroundColor: PANEL_BG,+ border: `2px solid ${selected ? ORANGE : BORDER}`,+ borderRadius: '6px',+ padding: '12px',+ minWidth: '280px',+ maxWidth: '350px',+ fontFamily: 'Consolas, monospace',+ boxShadow: selected ? `0 0 12px ${ORANGE}80` : 'none'+ }}>+ {/* Input handles - dynamically generated from schema */}+ {tool?.inputSchema?.properties && Object.keys(tool.inputSchema.properties).map((key, index) => (+ <Handle+ key={`input-${key}`}+ type="target"+ position={Position.Left}+ id={key}+ style={{+ top: `${30 + (index * 20)}px`,+ background: ORANGE,+ width: '10px',+ height: '10px',+ border: `2px solid ${DARK_BG}`+ }}+ />+ ))}++ {/* Header */}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ marginBottom: '12px',+ paddingBottom: '8px',+ borderBottom: `1px solid ${BORDER}`+ }}>+ <Zap size={16} color={ORANGE} />+ <div style={{ flex: 1 }}>+ <div style={{+ color: WHITE,+ fontSize: '11px',+ fontWeight: 'bold',+ marginBottom: '2px'+ }}>+ {data.label}+ </div>+ <div style={{+ color: GRAY,+ fontSize: '8px'+ }}>+ {data.serverId} • {data.toolName}+ </div>+ </div>+ </div>++ {/* Tool Description */}+ {tool?.description && (+ <div style={{+ color: GRAY,+ fontSize: '9px',+ marginBottom: '12px',+ lineHeight: '1.4'+ }}>+ {tool.description}+ </div>+ )}++ {/* Parameters */}+ {tool?.inputSchema?.properties && (+ <div style={{ marginBottom: '12px' }}>+ <div style={{+ color: YELLOW,+ fontSize: '10px',+ fontWeight: 'bold',+ marginBottom: '8px'+ }}>+ PARAMETERS+ </div>+ {Object.entries(tool.inputSchema.properties).map(([key, propSchema]: [string, any]) =>+ renderParameterInput(key, propSchema)+ )}+ </div>+ )}++ {/* Execute Button */}+ <button+ onClick={executeTool}+ disabled={!isReadyToExecute() || isExecuting}+ style={{+ width: '100%',+ backgroundColor: isReadyToExecute() && !isExecuting ? GREEN : GRAY,+ color: 'black',+ border: 'none',+ padding: '8px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: isReadyToExecute() && !isExecuting ? 'pointer' : 'not-allowed',+ borderRadius: '4px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ marginBottom: '8px'+ }}+ >+ {isExecuting ? (+ <>+ <Loader size={12} className="animate-spin" />+ EXECUTING...+ </>+ ) : (+ <>+ <Zap size={12} />+ EXECUTE TOOL+ </>+ )}+ </button>++ {/* Status */}+ {error && (+ <div style={{+ backgroundColor: `${RED}20`,+ border: `1px solid ${RED}`,+ borderRadius: '4px',+ padding: '6px',+ marginBottom: '8px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px'+ }}>+ <AlertCircle size={12} color={RED} />+ <div style={{ color: RED, fontSize: '9px', flex: 1 }}>+ {error}+ </div>+ </div>+ )}++ {lastResult && !error && (+ <div style={{+ backgroundColor: `${GREEN}20`,+ border: `1px solid ${GREEN}`,+ borderRadius: '4px',+ padding: '6px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px'+ }}>+ <CheckCircle size={12} color={GREEN} />+ <div style={{ color: GREEN, fontSize: '9px', flex: 1 }}>+ Executed successfully+ </div>+ </div>+ )}++ {/* Output handle */}+ <Handle+ type="source"+ position={Position.Right}+ id="output"+ style={{+ background: GREEN,+ width: '10px',+ height: '10px',+ border: `2px solid ${DARK_BG}`+ }}+ />+ </div>+ );+};++export default MCPToolNode;diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/mcpNodeConfigs.ts b/fincept-terminal-desktop/src/components/tabs/node-editor/mcpNodeConfigs.tsnew file mode 100644index 000000000..b20e2497b--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/mcpNodeConfigs.ts@@ -0,0 +1,134 @@+// MCP Node Configurations+// Dynamically generates node configs from available MCP servers++import { mcpToolService, MCPTool } from '../../../services/mcpToolService';++export interface MCPNodeConfig {+ id: string;+ type: 'mcp-tool';+ label: string;+ category: 'MCP Tools';+ icon: string;+ serverId: string;+ toolName: string;+ description: string;+ inputs: string[];+ outputs: string[];+}++/**+ * Generate node configurations from available MCP tools+ * This function is called when Node Editor initializes+ */+export async function generateMCPNodeConfigs(): Promise<MCPNodeConfig[]> {+ try {+ const tools = await mcpToolService.getAllTools();++ return tools.map((tool: MCPTool) => {+ // Extract inputs from tool schema+ const inputs = tool.inputSchema?.properties+ ? Object.keys(tool.inputSchema.properties)+ : [];++ return {+ id: `mcp-${tool.serverId}-${tool.name}`,+ type: 'mcp-tool' as const,+ label: tool.name.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()),+ category: 'MCP Tools' as const,+ icon: getIconForTool(tool),+ serverId: tool.serverId,+ toolName: tool.name,+ description: tool.description || `${tool.name} from ${tool.serverId}`,+ inputs,+ outputs: ['output'] // All MCP tools have output+ };+ });+ } catch (error) {+ console.error('[MCPNodeConfigs] Failed to generate configs:', error);+ return [];+ }+}++/**+ * Get icon emoji for tool based on server and tool name+ */+function getIconForTool(tool: MCPTool): string {+ const serverId = tool.serverId.toLowerCase();+ const toolName = tool.name.toLowerCase();++ // Database tools+ if (serverId.includes('postgres')) return '🐘';+ if (serverId.includes('questdb')) return '⚡';+ if (serverId.includes('sqlite')) return '💾';+ if (serverId.includes('mysql')) return '🐬';++ // Web tools+ if (serverId.includes('wikipedia')) return '📚';+ if (serverId.includes('search') || serverId.includes('brave')) return '🔍';+ if (serverId.includes('fetch') || toolName.includes('fetch')) return '🌐';++ // File tools+ if (serverId.includes('filesystem') || serverId.includes('file')) return '📁';++ // API tools+ if (serverId.includes('api') || serverId.includes('http')) return '🔌';++ // Productivity tools+ if (serverId.includes('slack')) return '💬';+ if (serverId.includes('email')) return '📧';+ if (serverId.includes('calendar')) return '📅';++ // Default+ return '⚡';+}++/**+ * Get MCP tool categories for filtering in Node Editor+ */+export function getMCPToolCategories(tools: MCPNodeConfig[]): string[] {+ const categories = new Set<string>();++ tools.forEach(tool => {+ const category = categorizeMCPTool(tool);+ categories.add(category);+ });++ return Array.from(categories);+}++/**+ * Categorize MCP tool for grouping in UI+ */+function categorizeMCPTool(tool: MCPNodeConfig): string {+ const serverId = tool.serverId.toLowerCase();++ if (serverId.includes('postgres') || serverId.includes('questdb') ||+ serverId.includes('sqlite') || serverId.includes('mysql')) {+ return 'Database';+ }++ if (serverId.includes('wikipedia') || serverId.includes('search') ||+ serverId.includes('fetch')) {+ return 'Web';+ }++ if (serverId.includes('file')) {+ return 'File System';+ }++ if (serverId.includes('api') || serverId.includes('http')) {+ return 'API';+ }++ return 'Other';+}++/**+ * Refresh MCP node configurations+ * Call this when new MCP servers are installed+ */+export async function refreshMCPNodeConfigs(): Promise<MCPNodeConfig[]> {+ // Clear cache to get fresh tool list+ mcpToolService.clearCache();+ return generateMCPNodeConfigs();+}diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio/AlertsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio/AlertsView.tsxindex 1e7cf35de..88e39b9bb 100644--- a/fincept-terminal-desktop/src/components/tabs/portfolio/AlertsView.tsx+++ b/fincept-terminal-desktop/src/components/tabs/portfolio/AlertsView.tsx@@ -2,7 +2,16 @@ import React, { useState, useEffect } from 'react';import { PortfolioSummary } from '../../../services/portfolioService';import { BLOOMBERG_COLORS, formatCurrency } from './utils';import { Bell, TrendingUp, TrendingDown, Target } from 'lucide-react';-import { alertsService, PriceAlert } from '../../../services/alertsService';++interface PriceAlert {+ id: string;+ symbol: string;+ type: string;+ condition: string;+ target_value: number;+ is_triggered: boolean;+ created_at: string;+}interface AlertsViewProps {portfolioSummary: PortfolioSummary;@@ -13,38 +22,17 @@ const AlertsView: React.FC<AlertsViewProps> = ({ portfolioSummary }) => {const currency = portfolioSummary.portfolio.currency;const [alerts, setAlerts] = useState<PriceAlert[]>([]);- const [loading, setLoading] = useState(true);+ const [loading, setLoading] = useState(false);const [stats, setStats] = useState({ total: 0, active: 0, triggered: 0, byType: {} as Record<string, number> });+ // Stub - alerts service removeduseEffect(() => {- const loadAlerts = async () => {- try {- await alertsService.initialize();- const portfolioAlerts = await alertsService.getPortfolioAlerts(portfolioSummary.portfolio.id, false);- const alertStats = await alertsService.getAlertStats(portfolioSummary.portfolio.id);-- setAlerts(portfolioAlerts);- setStats(alertStats);- } catch (error) {- console.error('Failed to load alerts:', error);- } finally {- setLoading(false);- }- };-- loadAlerts();+ setLoading(false);}, [portfolioSummary.portfolio.id]);const handleDeleteAlert = async (alertId: string) => {- try {- await alertsService.deleteAlert(alertId);- setAlerts(prev => prev.filter(a => a.id !== alertId));- // Refresh stats- const alertStats = await alertsService.getAlertStats(portfolioSummary.portfolio.id);- setStats(alertStats);- } catch (error) {- console.error('Failed to delete alert:', error);- }+ // Stub - alerts service removed+ setAlerts(prev => prev.filter(a => a.id !== alertId));};const getAlertIcon = (type: string) => {diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/AddStockModal.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/AddStockModal.tsxnew file mode 100644index 000000000..22b30bbcf--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/AddStockModal.tsx@@ -0,0 +1,179 @@+import React, { useState } from 'react';+import { BLOOMBERG_COLORS } from './utils';++interface AddStockModalProps {+ onClose: () => void;+ onAdd: (symbol: string, notes: string) => Promise<void>;+ existingSymbols: string[];+}++const AddStockModal: React.FC<AddStockModalProps> = ({ onClose, onAdd, existingSymbols }) => {+ const [symbol, setSymbol] = useState('');+ const [notes, setNotes] = useState('');+ const [loading, setLoading] = useState(false);++ const handleAdd = async () => {+ const trimmedSymbol = symbol.trim().toUpperCase();++ if (!trimmedSymbol) {+ alert('Please enter a stock symbol');+ return;+ }++ if (existingSymbols.includes(trimmedSymbol)) {+ alert(`${trimmedSymbol} is already in this watchlist`);+ return;+ }++ setLoading(true);+ try {+ await onAdd(trimmedSymbol, notes.trim());+ onClose();+ } catch (error) {+ console.error('Error adding stock:', error);+ alert(error instanceof Error ? error.message : 'Failed to add stock');+ } finally {+ setLoading(false);+ }+ };++ const handleKeyPress = (e: React.KeyboardEvent) => {+ if (e.key === 'Enter' && !loading && symbol.trim()) {+ handleAdd();+ }+ };++ return (+ <div style={{+ position: 'fixed',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(0,0,0,0.8)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 1000+ }}>+ <div style={{+ backgroundColor: BLOOMBERG_COLORS.DARK_BG,+ border: `2px solid ${BLOOMBERG_COLORS.GREEN}`,+ padding: '24px',+ minWidth: '400px'+ }}>+ <div style={{+ color: BLOOMBERG_COLORS.GREEN,+ fontSize: '14px',+ fontWeight: 'bold',+ marginBottom: '16px'+ }}>+ ADD STOCK TO WATCHLIST+ </div>++ <div style={{ marginBottom: '12px' }}>+ <label style={{+ color: BLOOMBERG_COLORS.GRAY,+ fontSize: '10px',+ display: 'block',+ marginBottom: '4px'+ }}>+ SYMBOL *+ </label>+ <input+ type="text"+ value={symbol}+ onChange={(e) => setSymbol(e.target.value.toUpperCase())}+ onKeyPress={handleKeyPress}+ style={{+ width: '100%',+ background: BLOOMBERG_COLORS.PANEL_BG,+ border: `1px solid ${BLOOMBERG_COLORS.GRAY}`,+ color: BLOOMBERG_COLORS.WHITE,+ padding: '8px',+ fontSize: '14px',+ fontFamily: 'Consolas, monospace',+ textTransform: 'uppercase',+ fontWeight: 'bold',+ letterSpacing: '1px'+ }}+ placeholder="AAPL"+ maxLength={10}+ autoFocus+ />+ <div style={{+ color: BLOOMBERG_COLORS.GRAY,+ fontSize: '9px',+ marginTop: '4px'+ }}>+ Enter stock ticker symbol (e.g., AAPL, MSFT, GOOGL)+ </div>+ </div>++ <div style={{ marginBottom: '16px' }}>+ <label style={{+ color: BLOOMBERG_COLORS.GRAY,+ fontSize: '10px',+ display: 'block',+ marginBottom: '4px'+ }}>+ NOTES (OPTIONAL)+ </label>+ <textarea+ value={notes}+ onChange={(e) => setNotes(e.target.value)}+ style={{+ width: '100%',+ background: BLOOMBERG_COLORS.PANEL_BG,+ border: `1px solid ${BLOOMBERG_COLORS.GRAY}`,+ color: BLOOMBERG_COLORS.WHITE,+ padding: '8px',+ fontSize: '11px',+ fontFamily: 'Consolas, monospace',+ resize: 'vertical',+ minHeight: '60px'+ }}+ placeholder="Add notes about this stock..."+ maxLength={200}+ />+ </div>++ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>+ <button+ onClick={onClose}+ disabled={loading}+ style={{+ background: BLOOMBERG_COLORS.GRAY,+ color: 'black',+ border: 'none',+ padding: '8px 16px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: loading ? 'not-allowed' : 'pointer',+ opacity: loading ? 0.5 : 1+ }}+ >+ CANCEL+ </button>+ <button+ onClick={handleAdd}+ disabled={loading || !symbol.trim()}+ style={{+ background: (!symbol.trim() || loading) ? BLOOMBERG_COLORS.GRAY : BLOOMBERG_COLORS.GREEN,+ color: 'black',+ border: 'none',+ padding: '8px 16px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: (!symbol.trim() || loading) ? 'not-allowed' : 'pointer'+ }}+ >+ {loading ? 'ADDING...' : 'ADD STOCK'}+ </button>+ </div>+ </div>+ </div>+ );+};++export default AddStockModal;diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/CreateWatchlistModal.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/CreateWatchlistModal.tsxnew file mode 100644index 000000000..5cb9bfbd8--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/CreateWatchlistModal.tsx@@ -0,0 +1,188 @@+import React, { useState } from 'react';+import { BLOOMBERG_COLORS, WATCHLIST_COLORS } from './utils';++interface CreateWatchlistModalProps {+ onClose: () => void;+ onCreate: (name: string, description: string, color: string) => Promise<void>;+ existingColors: string[];+}++const CreateWatchlistModal: React.FC<CreateWatchlistModalProps> = ({ onClose, onCreate, existingColors }) => {+ const [name, setName] = useState('');+ const [description, setDescription] = useState('');+ const [selectedColor, setSelectedColor] = useState(+ WATCHLIST_COLORS.find(c => !existingColors.includes(c)) || WATCHLIST_COLORS[0]+ );+ const [loading, setLoading] = useState(false);++ const handleCreate = async () => {+ if (!name.trim()) {+ alert('Please enter a watchlist name');+ return;+ }++ setLoading(true);+ try {+ await onCreate(name.trim(), description.trim(), selectedColor);+ onClose();+ } catch (error) {+ console.error('Error creating watchlist:', error);+ alert('Failed to create watchlist');+ } finally {+ setLoading(false);+ }+ };++ return (+ <div style={{+ position: 'fixed',+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ backgroundColor: 'rgba(0,0,0,0.8)',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ zIndex: 1000+ }}>+ <div style={{+ backgroundColor: BLOOMBERG_COLORS.DARK_BG,+ border: `2px solid ${BLOOMBERG_COLORS.ORANGE}`,+ padding: '24px',+ minWidth: '400px',+ maxWidth: '500px'+ }}>+ <div style={{+ color: BLOOMBERG_COLORS.ORANGE,+ fontSize: '14px',+ fontWeight: 'bold',+ marginBottom: '16px'+ }}>+ CREATE NEW WATCHLIST+ </div>++ <div style={{ marginBottom: '12px' }}>+ <label style={{+ color: BLOOMBERG_COLORS.GRAY,+ fontSize: '10px',+ display: 'block',+ marginBottom: '4px'+ }}>+ WATCHLIST NAME *+ </label>+ <input+ type="text"+ value={name}+ onChange={(e) => setName(e.target.value)}+ style={{+ width: '100%',+ background: BLOOMBERG_COLORS.PANEL_BG,+ border: `1px solid ${BLOOMBERG_COLORS.GRAY}`,+ color: BLOOMBERG_COLORS.WHITE,+ padding: '8px',+ fontSize: '11px',+ fontFamily: 'Consolas, monospace'+ }}+ placeholder="My Watchlist"+ maxLength={50}+ />+ </div>++ <div style={{ marginBottom: '12px' }}>+ <label style={{+ color: BLOOMBERG_COLORS.GRAY,+ fontSize: '10px',+ display: 'block',+ marginBottom: '4px'+ }}>+ DESCRIPTION+ </label>+ <textarea+ value={description}+ onChange={(e) => setDescription(e.target.value)}+ style={{+ width: '100%',+ background: BLOOMBERG_COLORS.PANEL_BG,+ border: `1px solid ${BLOOMBERG_COLORS.GRAY}`,+ color: BLOOMBERG_COLORS.WHITE,+ padding: '8px',+ fontSize: '11px',+ fontFamily: 'Consolas, monospace',+ resize: 'vertical',+ minHeight: '60px'+ }}+ placeholder="Optional description..."+ maxLength={200}+ />+ </div>++ <div style={{ marginBottom: '16px' }}>+ <label style={{+ color: BLOOMBERG_COLORS.GRAY,+ fontSize: '10px',+ display: 'block',+ marginBottom: '8px'+ }}>+ COLOR+ </label>+ <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>+ {WATCHLIST_COLORS.map(color => (+ <button+ key={color}+ onClick={() => setSelectedColor(color)}+ style={{+ width: '32px',+ height: '32px',+ backgroundColor: color,+ border: selectedColor === color+ ? `3px solid ${BLOOMBERG_COLORS.WHITE}`+ : `1px solid ${BLOOMBERG_COLORS.GRAY}`,+ cursor: 'pointer',+ borderRadius: '2px'+ }}+ title={color}+ />+ ))}+ </div>+ </div>++ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>+ <button+ onClick={onClose}+ disabled={loading}+ style={{+ background: BLOOMBERG_COLORS.GRAY,+ color: 'black',+ border: 'none',+ padding: '8px 16px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: loading ? 'not-allowed' : 'pointer',+ opacity: loading ? 0.5 : 1+ }}+ >+ CANCEL+ </button>+ <button+ onClick={handleCreate}+ disabled={loading || !name.trim()}+ style={{+ background: (!name.trim() || loading) ? BLOOMBERG_COLORS.GRAY : BLOOMBERG_COLORS.ORANGE,+ color: 'black',+ border: 'none',+ padding: '8px 16px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: (!name.trim() || loading) ? 'not-allowed' : 'pointer'+ }}+ >+ {loading ? 'CREATING...' : 'CREATE'}+ </button>+ </div>+ </div>+ </div>+ );+};++export default CreateWatchlistModal;diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/StockDetailPanel.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/StockDetailPanel.tsxnew file mode 100644index 000000000..55c1a96d9--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/StockDetailPanel.tsx@@ -0,0 +1,199 @@+import React from 'react';+import { WatchlistStockWithQuote } from '../../../services/watchlistService';+import { BLOOMBERG_COLORS, formatCurrency, formatPercent, formatVolume, getChangeColor } from './utils';++interface StockDetailPanelProps {+ stock: WatchlistStockWithQuote | null;+}++const StockDetailPanel: React.FC<StockDetailPanelProps> = ({ stock }) => {+ const { ORANGE, WHITE, GRAY, GREEN, RED, YELLOW, CYAN, PANEL_BG } = BLOOMBERG_COLORS;++ if (!stock) {+ return (+ <div style={{+ width: '320px',+ backgroundColor: PANEL_BG,+ border: `1px solid ${GRAY}`,+ padding: '12px',+ overflow: 'auto',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ color: GRAY,+ fontSize: '11px',+ textAlign: 'center'+ }}>+ <div style={{ marginBottom: '8px', fontSize: '12px' }}>+ NO STOCK SELECTED+ </div>+ <div>+ Click on a stock to view details+ </div>+ </div>+ );+ }++ const quote = stock.quote;++ return (+ <div style={{+ width: '320px',+ backgroundColor: PANEL_BG,+ border: `1px solid ${GRAY}`,+ padding: '4px',+ overflow: 'auto'+ }}>+ <div style={{+ color: ORANGE,+ fontSize: '11px',+ fontWeight: 'bold',+ marginBottom: '4px'+ }}>+ STOCK DETAIL: {stock.symbol}+ </div>+ <div style={{ borderBottom: `1px solid ${GRAY}`, marginBottom: '8px' }}></div>++ {!quote ? (+ <div style={{+ padding: '16px',+ textAlign: 'center',+ color: RED,+ fontSize: '10px'+ }}>+ Failed to load market data+ </div>+ ) : (+ <>+ {/* Price Info */}+ <div style={{ marginBottom: '12px' }}>+ <div style={{+ padding: '6px',+ backgroundColor: 'rgba(255,165,0,0.1)',+ marginBottom: '4px'+ }}>+ <div style={{+ color: GRAY,+ fontSize: '9px',+ marginBottom: '2px'+ }}>+ LAST PRICE+ </div>+ <div style={{+ color: WHITE,+ fontSize: '20px',+ fontWeight: 'bold'+ }}>+ {formatCurrency(quote.price)}+ </div>+ <div style={{+ color: getChangeColor(quote.change),+ fontSize: '12px'+ }}>+ {formatCurrency(quote.change)} ({formatPercent(quote.change_percent)})+ </div>+ </div>+ </div>++ {/* Trading Stats */}+ <div style={{+ fontSize: '9px',+ lineHeight: '1.5',+ marginBottom: '12px'+ }}>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ marginBottom: '2px'+ }}>+ <span style={{ color: GRAY }}>Open:</span>+ <span style={{ color: WHITE }}>{formatCurrency(quote.open)}</span>+ </div>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ marginBottom: '2px'+ }}>+ <span style={{ color: GRAY }}>Prev Close:</span>+ <span style={{ color: WHITE }}>{formatCurrency(quote.previous_close)}</span>+ </div>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ marginBottom: '2px'+ }}>+ <span style={{ color: GRAY }}>Day High:</span>+ <span style={{ color: GREEN }}>{formatCurrency(quote.high)}</span>+ </div>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ marginBottom: '2px'+ }}>+ <span style={{ color: GRAY }}>Day Low:</span>+ <span style={{ color: RED }}>{formatCurrency(quote.low)}</span>+ </div>+ <div style={{+ borderTop: `1px solid ${GRAY}`,+ marginTop: '4px',+ paddingTop: '4px'+ }}>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ marginBottom: '2px'+ }}>+ <span style={{ color: GRAY }}>Volume:</span>+ <span style={{ color: YELLOW }}>{formatVolume(quote.volume)}</span>+ </div>+ </div>+ </div>++ {/* Notes Section */}+ {stock.notes && (+ <div style={{+ borderTop: `1px solid ${GRAY}`,+ paddingTop: '8px',+ marginTop: '8px'+ }}>+ <div style={{+ color: YELLOW,+ fontSize: '10px',+ fontWeight: 'bold',+ marginBottom: '4px'+ }}>+ NOTES+ </div>+ <div style={{+ fontSize: '9px',+ color: WHITE,+ backgroundColor: 'rgba(255,255,255,0.05)',+ padding: '6px',+ borderLeft: `2px solid ${CYAN}`,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word'+ }}>+ {stock.notes}+ </div>+ </div>+ )}++ {/* Timestamp */}+ <div style={{+ borderTop: `1px solid ${GRAY}`,+ paddingTop: '8px',+ marginTop: '12px',+ fontSize: '8px',+ color: GRAY,+ textAlign: 'center'+ }}>+ Last Updated: {new Date(quote.timestamp * 1000).toLocaleString()}+ </div>+ </>+ )}+ </div>+ );+};++export default StockDetailPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/StockListView.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/StockListView.tsxnew file mode 100644index 000000000..931eca5aa--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/StockListView.tsx@@ -0,0 +1,258 @@+import React from 'react';+import { WatchlistStockWithQuote } from '../../../services/watchlistService';+import { BLOOMBERG_COLORS, formatCurrency, formatPercent, formatVolume, getChangeColor, SortCriteria } from './utils';+import { Trash2 } from 'lucide-react';++interface StockListViewProps {+ stocks: WatchlistStockWithQuote[];+ watchlistName: string;+ sortBy: SortCriteria;+ onSortChange: (sort: SortCriteria) => void;+ onStockClick: (stock: WatchlistStockWithQuote) => void;+ onRemoveStock: (symbol: string) => void;+ selectedSymbol?: string;+}++const StockListView: React.FC<StockListViewProps> = ({+ stocks,+ watchlistName,+ sortBy,+ onSortChange,+ onStockClick,+ onRemoveStock,+ selectedSymbol+}) => {+ const { ORANGE, WHITE, GRAY, GREEN, RED, YELLOW, CYAN, DARK_BG, PANEL_BG } = BLOOMBERG_COLORS;++ const handleRemove = (e: React.MouseEvent, symbol: string) => {+ e.stopPropagation();+ if (confirm(`Remove ${symbol} from watchlist?`)) {+ onRemoveStock(symbol);+ }+ };++ return (+ <div style={{+ flex: 1,+ backgroundColor: PANEL_BG,+ border: `1px solid ${GRAY}`,+ padding: '4px',+ overflow: 'auto'+ }}>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ marginBottom: '4px'+ }}>+ <div style={{+ color: ORANGE,+ fontSize: '11px',+ fontWeight: 'bold'+ }}>+ WATCHLIST: {watchlistName}+ </div>+ <div style={{+ display: 'flex',+ gap: '4px',+ fontSize: '9px'+ }}>+ <button+ onClick={() => onSortChange('TICKER')}+ style={{+ padding: '2px 6px',+ backgroundColor: sortBy === 'TICKER' ? ORANGE : DARK_BG,+ color: sortBy === 'TICKER' ? DARK_BG : WHITE,+ border: `1px solid ${GRAY}`,+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace',+ fontWeight: sortBy === 'TICKER' ? 'bold' : 'normal'+ }}+ >+ TICKER+ </button>+ <button+ onClick={() => onSortChange('CHANGE')}+ style={{+ padding: '2px 6px',+ backgroundColor: sortBy === 'CHANGE' ? ORANGE : DARK_BG,+ color: sortBy === 'CHANGE' ? DARK_BG : WHITE,+ border: `1px solid ${GRAY}`,+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace',+ fontWeight: sortBy === 'CHANGE' ? 'bold' : 'normal'+ }}+ >+ CHANGE+ </button>+ <button+ onClick={() => onSortChange('VOLUME')}+ style={{+ padding: '2px 6px',+ backgroundColor: sortBy === 'VOLUME' ? ORANGE : DARK_BG,+ color: sortBy === 'VOLUME' ? DARK_BG : WHITE,+ border: `1px solid ${GRAY}`,+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace',+ fontWeight: sortBy === 'VOLUME' ? 'bold' : 'normal'+ }}+ >+ VOLUME+ </button>+ <button+ onClick={() => onSortChange('PRICE')}+ style={{+ padding: '2px 6px',+ backgroundColor: sortBy === 'PRICE' ? ORANGE : DARK_BG,+ color: sortBy === 'PRICE' ? DARK_BG : WHITE,+ border: `1px solid ${GRAY}`,+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace',+ fontWeight: sortBy === 'PRICE' ? 'bold' : 'normal'+ }}+ >+ PRICE+ </button>+ </div>+ </div>+ <div style={{ borderBottom: `1px solid ${GRAY}`, marginBottom: '8px' }}></div>++ {stocks.length === 0 ? (+ <div style={{+ padding: '32px',+ textAlign: 'center',+ color: GRAY,+ fontSize: '11px'+ }}>+ <div style={{ marginBottom: '8px', fontSize: '12px' }}>+ No stocks in this watchlist yet+ </div>+ <div>+ Click "ADD STOCK" to add stocks+ </div>+ </div>+ ) : (+ <>+ {/* Table Header */}+ <div style={{+ display: 'grid',+ gridTemplateColumns: '100px 90px 90px 90px 50px',+ gap: '4px',+ padding: '4px',+ backgroundColor: 'rgba(255,255,255,0.05)',+ fontSize: '9px',+ fontWeight: 'bold',+ marginBottom: '2px'+ }}>+ <div style={{ color: GRAY }}>SYMBOL</div>+ <div style={{ color: GRAY }}>PRICE</div>+ <div style={{ color: GRAY }}>CHANGE</div>+ <div style={{ color: GRAY }}>VOLUME</div>+ <div style={{ color: GRAY }}>ACTION</div>+ </div>++ {/* Stock Rows */}+ {stocks.map((stock) => {+ const quote = stock.quote;+ const isSelected = selectedSymbol === stock.symbol;++ return (+ <div+ key={stock.id}+ onClick={() => onStockClick(stock)}+ style={{+ display: 'grid',+ gridTemplateColumns: '100px 90px 90px 90px 50px',+ gap: '4px',+ padding: '8px 4px',+ backgroundColor: isSelected+ ? 'rgba(255,165,0,0.1)'+ : 'rgba(255,255,255,0.02)',+ borderLeft: `3px solid ${quote ? getChangeColor(quote.change) : GRAY}`,+ fontSize: '10px',+ marginBottom: '1px',+ cursor: 'pointer',+ transition: 'background-color 0.2s'+ }}+ onMouseEnter={(e) => {+ if (!isSelected) {+ e.currentTarget.style.backgroundColor = 'rgba(255,255,255,0.05)';+ }+ }}+ onMouseLeave={(e) => {+ if (!isSelected) {+ e.currentTarget.style.backgroundColor = 'rgba(255,255,255,0.02)';+ }+ }}+ >+ <div style={{+ color: CYAN,+ fontWeight: 'bold',+ letterSpacing: '0.5px'+ }}>+ {stock.symbol}+ </div>++ {quote ? (+ <>+ <div style={{+ color: WHITE,+ fontWeight: 'bold'+ }}>+ {formatCurrency(quote.price)}+ </div>+ <div>+ <div style={{+ color: getChangeColor(quote.change)+ }}>+ {formatCurrency(quote.change)}+ </div>+ <div style={{+ color: getChangeColor(quote.change_percent),+ fontSize: '8px'+ }}>+ ({formatPercent(quote.change_percent)})+ </div>+ </div>+ <div style={{+ color: YELLOW+ }}>+ {formatVolume(quote.volume)}+ </div>+ </>+ ) : (+ <>+ <div style={{ color: GRAY }}>N/A</div>+ <div style={{ color: GRAY }}>N/A</div>+ <div style={{ color: GRAY }}>N/A</div>+ </>+ )}++ <div>+ <button+ onClick={(e) => handleRemove(e, stock.symbol)}+ style={{+ background: 'transparent',+ border: 'none',+ color: RED,+ cursor: 'pointer',+ padding: '2px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center'+ }}+ title={`Remove ${stock.symbol}`}+ >+ <Trash2 size={14} />+ </button>+ </div>+ </div>+ );+ })}+ </>+ )}+ </div>+ );+};++export default StockListView;diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistSidebar.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistSidebar.tsxnew file mode 100644index 000000000..7a72768fe--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistSidebar.tsx@@ -0,0 +1,281 @@+import React from 'react';+import { Watchlist } from '../../../services/watchlistService';+import { BLOOMBERG_COLORS } from './utils';+import { Trash2, Plus } from 'lucide-react';++interface WatchlistSidebarProps {+ watchlists: Array<Watchlist & { stock_count: number }>;+ selectedWatchlistId: string | null;+ onSelectWatchlist: (watchlistId: string) => void;+ onCreateWatchlist: () => void;+ onDeleteWatchlist: (watchlistId: string) => void;+ marketMovers?: {+ gainers: Array<{ symbol: string; quote: any }>;+ losers: Array<{ symbol: string; quote: any }>;+ };+ volumeLeaders?: Array<{ symbol: string; quote: any }>;+}++const WatchlistSidebar: React.FC<WatchlistSidebarProps> = ({+ watchlists,+ selectedWatchlistId,+ onSelectWatchlist,+ onCreateWatchlist,+ onDeleteWatchlist,+ marketMovers,+ volumeLeaders+}) => {+ const { ORANGE, WHITE, GRAY, GREEN, RED, CYAN, YELLOW, DARK_BG, PANEL_BG } = BLOOMBERG_COLORS;++ const handleDelete = (e: React.MouseEvent, watchlistId: string) => {+ e.stopPropagation();+ onDeleteWatchlist(watchlistId);+ };++ return (+ <div style={{+ width: '280px',+ backgroundColor: PANEL_BG,+ border: `1px solid ${GRAY}`,+ padding: '4px',+ overflow: 'auto',+ display: 'flex',+ flexDirection: 'column'+ }}>+ {/* Watchlist Groups */}+ <div style={{+ color: ORANGE,+ fontSize: '11px',+ fontWeight: 'bold',+ marginBottom: '4px',+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center'+ }}>+ <span>WATCHLIST GROUPS ({watchlists.length})</span>+ <button+ onClick={onCreateWatchlist}+ style={{+ background: 'transparent',+ border: `1px solid ${ORANGE}`,+ color: ORANGE,+ padding: '2px 4px',+ fontSize: '8px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '2px'+ }}+ title="Create new watchlist"+ >+ <Plus size={10} />+ NEW+ </button>+ </div>+ <div style={{ borderBottom: `1px solid ${GRAY}`, marginBottom: '8px' }}></div>++ <div style={{ flex: 1, overflow: 'auto', marginBottom: '8px' }}>+ {watchlists.length === 0 ? (+ <div style={{+ padding: '16px',+ textAlign: 'center',+ color: GRAY,+ fontSize: '10px'+ }}>+ No watchlists yet.+ <br />+ Click NEW to create one.+ </div>+ ) : (+ watchlists.map((watchlist) => (+ <button+ key={watchlist.id}+ onClick={() => onSelectWatchlist(watchlist.id)}+ style={{+ width: '100%',+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ padding: '8px',+ marginBottom: '3px',+ backgroundColor: selectedWatchlistId === watchlist.id+ ? 'rgba(255,165,0,0.1)'+ : 'rgba(255,255,255,0.02)',+ border: `1px solid ${selectedWatchlistId === watchlist.id ? ORANGE : 'transparent'}`,+ textAlign: 'left',+ cursor: 'pointer',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ if (selectedWatchlistId !== watchlist.id) {+ e.currentTarget.style.backgroundColor = 'rgba(255,255,255,0.05)';+ }+ }}+ onMouseLeave={(e) => {+ if (selectedWatchlistId !== watchlist.id) {+ e.currentTarget.style.backgroundColor = 'rgba(255,255,255,0.02)';+ }+ }}+ >+ <div style={{ flex: 1 }}>+ <div style={{+ color: watchlist.color,+ fontWeight: 'bold',+ marginBottom: '2px'+ }}>+ {watchlist.name}+ </div>+ <div style={{+ color: CYAN,+ fontSize: '9px'+ }}>+ {watchlist.stock_count} stocks+ </div>+ </div>+ <button+ onClick={(e) => handleDelete(e, watchlist.id)}+ style={{+ background: 'transparent',+ border: 'none',+ color: RED,+ cursor: 'pointer',+ padding: '2px',+ display: 'flex'+ }}+ title={`Delete ${watchlist.name}`}+ >+ <Trash2 size={12} />+ </button>+ </button>+ ))+ )}+ </div>++ {/* Market Movers */}+ {marketMovers && marketMovers.gainers.length > 0 && (+ <div style={{+ borderTop: `1px solid ${GRAY}`,+ marginTop: '8px',+ paddingTop: '8px',+ marginBottom: '8px'+ }}>+ <div style={{+ color: YELLOW,+ fontSize: '10px',+ fontWeight: 'bold',+ marginBottom: '4px'+ }}>+ MARKET MOVERS+ </div>+ {marketMovers.gainers.slice(0, 3).map((item, index) => (+ <div+ key={`gainer-${index}`}+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ padding: '3px',+ marginBottom: '2px',+ backgroundColor: 'rgba(255,255,255,0.02)',+ fontSize: '9px'+ }}+ >+ <div>+ <span style={{ color: CYAN }}>{item.symbol}</span>+ <span style={{+ color: GRAY,+ marginLeft: '4px',+ fontSize: '8px'+ }}>+ [GAINER]+ </span>+ </div>+ <span style={{+ color: GREEN,+ fontWeight: 'bold'+ }}>+ +{item.quote?.change_percent.toFixed(2)}%+ </span>+ </div>+ ))}+ {marketMovers.losers.slice(0, 2).map((item, index) => (+ <div+ key={`loser-${index}`}+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ padding: '3px',+ marginBottom: '2px',+ backgroundColor: 'rgba(255,255,255,0.02)',+ fontSize: '9px'+ }}+ >+ <div>+ <span style={{ color: CYAN }}>{item.symbol}</span>+ <span style={{+ color: GRAY,+ marginLeft: '4px',+ fontSize: '8px'+ }}>+ [LOSER]+ </span>+ </div>+ <span style={{+ color: RED,+ fontWeight: 'bold'+ }}>+ {item.quote?.change_percent.toFixed(2)}%+ </span>+ </div>+ ))}+ </div>+ )}++ {/* Volume Leaders */}+ {volumeLeaders && volumeLeaders.length > 0 && (+ <div style={{+ borderTop: `1px solid ${GRAY}`,+ marginTop: '8px',+ paddingTop: '8px'+ }}>+ <div style={{+ color: YELLOW,+ fontSize: '10px',+ fontWeight: 'bold',+ marginBottom: '4px'+ }}>+ VOLUME LEADERS+ </div>+ {volumeLeaders.slice(0, 4).map((item, index) => {+ const volume = item.quote?.volume || 0;+ const volumeStr = volume >= 1_000_000+ ? `${(volume / 1_000_000).toFixed(1)}M`+ : volume >= 1_000+ ? `${(volume / 1_000).toFixed(1)}K`+ : volume.toString();++ return (+ <div+ key={`volume-${index}`}+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ padding: '3px',+ marginBottom: '2px',+ backgroundColor: 'rgba(255,255,255,0.02)',+ fontSize: '9px'+ }}+ >+ <span style={{ color: CYAN }}>{item.symbol}</span>+ <span style={{ color: WHITE }}>{volumeStr}</span>+ </div>+ );+ })}+ </div>+ )}+ </div>+ );+};++export default WatchlistSidebar;diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/utils.ts b/fincept-terminal-desktop/src/components/tabs/watchlist/utils.tsnew file mode 100644index 000000000..3b43906b5--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/utils.ts@@ -0,0 +1,119 @@+// Watchlist Utilities - Shared constants, formatting, and helper functions++// Bloomberg Color Scheme+export const BLOOMBERG_COLORS = {+ ORANGE: '#FFA500',+ WHITE: '#FFFFFF',+ RED: '#FF0000',+ GREEN: '#00C800',+ YELLOW: '#FFFF00',+ GRAY: '#787878',+ BLUE: '#6496FA',+ PURPLE: '#C864FF',+ CYAN: '#00FFFF',+ DARK_BG: '#000000',+ PANEL_BG: '#0a0a0a'+};++// Format currency values+export const formatCurrency = (value: number | undefined | null): string => {+ if (value === undefined || value === null) return 'N/A';+ return `$${value.toFixed(2)}`;+};++// Format percentage values+export const formatPercent = (value: number | undefined | null): string => {+ if (value === undefined || value === null) return 'N/A';+ const sign = value >= 0 ? '+' : '';+ return `${sign}${value.toFixed(2)}%`;+};++// Format large numbers (market cap, volume)+export const formatLargeNumber = (value: number | undefined | null): string => {+ if (value === undefined || value === null) return 'N/A';++ if (value >= 1_000_000_000_000) {+ return `${(value / 1_000_000_000_000).toFixed(2)}T`;+ } else if (value >= 1_000_000_000) {+ return `${(value / 1_000_000_000).toFixed(2)}B`;+ } else if (value >= 1_000_000) {+ return `${(value / 1_000_000).toFixed(1)}M`;+ } else if (value >= 1_000) {+ return `${(value / 1_000).toFixed(1)}K`;+ }++ return value.toFixed(0);+};++// Format volume+export const formatVolume = (value: number | undefined | null): string => {+ return formatLargeNumber(value);+};++// Get color based on value (positive/negative)+export const getChangeColor = (value: number | undefined | null): string => {+ if (value === undefined || value === null) return BLOOMBERG_COLORS.GRAY;+ return value >= 0 ? BLOOMBERG_COLORS.GREEN : BLOOMBERG_COLORS.RED;+};++// Sort stocks by different criteria+export type SortCriteria = 'TICKER' | 'CHANGE' | 'VOLUME' | 'PRICE';++export const sortStocks = <T extends { symbol: string; quote: any }>(+ stocks: T[],+ criteria: SortCriteria,+ ascending: boolean = false+): T[] => {+ const sorted = [...stocks];++ sorted.sort((a, b) => {+ let compareValue = 0;++ switch (criteria) {+ case 'TICKER':+ compareValue = a.symbol.localeCompare(b.symbol);+ break;+ case 'CHANGE':+ const changeA = a.quote?.change_percent || 0;+ const changeB = b.quote?.change_percent || 0;+ compareValue = changeB - changeA;+ break;+ case 'VOLUME':+ const volA = a.quote?.volume || 0;+ const volB = b.quote?.volume || 0;+ compareValue = volB - volA;+ break;+ case 'PRICE':+ const priceA = a.quote?.price || 0;+ const priceB = b.quote?.price || 0;+ compareValue = priceB - priceA;+ break;+ }++ return ascending ? -compareValue : compareValue;+ });++ return sorted;+};++// Default watchlist colors+export const WATCHLIST_COLORS = [+ '#FFA500', // Orange+ '#6496FA', // Blue+ '#00C800', // Green+ '#00FFFF', // Cyan+ '#C864FF', // Purple+ '#FFFF00', // Yellow+ '#FF0000', // Red+ '#FFFFFF', // White+];++// Get next available color for new watchlist+export const getNextWatchlistColor = (existingColors: string[]): string => {+ for (const color of WATCHLIST_COLORS) {+ if (!existingColors.includes(color)) {+ return color;+ }+ }+ return WATCHLIST_COLORS[0]; // Fallback to orange+};diff --git a/fincept-terminal-desktop/src/services/alertsService.ts b/fincept-terminal-desktop/src/services/alertsService.tsdeleted file mode 100644index 8a3aa3f6b..000000000--- a/fincept-terminal-desktop/src/services/alertsService.ts+++ /dev/null@@ -1,241 +0,0 @@-// Portfolio Alerts Service-// Manages price alerts and notifications for portfolio holdings--import Database from '@tauri-apps/plugin-sql';--export interface PriceAlert {- id: string;- portfolio_id: string;- symbol: string;- type: 'PRICE_TARGET' | 'STOP_LOSS' | 'TAKE_PROFIT' | 'PRICE_CHANGE';- condition: 'ABOVE' | 'BELOW' | 'PERCENT_UP' | 'PERCENT_DOWN';- target_value: number;- is_triggered: boolean;- created_at: string;- triggered_at?: string;- notes?: string;-}--class AlertsService {- private db: Database | null = null;- private dbPath = 'sqlite:fincept_terminal.db';- private isInitialized = false;-- async initialize(): Promise<void> {- if (this.isInitialized && this.db) {- return;- }-- try {- this.db = await Database.load(this.dbPath);- await this.createTable();- this.isInitialized = true;- console.log('[AlertsService] Initialized successfully');- } catch (error) {- console.error('[AlertsService] Initialization failed:', error);- throw error;- }- }-- private async createTable(): Promise<void> {- if (!this.db) throw new Error('Database not initialized');-- await this.db.execute(`- CREATE TABLE IF NOT EXISTS portfolio_alerts (- id TEXT PRIMARY KEY,- portfolio_id TEXT NOT NULL,- symbol TEXT NOT NULL,- type TEXT NOT NULL,- condition TEXT NOT NULL,- target_value REAL NOT NULL,- is_triggered INTEGER DEFAULT 0,- created_at TEXT DEFAULT (datetime('now')),- triggered_at TEXT,- notes TEXT,- FOREIGN KEY (portfolio_id) REFERENCES portfolios(id) ON DELETE CASCADE- )- `);-- await this.db.execute(`- CREATE INDEX IF NOT EXISTS idx_alerts_portfolio ON portfolio_alerts(portfolio_id)- `);-- await this.db.execute(`- CREATE INDEX IF NOT EXISTS idx_alerts_symbol ON portfolio_alerts(symbol)- `);- }-- private ensureInitialized(): void {- if (!this.db || !this.isInitialized) {- throw new Error('AlertsService not initialized. Call initialize() first.');- }- }-- /**- * Create a new price alert- */- async createAlert(- portfolioId: string,- symbol: string,- type: PriceAlert['type'],- condition: PriceAlert['condition'],- targetValue: number,- notes?: string- ): Promise<PriceAlert> {- this.ensureInitialized();-- const id = crypto.randomUUID();- await this.db!.execute(- `INSERT INTO portfolio_alerts (id, portfolio_id, symbol, type, condition, target_value, notes)- VALUES ($1, $2, $3, $4, $5, $6, $7)`,- [id, portfolioId, symbol, type, condition, targetValue, notes || null]- );-- const result = await this.db!.select<PriceAlert[]>(- 'SELECT * FROM portfolio_alerts WHERE id = $1',- [id]- );-- return this.mapAlert(result[0]);- }-- /**- * Get all alerts for a portfolio- */- async getPortfolioAlerts(portfolioId: string, includeTriggered: boolean = false): Promise<PriceAlert[]> {- this.ensureInitialized();-- const query = includeTriggered- ? 'SELECT * FROM portfolio_alerts WHERE portfolio_id = $1 ORDER BY created_at DESC'- : 'SELECT * FROM portfolio_alerts WHERE portfolio_id = $1 AND is_triggered = 0 ORDER BY created_at DESC';-- const results = await this.db!.select<any[]>(query, [portfolioId]);- return results.map(r => this.mapAlert(r));- }-- /**- * Get alerts for a specific symbol- */- async getSymbolAlerts(portfolioId: string, symbol: string): Promise<PriceAlert[]> {- this.ensureInitialized();-- const results = await this.db!.select<any[]>(- 'SELECT * FROM portfolio_alerts WHERE portfolio_id = $1 AND symbol = $2 AND is_triggered = 0 ORDER BY created_at DESC',- [portfolioId, symbol]- );-- return results.map(r => this.mapAlert(r));- }-- /**- * Delete an alert- */- async deleteAlert(alertId: string): Promise<void> {- this.ensureInitialized();-- await this.db!.execute('DELETE FROM portfolio_alerts WHERE id = $1', [alertId]);- console.log(`[AlertsService] Deleted alert: ${alertId}`);- }-- /**- * Trigger an alert- */- async triggerAlert(alertId: string): Promise<void> {- this.ensureInitialized();-- await this.db!.execute(- `UPDATE portfolio_alerts SET is_triggered = 1, triggered_at = datetime('now') WHERE id = $1`,- [alertId]- );-- console.log(`[AlertsService] Triggered alert: ${alertId}`);- }-- /**- * Check if price conditions are met and trigger alerts- */- async checkAlerts(symbol: string, currentPrice: number, portfolioId?: string): Promise<PriceAlert[]> {- this.ensureInitialized();-- const query = portfolioId- ? 'SELECT * FROM portfolio_alerts WHERE symbol = $1 AND portfolio_id = $2 AND is_triggered = 0'- : 'SELECT * FROM portfolio_alerts WHERE symbol = $1 AND is_triggered = 0';-- const params = portfolioId ? [symbol, portfolioId] : [symbol];- const alerts = await this.db!.select<any[]>(query, params);-- const triggeredAlerts: PriceAlert[] = [];-- for (const alert of alerts) {- let shouldTrigger = false;-- switch (alert.condition) {- case 'ABOVE':- shouldTrigger = currentPrice >= alert.target_value;- break;- case 'BELOW':- shouldTrigger = currentPrice <= alert.target_value;- break;- // PERCENT_UP and PERCENT_DOWN would need base price tracking- }-- if (shouldTrigger) {- await this.triggerAlert(alert.id);- triggeredAlerts.push(this.mapAlert(alert));- }- }-- return triggeredAlerts;- }-- /**- * Get alert statistics- */- async getAlertStats(portfolioId: string): Promise<{- total: number;- active: number;- triggered: number;- byType: Record<string, number>;- }> {- this.ensureInitialized();-- const alerts = await this.db!.select<any[]>(- 'SELECT * FROM portfolio_alerts WHERE portfolio_id = $1',- [portfolioId]- );-- const stats = {- total: alerts.length,- active: alerts.filter(a => a.is_triggered === 0).length,- triggered: alerts.filter(a => a.is_triggered === 1).length,- byType: {} as Record<string, number>- };-- alerts.forEach(alert => {- stats.byType[alert.type] = (stats.byType[alert.type] || 0) + 1;- });-- return stats;- }-- /**- * Map database row to PriceAlert- */- private mapAlert(row: any): PriceAlert {- return {- ...row,- is_triggered: row.is_triggered === 1- };- }-- /**- * Check if service is ready- */- isReady(): boolean {- return this.isInitialized && this.db !== null;- }-}--// Export singleton instance-export const alertsService = new AlertsService();-export default alertsService;diff --git a/fincept-terminal-desktop/src/services/llmApi.ts b/fincept-terminal-desktop/src/services/llmApi.tsindex 18799eef4..94927c5f9 100644--- a/fincept-terminal-desktop/src/services/llmApi.ts+++ b/fincept-terminal-desktop/src/services/llmApi.ts@@ -502,10 +502,11 @@ class LLMApiService {];// Convert MCP tools to OpenAI function format+ // Prefix tool name with serverId for proper routingconst functions = tools.map(tool => ({type: 'function',function: {- name: tool.name,+ name: `${tool.serverId}__${tool.name}`, // Format: serverId__toolNamedescription: tool.description || '',parameters: tool.inputSchema || { type: 'object', properties: {} }}diff --git a/fincept-terminal-desktop/src/services/mcpManager.ts b/fincept-terminal-desktop/src/services/mcpManager.tsindex 2fe520d7d..4601fa687 100644--- a/fincept-terminal-desktop/src/services/mcpManager.ts+++ b/fincept-terminal-desktop/src/services/mcpManager.ts@@ -50,7 +50,35 @@ class MCPManager {try {console.log(`[MCPManager] Installing server: ${config.name}`);- // Add to database+ // Check if server already exists+ const existing = await sqliteService.getMCPServer(config.id);++ if (existing) {+ console.log(`[MCPManager] Server ${config.id} already installed, updating config...`);++ // Update existing server config+ await sqliteService.updateMCPServerConfig(config.id, {+ env: config.env+ });++ // Restart if running+ if (this.clients.has(config.id)) {+ await this.stopServer(config.id);+ }++ // Try to start with new config+ try {+ await this.startServer(config.id);+ } catch (startError) {+ console.warn(`[MCPManager] Failed to start existing server: ${startError}`);+ // Don't throw - server is already installed+ }++ console.log(`[MCPManager] Server ${config.name} updated successfully`);+ return;+ }++ // Add new server to databaseawait sqliteService.addMCPServer({id: config.id,name: config.name,@@ -63,8 +91,13 @@ class MCPManager {enabled: true});- // Try to start the server immediately- await this.startServer(config.id);+ // Try to start the server (don't fail install if start fails)+ try {+ await this.startServer(config.id);+ } catch (startError) {+ console.warn(`[MCPManager] Server installed but failed to start: ${startError}`);+ // Server is installed, just not running - this is OK+ }console.log(`[MCPManager] Server ${config.name} installed successfully`);} catch (error) {@@ -344,59 +377,57 @@ class MCPManager {clearInterval(this.healthCheckInterval);}- this.healthCheckInterval = setInterval(async () => {- for (const [serverId, client] of this.clients.entries()) {- try {- const isAlive = await client.ping();-- if (!isAlive) {- console.warn(`[MCPManager] Server ${serverId} is not responding`);-- // Get server config to check if we should auto-restart- const server = await sqliteService.getMCPServer(serverId);-- if (server && server.enabled) {- const errorInfo = this.serverErrors.get(serverId) || { count: 0, lastError: '', lastErrorTime: 0 };-- // Only attempt restart if we haven't exceeded max retries (3)- if (errorInfo.count < 3) {- console.log(`[MCPManager] Attempting automatic restart of ${serverId} (attempt ${errorInfo.count + 1}/3)`);-- try {- // Stop and restart- await this.stopServer(serverId);- await this.startServer(serverId);- console.log(`[MCPManager] Successfully restarted ${serverId}`);- } catch (restartError) {- console.error(`[MCPManager] Failed to restart ${serverId}:`, restartError);+ // Only start health check after servers have had time to initialize+ setTimeout(() => {+ this.healthCheckInterval = setInterval(async () => {+ for (const [serverId, client] of this.clients.entries()) {+ try {+ const isAlive = await client.ping();++ if (!isAlive) {+ console.warn(`[MCPManager] Server ${serverId} is not responding`);++ // Get server config to check if we should auto-restart+ const server = await sqliteService.getMCPServer(serverId);++ if (server && server.enabled) {+ const errorInfo = this.serverErrors.get(serverId) || { count: 0, lastError: '', lastErrorTime: 0 };++ // Only restart if last error was more than 5 minutes ago (avoid rapid restart loops)+ const timeSinceLastError = Date.now() - errorInfo.lastErrorTime;+ const shouldRetry = errorInfo.count < 3 && timeSinceLastError > 300000; // 5 minutes++ if (shouldRetry) {+ console.log(`[MCPManager] Attempting automatic restart of ${serverId} (attempt ${errorInfo.count + 1}/3)`);++ try {+ // Stop and restart+ await this.stopServer(serverId);+ await this.startServer(serverId);+ console.log(`[MCPManager] Successfully restarted ${serverId}`);+ } catch (restartError) {+ console.error(`[MCPManager] Failed to restart ${serverId}:`, restartError);+ }+ } else if (errorInfo.count >= 3) {+ console.error(`[MCPManager] Server ${serverId} exceeded max restart attempts (3)`);+ await sqliteService.updateMCPServerStatus(serverId, 'error');}} else {- console.error(`[MCPManager] Server ${serverId} exceeded max restart attempts (3)`);await sqliteService.updateMCPServerStatus(serverId, 'error');}} else {- await sqliteService.updateMCPServerStatus(serverId, 'error');- }- } else {- // Server is healthy, clear any error tracking- if (this.serverErrors.has(serverId)) {- this.serverErrors.delete(serverId);+ // Server is healthy, clear any error tracking+ if (this.serverErrors.has(serverId)) {+ this.serverErrors.delete(serverId);+ }}+ } catch (error) {+ // Don't track errors during health check - too noisy+ console.debug(`[MCPManager] Health check failed for ${serverId}:`, error);}- } catch (error) {- console.error(`[MCPManager] Health check failed for ${serverId}:`, error);-- // Track the error- const errorMsg = error instanceof Error ? error.message : 'Unknown error';- const existing = this.serverErrors.get(serverId) || { count: 0, lastError: '', lastErrorTime: 0 };- this.serverErrors.set(serverId, {- count: existing.count + 1,- lastError: errorMsg,- lastErrorTime: Date.now()- });}- }- }, 30000); // Check every 30 seconds+ }, 60000); // Check every 60 seconds (less aggressive)+ }, 10000); // Wait 10 seconds before starting health checks}// Get server health infodiff --git a/fincept-terminal-desktop/src/services/mcpToolService.ts b/fincept-terminal-desktop/src/services/mcpToolService.tsnew file mode 100644index 000000000..aaf75c122--- /dev/null+++ b/fincept-terminal-desktop/src/services/mcpToolService.ts@@ -0,0 +1,337 @@+// MCP Tool Service - Unified interface for MCP tool access across all tabs+// Provides fault-tolerant, modular access to MCP tools for Chat, Node Editor, and Agents++import { mcpManager } from './mcpManager';++export interface MCPTool {+ serverId: string;+ serverName: string;+ name: string;+ description?: string;+ inputSchema?: {+ type: string;+ properties?: Record<string, any>;+ required?: string[];+ };+}++export interface MCPToolExecutionResult {+ success: boolean;+ data?: any;+ error?: string;+ toolName: string;+ serverId: string;+ executionTime?: number;+}++export interface MCPToolValidationResult {+ valid: boolean;+ errors: string[];+ missingRequired: string[];+}++export type MCPToolCategory = 'database' | 'web' | 'file' | 'api' | 'data' | 'productivity' | 'other';++class MCPToolService {+ private toolCache: MCPTool[] = [];+ private cacheTimestamp: number = 0;+ private cacheTTL: number = 5000; // 5 seconds cache++ /**+ * Get all available MCP tools from running servers+ * Uses caching to reduce frequent calls+ */+ async getAllTools(): Promise<MCPTool[]> {+ try {+ const now = Date.now();++ // Return cached tools if still valid+ if (this.toolCache.length > 0 && (now - this.cacheTimestamp) < this.cacheTTL) {+ console.log('[MCPToolService] Returning cached tools:', this.toolCache.length);+ return this.toolCache;+ }++ // Fetch fresh tools+ const tools = await mcpManager.getAllTools();+ this.toolCache = tools;+ this.cacheTimestamp = now;++ console.log('[MCPToolService] Fetched fresh tools:', tools.length);+ return tools;+ } catch (error) {+ console.error('[MCPToolService] Error fetching tools:', error);+ // Return cached tools as fallback+ return this.toolCache;+ }+ }++ /**+ * Execute an MCP tool directly without LLM assistance+ * Used by Node Editor for direct tool execution+ */+ async executeToolDirect(+ serverId: string,+ toolName: string,+ params: Record<string, any>+ ): Promise<MCPToolExecutionResult> {+ const startTime = Date.now();++ try {+ console.log(`[MCPToolService] Executing tool directly: ${serverId}.${toolName}`, params);++ // Validate tool exists+ const tools = await this.getAllTools();+ const tool = tools.find(t => t.serverId === serverId && t.name === toolName);++ if (!tool) {+ return {+ success: false,+ error: `Tool not found: ${serverId}.${toolName}`,+ toolName,+ serverId+ };+ }++ // Validate parameters+ const validation = this.validateToolParams(tool, params);+ if (!validation.valid) {+ return {+ success: false,+ error: `Invalid parameters: ${validation.errors.join(', ')}`,+ toolName,+ serverId+ };+ }++ // Execute tool+ const result = await mcpManager.callTool(serverId, toolName, params);+ const executionTime = Date.now() - startTime;++ console.log(`[MCPToolService] Tool executed successfully in ${executionTime}ms`);++ return {+ success: true,+ data: result,+ toolName,+ serverId,+ executionTime+ };+ } catch (error: any) {+ const executionTime = Date.now() - startTime;+ console.error(`[MCPToolService] Tool execution failed:`, error);++ return {+ success: false,+ error: error.message || 'Unknown error during tool execution',+ toolName,+ serverId,+ executionTime+ };+ }+ }++ /**+ * Get tools filtered by category+ * Used to show relevant tools in different contexts+ */+ async getToolsByCategory(category: MCPToolCategory): Promise<MCPTool[]> {+ try {+ const allTools = await this.getAllTools();+ return allTools.filter(tool => this.categorizeTool(tool) === category);+ } catch (error) {+ console.error('[MCPToolService] Error filtering tools by category:', error);+ return [];+ }+ }++ /**+ * Get tools from a specific server+ */+ async getToolsByServer(serverId: string): Promise<MCPTool[]> {+ try {+ const allTools = await this.getAllTools();+ return allTools.filter(tool => tool.serverId === serverId);+ } catch (error) {+ console.error('[MCPToolService] Error filtering tools by server:', error);+ return [];+ }+ }++ /**+ * Validate tool parameters against schema+ */+ validateToolParams(tool: MCPTool, params: Record<string, any>): MCPToolValidationResult {+ const errors: string[] = [];+ const missingRequired: string[] = [];++ // If no schema, assume valid+ if (!tool.inputSchema || !tool.inputSchema.properties) {+ return { valid: true, errors: [], missingRequired: [] };+ }++ const schema = tool.inputSchema;+ const required = schema.required || [];++ // Check required parameters+ for (const reqParam of required) {+ if (!(reqParam in params) || params[reqParam] === undefined || params[reqParam] === '') {+ missingRequired.push(reqParam);+ errors.push(`Missing required parameter: ${reqParam}`);+ }+ }++ // Basic type validation+ if (schema.properties) {+ for (const [key, value] of Object.entries(params)) {+ if (schema.properties[key]) {+ const expectedType = schema.properties[key].type;+ const actualType = typeof value;++ // Simple type checking+ if (expectedType === 'string' && actualType !== 'string') {+ errors.push(`Parameter '${key}' should be string, got ${actualType}`);+ } else if (expectedType === 'number' && actualType !== 'number') {+ errors.push(`Parameter '${key}' should be number, got ${actualType}`);+ } else if (expectedType === 'boolean' && actualType !== 'boolean') {+ errors.push(`Parameter '${key}' should be boolean, got ${actualType}`);+ }+ }+ }+ }++ return {+ valid: errors.length === 0,+ errors,+ missingRequired+ };+ }++ /**+ * Categorize a tool based on server ID and tool name+ */+ private categorizeTool(tool: MCPTool): MCPToolCategory {+ const serverId = tool.serverId.toLowerCase();+ const toolName = tool.name.toLowerCase();++ // Database tools+ if (serverId.includes('postgres') || serverId.includes('questdb') ||+ serverId.includes('sqlite') || serverId.includes('mysql') ||+ toolName.includes('query') || toolName.includes('database')) {+ return 'database';+ }++ // Web tools+ if (serverId.includes('wikipedia') || serverId.includes('search') ||+ serverId.includes('fetch') || serverId.includes('brave') ||+ toolName.includes('search') || toolName.includes('fetch')) {+ return 'web';+ }++ // File tools+ if (serverId.includes('filesystem') || serverId.includes('file') ||+ toolName.includes('read') || toolName.includes('write') || toolName.includes('file')) {+ return 'file';+ }++ // API tools+ if (serverId.includes('api') || serverId.includes('http') ||+ toolName.includes('api') || toolName.includes('request')) {+ return 'api';+ }++ // Data tools+ if (toolName.includes('data') || toolName.includes('analyze') ||+ toolName.includes('transform')) {+ return 'data';+ }++ // Productivity tools+ if (serverId.includes('slack') || serverId.includes('email') ||+ serverId.includes('calendar') || serverId.includes('notion')) {+ return 'productivity';+ }++ return 'other';+ }++ /**+ * Get a specific tool by server and name+ */+ async getTool(serverId: string, toolName: string): Promise<MCPTool | null> {+ try {+ const tools = await this.getAllTools();+ return tools.find(t => t.serverId === serverId && t.name === toolName) || null;+ } catch (error) {+ console.error('[MCPToolService] Error getting tool:', error);+ return null;+ }+ }++ /**+ * Check if a specific tool is available+ */+ async isToolAvailable(serverId: string, toolName: string): Promise<boolean> {+ const tool = await this.getTool(serverId, toolName);+ return tool !== null;+ }++ /**+ * Get all available server IDs+ */+ async getAvailableServers(): Promise<string[]> {+ try {+ const tools = await this.getAllTools();+ const serverIds = new Set(tools.map(t => t.serverId));+ return Array.from(serverIds);+ } catch (error) {+ console.error('[MCPToolService] Error getting available servers:', error);+ return [];+ }+ }++ /**+ * Clear tool cache (useful when servers are added/removed)+ */+ clearCache(): void {+ console.log('[MCPToolService] Clearing tool cache');+ this.toolCache = [];+ this.cacheTimestamp = 0;+ }++ /**+ * Format tools for OpenAI function calling+ * Used by Chat tab and Agents tab+ */+ formatToolsForOpenAI(tools: MCPTool[]): any[] {+ return tools.map(tool => ({+ type: 'function' as const,+ function: {+ name: `${tool.serverId}__${tool.name}`,+ description: tool.description || `Tool: ${tool.name} from ${tool.serverId}`,+ parameters: tool.inputSchema || {+ type: 'object',+ properties: {},+ required: []+ }+ }+ }));+ }++ /**+ * Parse OpenAI function name back to serverId and toolName+ */+ parseOpenAIFunctionName(functionName: string): { serverId: string; toolName: string } | null {+ const parts = functionName.split('__');+ if (parts.length !== 2) {+ console.error('[MCPToolService] Invalid function name format:', functionName);+ return null;+ }+ return {+ serverId: parts[0],+ toolName: parts[1]+ };+ }+}++// Export singleton instance+export const mcpToolService = new MCPToolService();diff --git a/fincept-terminal-desktop/src/services/sqliteService.ts b/fincept-terminal-desktop/src/services/sqliteService.tsindex 7c36730fd..c8d9d695f 100644--- a/fincept-terminal-desktop/src/services/sqliteService.ts+++ b/fincept-terminal-desktop/src/services/sqliteService.ts@@ -321,6 +321,30 @@ class SQLiteService {)`);+ // Watchlist tables+ await this.db.execute(`+ CREATE TABLE IF NOT EXISTS watchlists (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT,+ color TEXT DEFAULT '#FFA500',+ created_at TEXT DEFAULT (datetime('now')),+ updated_at TEXT DEFAULT (datetime('now'))+ )+ `);++ await this.db.execute(`+ CREATE TABLE IF NOT EXISTS watchlist_stocks (+ id TEXT PRIMARY KEY,+ watchlist_id TEXT NOT NULL,+ symbol TEXT NOT NULL,+ added_at TEXT DEFAULT (datetime('now')),+ notes TEXT,+ FOREIGN KEY (watchlist_id) REFERENCES watchlists(id) ON DELETE CASCADE,+ UNIQUE(watchlist_id, symbol)+ )+ `);+// Create indexesawait this.db.execute(`CREATE INDEX IF NOT EXISTS idx_credentials_service ON credentials(service_name)`);await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_settings_category ON settings(category)`);@@ -336,6 +360,8 @@ class SQLiteService {await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_portfolio_transactions_date ON portfolio_transactions(transaction_date DESC)`);await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_portfolio_snapshots_portfolio ON portfolio_snapshots(portfolio_id)`);await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_portfolio_snapshots_date ON portfolio_snapshots(snapshot_date DESC)`);+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_watchlist_stocks_watchlist ON watchlist_stocks(watchlist_id)`);+ await this.db.execute(`CREATE INDEX IF NOT EXISTS idx_watchlist_stocks_symbol ON watchlist_stocks(symbol)`);}private async seedDefaultSettings(): Promise<void> {diff --git a/fincept-terminal-desktop/src/services/watchlistService.ts b/fincept-terminal-desktop/src/services/watchlistService.tsnew file mode 100644index 000000000..52e2aa4f4--- /dev/null+++ b/fincept-terminal-desktop/src/services/watchlistService.ts@@ -0,0 +1,429 @@+// Watchlist Service - Manages watchlists and stock tracking for Fincept Terminal+// Handles watchlist CRUD, stock management, and live market data integration++import Database from '@tauri-apps/plugin-sql';+import { marketDataService, QuoteData } from './marketDataService';++// ==================== TYPES ====================++export interface Watchlist {+ id: string;+ name: string;+ description?: string;+ color: string;+ created_at: string;+ updated_at: string;+}++export interface WatchlistStock {+ id: string;+ watchlist_id: string;+ symbol: string;+ added_at: string;+ notes?: string;+}++export interface WatchlistStockWithQuote extends WatchlistStock {+ quote: QuoteData | null;+}++export interface WatchlistWithStocks {+ watchlist: Watchlist;+ stocks: WatchlistStockWithQuote[];+ stock_count: number;+}++// ==================== WATCHLIST SERVICE CLASS ====================++class WatchlistService {+ private db: Database | null = null;+ private dbPath = 'sqlite:fincept_terminal.db';+ private isInitialized = false;++ /**+ * Initialize database connection+ */+ async initialize(): Promise<void> {+ if (this.isInitialized && this.db) {+ return;+ }++ try {+ this.db = await Database.load(this.dbPath);+ this.isInitialized = true;+ console.log('[WatchlistService] Initialized successfully');+ } catch (error) {+ console.error('[WatchlistService] Initialization failed:', error);+ throw error;+ }+ }++ /**+ * Ensure database is initialized+ */+ private ensureInitialized(): void {+ if (!this.db || !this.isInitialized) {+ throw new Error('WatchlistService not initialized. Call initialize() first.');+ }+ }++ // ==================== WATCHLIST CRUD ====================++ /**+ * Create a new watchlist+ */+ async createWatchlist(name: string, description?: string, color: string = '#FFA500'): Promise<Watchlist> {+ this.ensureInitialized();++ const id = crypto.randomUUID();+ await this.db!.execute(+ `INSERT INTO watchlists (id, name, description, color)+ VALUES ($1, $2, $3, $4)`,+ [id, name, description || null, color]+ );++ const result = await this.db!.select<Watchlist[]>(+ 'SELECT * FROM watchlists WHERE id = $1',+ [id]+ );++ console.log(`[WatchlistService] Created watchlist: ${name} (ID: ${id})`);+ return result[0];+ }++ /**+ * Get all watchlists+ */+ async getWatchlists(): Promise<Watchlist[]> {+ this.ensureInitialized();++ const watchlists = await this.db!.select<Watchlist[]>(+ 'SELECT * FROM watchlists ORDER BY created_at DESC'+ );++ return watchlists;+ }++ /**+ * Get watchlist by ID+ */+ async getWatchlist(watchlistId: string): Promise<Watchlist | null> {+ this.ensureInitialized();++ const result = await this.db!.select<Watchlist[]>(+ 'SELECT * FROM watchlists WHERE id = $1',+ [watchlistId]+ );++ return result.length > 0 ? result[0] : null;+ }++ /**+ * Update watchlist+ */+ async updateWatchlist(watchlistId: string, updates: Partial<Omit<Watchlist, 'id' | 'created_at' | 'updated_at'>>): Promise<void> {+ this.ensureInitialized();++ const sets: string[] = [];+ const values: any[] = [];++ if (updates.name !== undefined) {+ sets.push('name = $' + (values.length + 1));+ values.push(updates.name);+ }+ if (updates.description !== undefined) {+ sets.push('description = $' + (values.length + 1));+ values.push(updates.description);+ }+ if (updates.color !== undefined) {+ sets.push('color = $' + (values.length + 1));+ values.push(updates.color);+ }++ if (sets.length > 0) {+ sets.push("updated_at = datetime('now')");+ values.push(watchlistId);++ await this.db!.execute(+ `UPDATE watchlists SET ${sets.join(', ')} WHERE id = $${values.length}`,+ values+ );+ }+ }++ /**+ * Delete watchlist (cascades to stocks)+ */+ async deleteWatchlist(watchlistId: string): Promise<void> {+ this.ensureInitialized();++ await this.db!.execute('DELETE FROM watchlists WHERE id = $1', [watchlistId]);+ console.log(`[WatchlistService] Deleted watchlist: ${watchlistId}`);+ }++ // ==================== STOCK MANAGEMENT ====================++ /**+ * Add stock to watchlist+ */+ async addStock(watchlistId: string, symbol: string, notes?: string): Promise<WatchlistStock> {+ this.ensureInitialized();++ // Check if stock already exists in watchlist+ const existing = await this.db!.select<WatchlistStock[]>(+ 'SELECT * FROM watchlist_stocks WHERE watchlist_id = $1 AND symbol = $2',+ [watchlistId, symbol]+ );++ if (existing.length > 0) {+ throw new Error(`Stock ${symbol} already exists in watchlist`);+ }++ const id = crypto.randomUUID();+ await this.db!.execute(+ `INSERT INTO watchlist_stocks (id, watchlist_id, symbol, notes)+ VALUES ($1, $2, $3, $4)`,+ [id, watchlistId, symbol.toUpperCase(), notes || null]+ );++ const result = await this.db!.select<WatchlistStock[]>(+ 'SELECT * FROM watchlist_stocks WHERE id = $1',+ [id]+ );++ console.log(`[WatchlistService] Added stock ${symbol} to watchlist ${watchlistId}`);+ return result[0];+ }++ /**+ * Remove stock from watchlist+ */+ async removeStock(watchlistId: string, symbol: string): Promise<void> {+ this.ensureInitialized();++ await this.db!.execute(+ 'DELETE FROM watchlist_stocks WHERE watchlist_id = $1 AND symbol = $2',+ [watchlistId, symbol.toUpperCase()]+ );++ console.log(`[WatchlistService] Removed stock ${symbol} from watchlist ${watchlistId}`);+ }++ /**+ * Update stock notes+ */+ async updateStockNotes(watchlistId: string, symbol: string, notes: string): Promise<void> {+ this.ensureInitialized();++ await this.db!.execute(+ 'UPDATE watchlist_stocks SET notes = $1 WHERE watchlist_id = $2 AND symbol = $3',+ [notes, watchlistId, symbol.toUpperCase()]+ );+ }++ /**+ * Get all stocks in a watchlist+ */+ async getWatchlistStocks(watchlistId: string): Promise<WatchlistStock[]> {+ this.ensureInitialized();++ return await this.db!.select<WatchlistStock[]>(+ 'SELECT * FROM watchlist_stocks WHERE watchlist_id = $1 ORDER BY added_at DESC',+ [watchlistId]+ );+ }++ /**+ * Get watchlist stocks with live market quotes+ */+ async getWatchlistStocksWithQuotes(watchlistId: string): Promise<WatchlistStockWithQuote[]> {+ this.ensureInitialized();++ const stocks = await this.getWatchlistStocks(watchlistId);++ if (stocks.length === 0) {+ return [];+ }++ // Fetch quotes for all symbols+ const symbols = stocks.map(s => s.symbol);+ const quotes = await marketDataService.getQuotes(symbols);++ // Map quotes to stocks+ const quoteMap = new Map<string, QuoteData>();+ quotes.forEach(quote => {+ quoteMap.set(quote.symbol, quote);+ });++ return stocks.map(stock => ({+ ...stock,+ quote: quoteMap.get(stock.symbol) || null+ }));+ }++ /**+ * Get complete watchlist with stocks and quotes+ */+ async getWatchlistWithStocks(watchlistId: string): Promise<WatchlistWithStocks | null> {+ this.ensureInitialized();++ const watchlist = await this.getWatchlist(watchlistId);+ if (!watchlist) {+ return null;+ }++ const stocks = await this.getWatchlistStocksWithQuotes(watchlistId);++ return {+ watchlist,+ stocks,+ stock_count: stocks.length+ };+ }++ /**+ * Get all watchlists with stock counts+ */+ async getWatchlistsWithCounts(): Promise<Array<Watchlist & { stock_count: number }>> {+ this.ensureInitialized();++ const watchlists = await this.getWatchlists();++ const withCounts = await Promise.all(+ watchlists.map(async (watchlist) => {+ const stocks = await this.getWatchlistStocks(watchlist.id);+ return {+ ...watchlist,+ stock_count: stocks.length+ };+ })+ );++ return withCounts;+ }++ // ==================== MARKET DATA HELPERS ====================++ /**+ * Get market movers (top gainers and losers) from all watchlists+ */+ async getMarketMovers(limit: number = 5): Promise<{+ gainers: WatchlistStockWithQuote[];+ losers: WatchlistStockWithQuote[];+ }> {+ this.ensureInitialized();++ // Get all unique symbols from all watchlists+ const allStocks = await this.db!.select<{ symbol: string }[]>(+ 'SELECT DISTINCT symbol FROM watchlist_stocks'+ );++ if (allStocks.length === 0) {+ return { gainers: [], losers: [] };+ }++ const symbols = allStocks.map(s => s.symbol);+ const quotes = await marketDataService.getQuotes(symbols);++ // Sort by change percent+ const sortedQuotes = quotes.sort((a, b) => b.change_percent - a.change_percent);++ const gainers = sortedQuotes.slice(0, limit).map(quote => ({+ id: '',+ watchlist_id: '',+ symbol: quote.symbol,+ added_at: '',+ quote+ }));++ const losers = sortedQuotes.slice(-limit).reverse().map(quote => ({+ id: '',+ watchlist_id: '',+ symbol: quote.symbol,+ added_at: '',+ quote+ }));++ return { gainers, losers };+ }++ /**+ * Get volume leaders from all watchlists+ */+ async getVolumeLeaders(limit: number = 5): Promise<WatchlistStockWithQuote[]> {+ this.ensureInitialized();++ const allStocks = await this.db!.select<{ symbol: string }[]>(+ 'SELECT DISTINCT symbol FROM watchlist_stocks'+ );++ if (allStocks.length === 0) {+ return [];+ }++ const symbols = allStocks.map(s => s.symbol);+ const quotes = await marketDataService.getQuotes(symbols);++ // Sort by volume+ const sortedQuotes = quotes+ .filter(q => q.volume !== undefined && q.volume !== null)+ .sort((a, b) => (b.volume || 0) - (a.volume || 0));++ return sortedQuotes.slice(0, limit).map(quote => ({+ id: '',+ watchlist_id: '',+ symbol: quote.symbol,+ added_at: '',+ quote+ }));+ }++ // ==================== EXPORT ====================++ /**+ * Export watchlist as CSV+ */+ async exportWatchlistCSV(watchlistId: string): Promise<string> {+ const data = await this.getWatchlistWithStocks(watchlistId);++ if (!data) {+ throw new Error('Watchlist not found');+ }++ let csv = 'Symbol,Price,Change,Change %,Volume,High,Low,Open,Prev Close,Notes\n';++ data.stocks.forEach(stock => {+ const q = stock.quote;+ if (q) {+ csv += `${stock.symbol},${q.price.toFixed(2)},${q.change.toFixed(2)},${q.change_percent.toFixed(2)},${q.volume || 'N/A'},${q.high?.toFixed(2) || 'N/A'},${q.low?.toFixed(2) || 'N/A'},${q.open?.toFixed(2) || 'N/A'},${q.previous_close?.toFixed(2) || 'N/A'},"${stock.notes || ''}"\n`;+ } else {+ csv += `${stock.symbol},N/A,N/A,N/A,N/A,N/A,N/A,N/A,N/A,"${stock.notes || ''}"\n`;+ }+ });++ return csv;+ }++ // ==================== UTILITY ====================++ /**+ * Check if service is ready+ */+ isReady(): boolean {+ return this.isInitialized && this.db !== null;+ }++ /**+ * Get service status+ */+ getStatus(): { initialized: boolean; ready: boolean } {+ return {+ initialized: this.isInitialized,+ ready: this.isReady()+ };+ }+}++// Export singleton instance+export const watchlistService = new WatchlistService();+export default watchlistService;