-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
2349 lines (1993 loc) · 92.3 KB
/
server.py
File metadata and controls
2349 lines (1993 loc) · 92.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Coreflux MQTT MCP Server
A Model Context Protocol (MCP) server that provides integration between Claude and Coreflux MQTT broker.
Supports dynamic action discovery, LOT code generation, and comprehensive MQTT operations.
SECURITY NOTE: This server implements comprehensive log sanitization to prevent sensitive information
(passwords, API keys, certificates, file paths) from being exposed in log files. All logging
functions use automatic sanitization via the safe_log() function and SENSITIVE_PATTERNS.
See SECURITY_LOGGING.md for detailed documentation on log sanitization features.
"""
from mcp.server.fastmcp import FastMCP, Context
import os
import paho.mqtt.client as mqtt
import uuid
import argparse
import requests
import json
import logging
import sys
import time
import threading
from datetime import datetime
from dotenv import load_dotenv
from parser import process_json_rpc_message
from typing import Optional
import pydantic
from pydantic import BaseModel, validator
import re
# Define a custom NONE logging level (higher than CRITICAL)
NONE_LEVEL = 100 # Higher than CRITICAL (50)
logging.addLevelName(NONE_LEVEL, "NONE")
# Log sanitization patterns
SENSITIVE_PATTERNS = [
# API Keys and tokens (more comprehensive)
(r'Bearer\s+[A-Za-z0-9\-._~+/]+=*', 'Bearer [REDACTED]'),
(r'api[_-]?key["\']?\s*[:=]\s*["\']?[A-Za-z0-9\-._~+/]{8,}["\']?', 'api_key: [REDACTED]'),
(r'token["\']?\s*[:=]\s*["\']?[A-Za-z0-9\-._~+/]{8,}["\']?', 'token: [REDACTED]'),
(r'secret["\']?\s*[:=]\s*["\']?[A-Za-z0-9\-._~+/]{8,}["\']?', 'secret: [REDACTED]'),
(r'authorization["\']?\s*[:=]\s*["\']?[A-Za-z0-9\-._~+/]{8,}["\']?', 'authorization: [REDACTED]'),
# Passwords (more patterns)
(r'password["\']?\s*[:=]\s*["\']?[^"\'\s]{3,}["\']?', 'password: [REDACTED]'),
(r'passwd["\']?\s*[:=]\s*["\']?[^"\'\s]{3,}["\']?', 'passwd: [REDACTED]'),
(r'pwd["\']?\s*[:=]\s*["\']?[^"\'\s]{3,}["\']?', 'pwd: [REDACTED]'),
(r'pass["\']?\s*[:=]\s*["\']?[^"\'\s]{3,}["\']?', 'pass: [REDACTED]'),
# File paths (more comprehensive)
(r'[C-Z]:\\[^"\'\s]*(?:key|cert|crt|pem|p12|pfx)[^"\'\s]*', '[CERT_PATH_REDACTED]'),
(r'[C-Z]:\\Users\\[^\\]+\\[^"\'\s]*', '[USER_PATH_REDACTED]'),
(r'[C-Z]:\\[^"\'\s]+', '[PATH_REDACTED]'),
(r'/(?:home|root|usr|opt|etc|var)/[^"\'\s]*(?:key|cert|crt|pem|p12|pfx)[^"\'\s]*', '[CERT_PATH_REDACTED]'),
(r'/(?:home|root)/[^/]+/[^"\'\s]*', '[USER_PATH_REDACTED]'),
(r'/(?:home|root|usr|opt|etc|var)/[^"\'\s]+', '[PATH_REDACTED]'),
# URLs with credentials
(r'https?://[^:\s]+:[^@\s]+@[^/\s]+', 'https://[USER]:[PASS]@[HOST]'),
(r'ftp://[^:\s]+:[^@\s]+@[^/\s]+', 'ftp://[USER]:[PASS]@[HOST]'),
# Connection strings
(r'mongodb://[^:\s]+:[^@\s]+@[^/\s]+', 'mongodb://[USER]:[PASS]@[HOST]'),
(r'mysql://[^:\s]+:[^@\s]+@[^/\s]+', 'mysql://[USER]:[PASS]@[HOST]'),
(r'postgresql://[^:\s]+:[^@\s]+@[^/\s]+', 'postgresql://[USER]:[PASS]@[HOST]'),
# Certificate content
(r'-----BEGIN[^-]+-----[^-]+-----END[^-]+-----', '[CERTIFICATE_REDACTED]'),
# MQTT message content that might contain sensitive data
(r'"payload":\s*"[^"]{100,}"', '"payload": "[PAYLOAD_REDACTED]"'),
# Long hex strings (likely keys/hashes)
(r'\b[A-Fa-f0-9]{32,}\b', '[HEX_REDACTED]'),
# JWT tokens
(r'eyJ[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]*', '[JWT_REDACTED]'),
# Base64 encoded data (likely sensitive if > 32 chars)
(r'[A-Za-z0-9+/]{32,}={0,2}', '[BASE64_REDACTED]'),
]
def sanitize_log_message(message: str) -> str:
"""
Sanitize log messages to remove sensitive information.
Args:
message: The original log message
Returns:
Sanitized log message with sensitive data redacted
"""
if not isinstance(message, str):
message = str(message)
sanitized = message
for pattern, replacement in SENSITIVE_PATTERNS:
sanitized = re.sub(pattern, replacement, sanitized, flags=re.IGNORECASE)
return sanitized
def safe_log(logger_func, message: str, *args, **kwargs):
"""
Safely log a message with automatic sanitization.
Args:
logger_func: The logger function (logger.info, logger.error, etc.)
message: The message to log
*args: Additional arguments for the logger
**kwargs: Additional keyword arguments for the logger
"""
try:
sanitized_message = sanitize_log_message(message)
logger_func(sanitized_message, *args, **kwargs)
except Exception as e:
# Fallback to basic logging if sanitization fails
try:
logger_func(f"[LOG_SANITIZATION_ERROR] Original message redacted due to sanitization error: {str(e)}")
except:
pass # Give up if even basic logging fails
def sanitize_function_args(**kwargs) -> dict:
"""
Sanitize function arguments for logging purposes.
Args:
**kwargs: Function arguments to sanitize
Returns:
Dictionary with sanitized argument values
"""
sanitized = {}
sensitive_keys = ['password', 'api_key', 'token', 'secret', 'key', 'cert', 'authorization']
for key, value in kwargs.items():
key_lower = key.lower()
if any(sensitive in key_lower for sensitive in sensitive_keys):
sanitized[key] = '[REDACTED]' if value else None
elif isinstance(value, str) and len(value) > 100:
# Truncate very long strings and sanitize
sanitized[key] = sanitize_log_message(value[:100] + '...')
elif isinstance(value, str):
sanitized[key] = sanitize_log_message(value)
else:
sanitized[key] = value
return sanitized
def log_function_call(func_name: str, **kwargs):
"""
Safely log a function call with sanitized arguments.
Args:
func_name: Name of the function being called
**kwargs: Function arguments to log
"""
sanitized_args = sanitize_function_args(**kwargs)
safe_log(logger.debug, f"Function {func_name} called with args: {sanitized_args}")
def is_potentially_sensitive(value: str) -> bool:
"""
Check if a string value might contain sensitive information.
Args:
value: String to check
Returns:
True if the value might be sensitive
"""
if not isinstance(value, str) or len(value) < 8:
return False
# Check for patterns that might indicate sensitive data
sensitive_indicators = [
r'[A-Za-z0-9]{32,}', # Long alphanumeric strings (likely keys)
r'Bearer\s+', # Bearer tokens
r'-----BEGIN', # Certificate start
r'[A-Za-z0-9+/]{20,}={0,2}', # Base64 data
r'eyJ[A-Za-z0-9]', # JWT tokens
]
for pattern in sensitive_indicators:
if re.search(pattern, value):
return True
return False
# Load environment variables from .env file if it exists
load_dotenv()
# Import configuration validator
from config_validator import ConfigurationValidator, ConfigurationError
# Import enhanced systems
from message_processor import get_message_processor, MessageProcessor
from enhanced_logging import get_log_manager, setup_logging as enhanced_setup_logging
# Configure logging
def setup_logging(level_name):
# Special handling for NONE level
if level_name == "NONE":
# Disable all logging by setting level to NONE_LEVEL
level = NONE_LEVEL
else:
# Use standard logging levels
level = getattr(logging, level_name, logging.INFO)
# Create a logger with our app name
logger = logging.getLogger("CorefluxMCP")
logger.setLevel(level)
# Remove any existing handlers to avoid duplicates
for handler in logger.handlers[:]:
logger.removeHandler(handler)
# Use a format that doesn't conflict with MCP's logging
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# Add handlers with our formatter
handlers = [
logging.FileHandler("coreflux_mcp.log"),
logging.StreamHandler(sys.stderr)
]
for handler in handlers:
handler.setFormatter(formatter)
handler.setLevel(level)
logger.addHandler(handler)
# Don't interfere with the root logger, which MCP might use
logger.propagate = False
return logger
# Parse command-line arguments
def parse_args():
parser = argparse.ArgumentParser(description="Coreflux MQTT MCP Server")
parser.add_argument("--mqtt-host", default=os.environ.get("MQTT_BROKER", "localhost"),
help="MQTT broker hostname")
parser.add_argument("--mqtt-port", type=int, default=int(os.environ.get("MQTT_PORT", "1883")),
help="MQTT broker port")
parser.add_argument("--mqtt-user", default=os.environ.get("MQTT_USER"),
help="MQTT username")
parser.add_argument("--mqtt-password", default=os.environ.get("MQTT_PASSWORD"),
help="MQTT password")
parser.add_argument("--mqtt-client-id", default=os.environ.get("MQTT_CLIENT_ID", f"coreflux-mcp-{uuid.uuid4().hex[:8]}"),
help="MQTT client ID")
parser.add_argument("--mqtt-use-tls", action="store_true", default=os.environ.get("MQTT_USE_TLS", "false").lower() == "true",
help="Use TLS for MQTT connection")
parser.add_argument("--mqtt-ca-cert", default=os.environ.get("MQTT_CA_CERT"),
help="Path to CA certificate file for TLS")
parser.add_argument("--mqtt-client-cert", default=os.environ.get("MQTT_CLIENT_CERT"),
help="Path to client certificate file for TLS")
parser.add_argument("--mqtt-client-key", default=os.environ.get("MQTT_CLIENT_KEY"),
help="Path to client key file for TLS")
parser.add_argument("--do-agent-api-key", default=os.environ.get("DO_AGENT_API_KEY"),
help="DigitalOcean Agent Platform API key")
parser.add_argument("--lot-verifier-api-url", default=os.environ.get("LOT_VERIFIER_API_URL", "http://localhost:8000/validate/code"),
help="LOT code verification API endpoint URL")
parser.add_argument("--log-level", default=os.environ.get("LOG_LEVEL", "INFO"),
choices=["NONE", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
help="Set logging level (NONE disables all logging)")
return parser.parse_args()
# Get command line arguments and setup logging
args = parse_args()
logger = setup_logging(args.log_level)
# Validate configuration before proceeding
config_validator = ConfigurationValidator(logger)
try:
logger.info("Validating server configuration...")
is_valid = config_validator.log_configuration_status()
if not is_valid:
logger.error("Configuration validation failed. Please check your environment variables.")
logger.info("Run 'python setup_assistant.py' to configure the server.")
# Don't exit here - allow server to start for configuration tools to work
logger.warning("Starting server anyway to allow configuration via MCP tools.")
else:
logger.info("Configuration validation passed successfully.")
except Exception as e:
logger.error(f"Error during configuration validation: {str(e)}")
logger.warning("Continuing with startup despite validation error.")
# Configure FastMCP server
mcp = FastMCP(
"Coreflux Broker",
description="Connect to a Coreflux MQTT broker and control Coreflux actions, models, and rules",
dependencies=["paho-mqtt"]
)
# Initialize enhanced message processor
message_processor = get_message_processor(logger)
logger.info("Enhanced message processor initialized")
# Global MQTT client and enhanced message processing
mqtt_client = None
discovered_actions = {}
registered_dynamic_tools = set() # Keep track of dynamically registered tools
connection_status = {
"connected": False,
"last_connection_attempt": None,
"reconnect_count": 0,
"last_error": None
}
server_start_time = datetime.now()
mqtt_subscriptions = {} # Track active subscriptions
mqtt_message_buffer = {} # Legacy buffer for backward compatibility
# Enhanced message processing
message_processor = None # Will be initialized with logger
# MQTT connection and message handling
def on_connect(client, userdata, flags, rc, properties=None):
result_code_map = {
0: "Connection successful",
1: "Connection refused - incorrect protocol version",
2: "Connection refused - invalid client identifier",
3: "Connection refused - server unavailable",
4: "Connection refused - bad username or password",
5: "Connection refused - not authorized"
}
if rc == 0:
connection_status["connected"] = True
connection_status["reconnect_count"] = 0
connection_status["last_error"] = None
logger.info(f"Connected to MQTT broker successfully (code: {rc})")
# Subscribe to all action descriptions
try:
client.subscribe("$SYS/Coreflux/Actions/+/Description")
logger.info("Subscribed to Coreflux action descriptions")
except Exception as e:
logger.error(f"Failed to subscribe to topics: {str(e)}")
else:
connection_status["connected"] = False
connection_status["last_error"] = result_code_map.get(rc, f"Unknown error code: {rc}")
logger.error(f"Failed to connect to MQTT broker: {connection_status['last_error']}")
def on_disconnect(client, userdata, rc, properties=None, reason_code=0):
connection_status["connected"] = False
if rc == 0:
logger.info("Disconnected from MQTT broker gracefully")
else:
logger.warning(f"Unexpected disconnection from MQTT broker (code: {rc})")
# Implement reconnection logic
connection_status["reconnect_count"] += 1
connection_status["last_connection_attempt"] = datetime.now()
def on_message(client, userdata, msg):
try:
# Store message in buffer (legacy support)
topic = msg.topic
try:
payload = msg.payload.decode('utf-8')
except UnicodeDecodeError:
payload = str(msg.payload)
# Enhanced message processing
if message_processor:
metadata = {
"qos": msg.qos,
"retain": msg.retain,
"timestamp": time.time()
}
message_processor.add_message(topic, payload, metadata)
# Legacy buffer (for backward compatibility)
if topic not in mqtt_message_buffer:
mqtt_message_buffer[topic] = []
# Add message with timestamp
mqtt_message_buffer[topic].append({
"payload": payload,
"timestamp": time.time(),
"qos": msg.qos,
"retain": msg.retain
})
# Limit buffer size (keep last 100 messages per topic)
if len(mqtt_message_buffer[topic]) > 100:
mqtt_message_buffer[topic] = mqtt_message_buffer[topic][-100:]
# Extract action name from topic
topic_parts = msg.topic.split('/')
if len(topic_parts) >= 4 and topic_parts[-1] == "Description":
action_name = topic_parts[-2]
# Log the raw data for debugging
payload_raw = msg.payload
safe_log(logger.debug, f"Raw message received: {repr(payload_raw)}")
try:
# Safe decoding of the payload
payload_str = payload_raw.decode('utf-8').strip()
# Extract description using more robust parsing
description = extract_description_safely(payload_str)
# Check if we already have this action
if action_name in discovered_actions:
# Only update the description if it changed
if discovered_actions[action_name] != description:
discovered_actions[action_name] = description
logger.info(f"Updated action description: {action_name} - {description}")
return
# New action discovered
discovered_actions[action_name] = description
logger.info(f"Discovered new action: {action_name} - {description}")
# Register a dynamic tool for this action if not already registered
if action_name not in registered_dynamic_tools:
register_dynamic_action_tool(action_name, description)
except UnicodeDecodeError as e:
logger.error(f"Failed to decode message payload: {str(e)}")
return
except Exception as e:
logger.error(f"Error processing MQTT message: {str(e)}", exc_info=True)
# Helper function for safely extracting descriptions from potentially malformed JSON
def extract_description_safely(payload_str):
"""
Extract description from a payload string that might be JSON or plain text.
Implements robust parsing to handle malformed JSON gracefully.
Args:
payload_str: The string to parse
Returns:
A string representing the description
"""
# If it's empty, return empty string
if not payload_str or not payload_str.strip():
return ""
# If it doesn't look like JSON, just return the string as-is
if not (payload_str.strip().startswith('{') and payload_str.strip().endswith('}')):
return payload_str.strip()
# It looks like JSON, try to parse it properly
try:
# Parse as JSON using the parser module
data = process_json_rpc_message(payload_str)
# If it's a dict with a description field, return that
if isinstance(data, dict) and 'description' in data:
return data['description']
# Otherwise, return the whole object as a string
return payload_str
except Exception as e:
logger.warning(f"JSON parse error: {str(e)}")
safe_log(logger.debug, f"Problematic payload: {payload_str}")
# Return the payload as-is since we couldn't parse it
return payload_str
def register_dynamic_action_tool(action_name, description):
try:
# Skip if already registered
if action_name in registered_dynamic_tools:
return
# Create a unique function name for this action
tool_func_name = f"run_{action_name}"
# Create function in a safer way - avoid direct string interpolation in exec
# Create the function text with proper escaping for the docstring
description_safe = description.replace('\\', '\\\\').replace('"', '\\"')
# Define the function code
func_code = f'''
@mcp.tool()
async def {tool_func_name}(ctx: Context) -> str:
"""Run the {action_name} action: {description_safe}"""
response = execute_command(f"-runAction {action_name}")
logger.info(f"Executed action {action_name}")
return response
'''
# Execute the code in global scope
exec(func_code, globals())
# Mark as registered
registered_dynamic_tools.add(action_name)
logger.info(f"Registered dynamic tool for action: {action_name} as {tool_func_name}")
except Exception as e:
logger.error(f"Failed to register dynamic tool for {action_name}: {str(e)}", exc_info=True)
# Setup MQTT client
def setup_mqtt(args):
global mqtt_client
# Set logging level from arguments
try:
log_level = getattr(logging, args.log_level)
logger.setLevel(log_level)
logger.info(f"Log level set to {args.log_level}")
except AttributeError:
logger.warning(f"Invalid log level: {args.log_level}, defaulting to INFO")
logger.setLevel(logging.INFO)
# Use protocol version 5 (MQTT v5) with the newer callback API and unique client ID
try:
mqtt_client = mqtt.Client(client_id=args.mqtt_client_id, protocol=mqtt.MQTTv5, callback_api_version=mqtt.CallbackAPIVersion.VERSION2)
# Set up authentication if provided
if args.mqtt_user and args.mqtt_password:
mqtt_client.username_pw_set(args.mqtt_user, args.mqtt_password)
safe_log(logger.debug, f"Using MQTT authentication with username: {args.mqtt_user}")
# Configure TLS if enabled
if args.mqtt_use_tls:
# Check if certificate files exist before attempting to use them
cert_files = [
(args.mqtt_ca_cert, "CA certificate"),
(args.mqtt_client_cert, "Client certificate"),
(args.mqtt_client_key, "Client key")
]
missing_files = []
for cert_path, cert_name in cert_files:
if cert_path and not os.path.exists(cert_path):
missing_files.append(f"{cert_name} at {cert_path}")
if missing_files:
safe_log(logger.error, f"Missing certificate files: {', '.join(missing_files)}")
logger.warning("TLS configuration incomplete. MQTT client created but not connected.")
# Set callbacks but don't attempt connection
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
mqtt_client.on_disconnect = on_disconnect
return False
mqtt_client.tls_set(
ca_certs=args.mqtt_ca_cert,
certfile=args.mqtt_client_cert,
keyfile=args.mqtt_client_key
)
logger.info("TLS configuration enabled for MQTT connection")
# Set callbacks
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
mqtt_client.on_disconnect = on_disconnect
# Attempt to connect to broker
safe_log(logger.info, f"Attempting to connect to MQTT broker at {args.mqtt_host}:{args.mqtt_port} with client ID: {args.mqtt_client_id}")
connection_status["last_connection_attempt"] = datetime.now()
# Set a connection timeout
try:
mqtt_client.connect(args.mqtt_host, args.mqtt_port, 60)
mqtt_client.loop_start()
# Wait briefly to check connection status
max_wait = 3 # seconds
for _ in range(max_wait * 2):
if connection_status["connected"]:
logger.info("MQTT client connected successfully")
return True
time.sleep(0.5)
# If we get here, we didn't connect within the timeout
logger.warning(f"MQTT connection not confirmed after {max_wait} seconds, but client initialized")
logger.info("Use mqtt_connect tool or check_broker_health to retry connection")
return False
except (ConnectionRefusedError, TimeoutError, OSError) as e:
logger.warning(f"Failed to connect to MQTT broker: {str(e)}")
connection_status["last_error"] = str(e)
logger.info("MQTT client initialized but not connected. Use mqtt_connect tool to retry.")
return False
except Exception as e:
logger.warning(f"MQTT connection error: {str(e)}")
connection_status["last_error"] = str(e)
logger.info("MQTT client initialized but not connected. Use mqtt_connect tool to retry.")
return False
except Exception as e:
logger.error(f"Error creating MQTT client: {str(e)}", exc_info=True)
connection_status["last_error"] = str(e)
logger.warning("MQTT client creation failed. Some tools may not work until connection is established.")
return False
# Helper function to execute Coreflux commands
def execute_command(command_string, timeout=10.0):
if not mqtt_client:
error_msg = "MQTT client not initialized"
logger.error(error_msg)
return f"ERROR: {error_msg}"
if not connection_status["connected"]:
error_msg = "MQTT client not connected"
logger.error(error_msg)
return f"ERROR: {error_msg}"
# Event to signal when we receive a response
response_event = threading.Event()
response_data = {"payload": None, "error": None}
# Callback for command output messages
def on_command_output(client, userdata, msg):
try:
payload = msg.payload.decode('utf-8')
response_data["payload"] = payload
logger.debug(f"Received command output: {payload}")
except UnicodeDecodeError:
response_data["payload"] = str(msg.payload)
except Exception as e:
response_data["error"] = f"Error processing command output: {str(e)}"
response_event.set()
try:
# Subscribe to command output topic
output_topic = "$SYS/Coreflux/Command/Output"
mqtt_client.message_callback_add(output_topic, on_command_output)
subscribe_result, mid = mqtt_client.subscribe(output_topic, 0)
if subscribe_result != mqtt.MQTT_ERR_SUCCESS:
error_msg = f"Failed to subscribe to command output: {mqtt.error_string(subscribe_result)}"
logger.error(error_msg)
return f"ERROR: {error_msg}"
logger.debug(f"Subscribed to {output_topic} for command feedback")
# Small delay to ensure subscription is established
time.sleep(0.1)
# Publish the command
publish_result = mqtt_client.publish("$SYS/Coreflux/Command", command_string)
if publish_result.rc != mqtt.MQTT_ERR_SUCCESS:
error_msg = f"Failed to publish command: {mqtt.error_string(publish_result.rc)}"
logger.error(error_msg)
# Clean up subscription
mqtt_client.unsubscribe(output_topic)
mqtt_client.message_callback_remove(output_topic)
return f"ERROR: {error_msg}"
safe_log(logger.info, f"Published command: {sanitize_log_message(command_string)}")
# Wait for response or timeout
if response_event.wait(timeout):
# Response received
if response_data["error"]:
logger.error(response_data["error"])
response = f"ERROR: {response_data['error']}"
else:
response = response_data["payload"] or "Command executed (no output)"
logger.info(f"Command completed successfully")
else:
# Timeout
logger.warning(f"Command response timeout after {timeout} seconds")
response = f"WARNING: Command sent but no response received within {timeout} seconds"
# Clean up subscription
mqtt_client.unsubscribe(output_topic)
mqtt_client.message_callback_remove(output_topic)
return response
except Exception as e:
error_msg = f"MQTT protocol error while executing command: {str(e)}"
logger.error(error_msg)
# Attempt cleanup
try:
mqtt_client.unsubscribe(output_topic)
mqtt_client.message_callback_remove(output_topic)
except:
pass
return f"ERROR: {error_msg}"
# region COREFLUX TOOLS
class StringModel(BaseModel):
value: str
@validator('value', pre=True)
def ensure_string(cls, v):
if not isinstance(v, str):
raise ValueError('Value must be a string')
return v
@mcp.tool()
async def add_rule(rule_definition: str, ctx: Context) -> str:
try:
StringModel(value=rule_definition)
except Exception as e:
return f"ERROR: rule_definition must be a string: {e}"
safe_log(logger.info, f"Adding rule: {rule_definition[:50]}..." if len(rule_definition) > 50 else f"Adding rule: {rule_definition}")
result = execute_command(f"-addRule {rule_definition}")
try:
StringModel(value=result)
except Exception as e:
return f"ERROR: Output is not a string: {e}"
return result
@mcp.tool()
async def remove_rule(rule_name: str, ctx: Context) -> str:
try:
StringModel(value=rule_name)
except Exception as e:
return f"ERROR: rule_name must be a string: {e}"
logger.info(f"Removing rule: {rule_name}")
result = execute_command(f"-removeRule {rule_name}")
try:
StringModel(value=result)
except Exception as e:
return f"ERROR: Output is not a string: {e}"
return result
@mcp.tool()
async def add_route(ctx: Context) -> str:
"""Add a new route connection"""
logger.info("Adding new route")
result = execute_command("-addRoute")
try:
StringModel(value=result)
except Exception as e:
return f"ERROR: Output is not a string: {e}"
return result
@mcp.tool()
async def remove_route(route_id: str, ctx: Context) -> str:
try:
StringModel(value=route_id)
except Exception as e:
return f"ERROR: route_id must be a string: {e}"
logger.info(f"Removing route: {route_id}")
result = execute_command(f"-removeRoute {route_id}")
try:
StringModel(value=result)
except Exception as e:
return f"ERROR: Output is not a string: {e}"
return result
@mcp.tool()
async def add_model(model_definition: str, ctx: Context) -> str:
try:
StringModel(value=model_definition)
except Exception as e:
return f"ERROR: model_definition must be a string: {e}"
safe_log(logger.info, f"Adding model: {model_definition[:50]}..." if len(model_definition) > 50 else f"Adding model: {model_definition}")
result = execute_command(f"-addModel {model_definition}")
try:
StringModel(value=result)
except Exception as e:
return f"ERROR: Output is not a string: {e}"
return result
@mcp.tool()
async def remove_model(model_name: str, ctx: Context) -> str:
try:
StringModel(value=model_name)
except Exception as e:
return f"ERROR: model_name must be a string: {e}"
logger.info(f"Removing model: {model_name}")
result = execute_command(f"-removeModel {model_name}")
try:
StringModel(value=result)
except Exception as e:
return f"ERROR: Output is not a string: {e}"
return result
@mcp.tool()
async def add_action(action_definition: str, ctx: Context) -> str:
try:
StringModel(value=action_definition)
except Exception as e:
return f"ERROR: action_definition must be a string: {e}"
safe_log(logger.info, f"Adding action: {action_definition[:50]}..." if len(action_definition) > 50 else f"Adding action: {action_definition}")
result = execute_command(f"-addAction {action_definition}")
try:
StringModel(value=result)
except Exception as e:
return f"ERROR: Output is not a string: {e}"
return result
@mcp.tool()
async def remove_action(action_name: str, ctx: Context) -> str:
try:
StringModel(value=action_name)
except Exception as e:
return f"ERROR: action_name must be a string: {e}"
logger.info(f"Removing action: {action_name}")
result = execute_command(f"-removeAction {action_name}")
try:
StringModel(value=result)
except Exception as e:
return f"ERROR: Output is not a string: {e}"
return result
@mcp.tool()
async def run_action(action_name: str, ctx: Context) -> str:
try:
StringModel(value=action_name)
except Exception as e:
return f"ERROR: action_name must be a string: {e}"
logger.info(f"Running action: {action_name}")
result = execute_command(f"-runAction {action_name}")
try:
StringModel(value=result)
except Exception as e:
return f"ERROR: Output is not a string: {e}"
return result
# @mcp.tool()
# async def remove_all_models(ctx: Context) -> str:
# """Remove all models from Coreflux"""
# logger.warning("Removing ALL models - this is a destructive operation")
# result = execute_command("-removeAllModels")
# try:
# StringModel(value=result)
# except Exception as e:
# return f"ERROR: Output is not a string: {e}"
# return result
# @mcp.tool()
# async def remove_all_actions(ctx: Context) -> str:
# """Remove all actions from Coreflux"""
# logger.warning("Removing ALL actions - this is a destructive operation")
# result = execute_command("-removeAllActions")
# try:
# StringModel(value=result)
# except Exception as e:
# return f"ERROR: Output is not a string: {e}"
# return result
# @mcp.tool()
# async def remove_all_routes(ctx: Context) -> str:
# """Remove all routes from Coreflux"""
# logger.warning("Removing ALL routes - this is a destructive operation")
# result = execute_command("-removeAllRoutes")
# try:
# StringModel(value=result)
# except Exception as e:
# return f"ERROR: Output is not a string: {e}"
# return result
@mcp.tool()
async def lot_diagnostic(diagnostic_value: str, ctx: Context) -> str:
try:
StringModel(value=diagnostic_value)
except Exception as e:
return f"ERROR: diagnostic_value must be a string: {e}"
logger.info(f"Setting LOT diagnostic to: {diagnostic_value}")
result = execute_command(f"-lotDiagnostic {diagnostic_value}")
try:
StringModel(value=result)
except Exception as e:
return f"ERROR: Output is not a string: {e}"
return result
@mcp.tool()
async def list_discovered_actions(ctx: Context) -> str:
"""List all discovered Coreflux actions"""
if not discovered_actions:
logger.info("No actions discovered yet")
return "No actions discovered yet."
logger.info(f"Listing {len(discovered_actions)} discovered actions")
result = "Discovered Coreflux Actions:\n\n"
for action_name, description in discovered_actions.items():
tool_status = "✓" if action_name in registered_dynamic_tools else "✗"
result += f"- {action_name}: {description} [Tool: {tool_status}]\n"
try:
StringModel(value=result)
except Exception as e:
return f"ERROR: Output is not a string: {e}"
return result
@mcp.tool()
async def get_connection_status(ctx: Context) -> str:
"""Get the current MQTT connection status and guidance for troubleshooting"""
status = {
"connected": connection_status["connected"],
"last_connection_attempt": str(connection_status["last_connection_attempt"]) if connection_status["last_connection_attempt"] else None,
"reconnect_count": connection_status["reconnect_count"],
"last_error": connection_status["last_error"],
"discovered_actions": len(discovered_actions),
"registered_tools": len(registered_dynamic_tools),
"mqtt_client_initialized": mqtt_client is not None
}
# Add troubleshooting guidance
guidance = []
if not mqtt_client:
guidance.append("❌ MQTT client not initialized. This indicates a serious configuration issue.")
guidance.append("💡 Try running setup_assistant.py to configure your connection.")
elif not connection_status["connected"]:
guidance.append("⚠️ MQTT client initialized but not connected.")
guidance.append("💡 Use mqtt_connect tool to establish connection.")
guidance.append("💡 Use check_broker_health tool to test and reconnect.")
if connection_status["last_error"]:
guidance.append(f"🔍 Last error: {connection_status['last_error']}")
else:
guidance.append("✅ MQTT connection is healthy and active.")
if len(discovered_actions) == 0:
guidance.append("ℹ️ No Coreflux actions discovered yet. This may be normal for new connections.")
status["troubleshooting_guidance"] = guidance
logger.info(f"Connection status requested: connected={status['connected']}, client_initialized={status['mqtt_client_initialized']}")
result = json.dumps(status, indent=2)
try:
StringModel(value=result)
except Exception as e:
return f"ERROR: Output is not a string: {e}"
return result
@mcp.tool()
def request_lot_code(ctx: Context, query: str, context: str = "") -> str:
"""
Request LOT code generation from the DigitalOcean Agent Platform API.
This function sends a query to the DigitalOcean Agent Platform to generate
LOT (Logic Object Tree) code based on the provided query and context.
Args:
ctx: The MCP context
query: The query describing what LOT code to generate
context: Optional context to provide additional information
Returns:
A formatted string containing the generated LOT code and explanation
"""
try:
StringModel(value=query)
StringModel(value=context)
except Exception as e:
return f"ERROR: query/context must be a string: {e}"
# Check if API key is configured
api_key = args.do_agent_api_key
if not api_key:
error_msg = "DigitalOcean Agent Platform API key not configured. Please set DO_AGENT_API_KEY in your .env file or use --do-agent-api-key argument."
logger.error(error_msg)
return f"Error: {error_msg}"
# Log function call (API key will be automatically redacted)
log_function_call("request_lot_code", query=query, context=context, api_key=api_key)
# Coreflux Copilot API endpoint
api_url = "https://xtov5ljwjkydusw2zpus4yxe.agents.do-ai.run/api/v1/chat/completions"
# Create payload for Coreflux Copilot
# The Coreflux Copilot expects a specific chat completion format
try:
# Build the user message content
user_content = f"Generate LOT code for the following query: {query}"
if context:
user_content += f"\n\nContext: {context}"
payload = {
"messages": [
{
"role": "user",
"content": user_content
}
],
"stream": False,
"include_functions_info": False,
"include_retrieval_info": True,
"include_guardrails_info": False
}
safe_log(logger.debug, f"Sending request to DO Agent Platform: {json.dumps(payload, ensure_ascii=False)[:200]}...")
safe_log(logger.info, f"Requesting LOT code generation with query: {query[:50]}..." if len(query) > 50 else f"Requesting LOT code generation with query: {query}")
except Exception as e:
error_msg = f"Failed to create payload: {str(e)}"
logger.error(error_msg)
return f"Error: {error_msg}"
try:
# Set proper headers for Coreflux Copilot API
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": f"Bearer {api_key}"
}
response = requests.post(api_url, json=payload, headers=headers, timeout=30)
# Debug the raw response
safe_log(logger.debug, f"Raw API response status: {response.status_code}")
safe_log(logger.debug, f"Raw API response headers: {dict(response.headers)}")
safe_log(logger.debug, f"Raw API response content: {response.text[:200]}..." if len(response.text) > 200 else response.text)
if response.status_code == 200:
# Process the response from Coreflux Copilot