forked from lifehaverdev/MiladyOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiladyos_mcp.py
More file actions
2350 lines (2079 loc) · 106 KB
/
Copy pathmiladyos_mcp.py
File metadata and controls
2350 lines (2079 loc) · 106 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
import json
import logging
import os
import time
import asyncio
from typing import Any, Dict, List, Optional
import textwrap
import uuid
import click
import anyio
import sqlite3
from contextlib import closing
from pathlib import Path
def get_redis_config():
"""
Get Redis configuration based on environment variables.
Centralizes Redis configuration to avoid duplication.
"""
if not REDIS_AVAILABLE:
raise ImportError("Redis package is required for MiladyOS. Please install with 'pip install redis'")
# In Kubernetes, use service names for discovery
if os.getenv("KUBERNETES_MODE", "false").lower() == "true":
redis_host = os.getenv("REDIS_HOST", "redka")
redis_port = int(os.getenv("REDIS_PORT", "6379"))
logger.info(f"Running in Kubernetes mode, using Redis at {redis_host}:{redis_port}")
else:
redis_host = os.getenv("REDIS_HOST", "localhost")
redis_port = int(os.getenv("REDIS_PORT", "6379"))
return redis_host, redis_port
def create_error_response(error_message, tool=None, status="error", additional_info=None):
"""
Create a standardized error response dictionary.
Args:
error_message: The main error message
tool: Optional tool name that triggered the error
status: Error status code (default: "error")
additional_info: Optional dictionary with additional error details
Returns:
Dictionary with standardized error format
"""
response = {
"success": False,
"error": error_message,
"status": status
}
if tool:
response["tool"] = tool
if additional_info and isinstance(additional_info, dict):
response.update(additional_info)
return response
def create_success_response(message=None, data=None, status="success", additional_info=None):
"""
Create a standardized success response dictionary.
Args:
message: Optional success message
data: Optional data to include in the response
status: Success status code (default: "success")
additional_info: Optional dictionary with additional information
Returns:
Dictionary with standardized success format
"""
response = {
"success": True,
"status": status
}
if message:
response["message"] = message
if data:
if isinstance(data, dict):
response.update(data)
else:
response["data"] = data
if additional_info and isinstance(additional_info, dict):
response.update(additional_info)
return response
import jenkins
import colorlog
from mcp.server.lowlevel import Server
from mcp.server.stdio import stdio_server
from mcp import types
from xml.sax.saxutils import escape
# Import our metadata management system
from miladyos_metadata import RedkaMetadataManager, REDIS_AVAILABLE, metadata_manager
# Note: We use the shared metadata_manager instance from miladyos_metadata
# but can also create our own instances of RedkaMetadataManager when needed
# Configure logging
logger = colorlog.getLogger("miladyos-mcp-tools")
handler = colorlog.StreamHandler()
handler.setFormatter(colorlog.ColoredFormatter(
"%(log_color)s%(levelname)s%(reset)s: %(message)s"
))
logger.handlers = []
logger.addHandler(handler)
logger.setLevel(logging.INFO)
# ===== Configuration =====
class Config:
"""MiladyOS configuration settings."""
# Default supported tools
DEFAULT_TOOLS = [
"create_template",
"edit_template",
"list_templates",
"view_template",
"deploy_pipeline",
"run_pipeline",
"get_pipeline_status",
"list_pipeline_runs",
"hello_world",
"execute_command",
"read_query",
"list_db_tables",
"describe_db_table"
]
# Jenkins credentials - hardcoded for reliability
JENKINS_USER = "admin"
JENKINS_PASSWORD = "password"
# Jenkins server configurations
JENKINS_SERVERS = {
"default": {
"url": os.getenv("JENKINS_URL", "http://localhost:8080")
}
}
# SQLite database path
SQLITE_DB_PATH = os.getenv("SQLITE_DB_PATH", "/data/redka/data.db")
# Templates and metadata directories
TEMPLATES_DIR = os.getenv("TEMPLATES_DIR", "templates")
METADATA_DIR = os.getenv("METADATA_DIR", "metadata")
@classmethod
def get_jenkins_servers(cls):
"""Return Jenkins server configurations."""
return cls.JENKINS_SERVERS
# ===== Custom Exceptions =====
class JenkinsApiError(Exception):
"""Raised when there's an error with the Jenkins API."""
pass
class SqliteApiError(Exception):
"""Raised when there's an error with the SQLite API."""
pass
# ===== SQLite Utilities =====
class SqliteUtils:
"""Utility functions for interacting with SQLite."""
DEFAULT_DB_PATH = "/data/redka/data.db"
@staticmethod
def connect_to_db(db_path=None):
"""
Connect to SQLite database and return connection.
"""
try:
db_path = db_path or SqliteUtils.DEFAULT_DB_PATH
# Ensure the parent directory exists
parent_dir = os.path.dirname(db_path)
if not os.path.exists(parent_dir):
os.makedirs(parent_dir, exist_ok=True)
logger.info(f"Created directory for SQLite database: {parent_dir}")
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
logger.info(f"Successfully connected to SQLite database: {db_path}")
return conn
except Exception as e:
logger.error(f"Error connecting to SQLite database: {e}")
raise SqliteApiError(f"Failed to connect to SQLite database: {str(e)}")
@staticmethod
def execute_read_query(db_path, query):
"""Execute a SELECT query on the SQLite database."""
if not query.strip().upper().startswith("SELECT"):
raise SqliteApiError("Only SELECT queries are allowed for read_query")
try:
with closing(SqliteUtils.connect_to_db(db_path)) as conn:
with closing(conn.cursor()) as cursor:
cursor.execute(query)
rows = cursor.fetchall()
results = [dict(row) for row in rows]
return results
except Exception as e:
logger.error(f"Error executing read query: {e}")
raise SqliteApiError(f"Error executing read query: {str(e)}")
@staticmethod
def list_tables(db_path):
"""List all tables in the SQLite database."""
try:
with closing(SqliteUtils.connect_to_db(db_path)) as conn:
with closing(conn.cursor()) as cursor:
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
rows = cursor.fetchall()
return [dict(row) for row in rows]
except Exception as e:
logger.error(f"Error listing tables: {e}")
raise SqliteApiError(f"Error listing tables: {str(e)}")
@staticmethod
def describe_table(db_path, table_name):
"""Get schema information for a specific table."""
try:
with closing(SqliteUtils.connect_to_db(db_path)) as conn:
with closing(conn.cursor()) as cursor:
cursor.execute(f"PRAGMA table_info({table_name})")
rows = cursor.fetchall()
return [dict(row) for row in rows]
except Exception as e:
logger.error(f"Error describing table {table_name}: {e}")
raise SqliteApiError(f"Error describing table: {str(e)}")
# ===== Jenkins Utilities =====
class JenkinsUtils:
"""Utility functions for interacting with Jenkins."""
@staticmethod
def connect_to_jenkins(server_name, username=None, password=None):
"""
Connect to Jenkins server and return server instance.
"""
try:
jenkins_dict = Config.get_jenkins_servers()
if server_name not in jenkins_dict:
raise ValueError(f"Unknown Jenkins server: {server_name}")
server_url = jenkins_dict[server_name]["url"]
# Always use default credentials if none provided
if username is None:
username = Config.JENKINS_USER
if password is None:
password = Config.JENKINS_PASSWORD
server = jenkins.Jenkins(
server_url,
username=username,
password=password,
)
try:
# Test connection
server.get_whoami()
logger.info(f"Successfully connected to Jenkins server: {server_name} ({server_url})")
return server
except Exception:
# Add retry with delay if first attempt fails
logger.info(f"Retrying connection to {server_name} after 2 second delay...")
time.sleep(2)
server = jenkins.Jenkins(
server_url,
username=username,
password=password,
)
server.get_whoami()
logger.info(f"Retry connection successful for {server_name}")
return server
except ImportError:
raise JenkinsApiError("Jenkins module not installed. Please install python-jenkins package.")
except Exception as e:
logger.error(f"Error connecting to Jenkins server {server_name}: {e}")
raise JenkinsApiError(f"Failed to connect to Jenkins server: {str(e)}")
@staticmethod
def get_jenkinsfile_content(template_name, with_line_numbers=False):
"""
Read and return Jenkinsfile content for a template.
Args:
template_name: Name of the template to read
with_line_numbers: If True, returns a dict with 'content' and 'lines' keys
where 'lines' is a list of lines with line numbers
"""
jenkinsfile_path = f"{Config.TEMPLATES_DIR}/{template_name}.Jenkinsfile"
try:
with open(jenkinsfile_path, "r") as file:
content = file.read()
logger.info(f"Successfully read Jenkinsfile for template: {template_name}")
if with_line_numbers:
lines = content.splitlines()
lines_with_numbers = [(i+1, line) for i, line in enumerate(lines)]
return {
"content": content,
"lines": lines_with_numbers,
"path": jenkinsfile_path
}
return content
except FileNotFoundError:
raise FileNotFoundError(f"Jenkinsfile not found for template: {template_name}")
except Exception as e:
logger.error(f"Error reading Jenkinsfile for {template_name}: {e}")
raise JenkinsApiError(f"Error reading Jenkinsfile: {str(e)}")
@staticmethod
async def delete_job_if_exists(server, job_name):
"""Delete a Jenkins job if it exists."""
try:
if server.job_exists(job_name):
logger.info(f"Job {job_name} exists. Attempting to delete.")
server.delete_job(job_name)
logger.info(f"Job {job_name} deleted.")
return True
else:
logger.info(f"Job {job_name} does not exist. No need to delete.")
return False
except Exception as e:
logger.error(f"Error deleting job {job_name}: {e}")
raise JenkinsApiError(f"Error deleting job: {str(e)}")
@staticmethod
async def create_job(server, job_name, jenkinsfile_content):
"""Create a Jenkins job with the provided Jenkinsfile content."""
pipeline_xml = f"""
<flow-definition plugin="workflow-job@2.40">
<definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.90">
<script>{escape(jenkinsfile_content)}</script>
<sandbox>true</sandbox>
</definition>
<!-- Other configurations as needed -->
</flow-definition>
"""
try:
logger.info(f"Creating new job {job_name}.")
server.create_job(job_name, pipeline_xml)
logger.info(f"Job {job_name} created successfully.")
return True
except Exception as e:
logger.error(f"Error creating job {job_name}: {e}")
raise JenkinsApiError(f"Error creating job: {str(e)}")
@staticmethod
async def start_jenkins_job(server, job_name, parameters=None):
"""
Start a Jenkins job and return queue number and build number.
"""
try:
# First check if we can access the job
try:
job_exists = server.job_exists(job_name)
if not job_exists:
logger.error(f"Job {job_name} does not exist")
return {
"status": "error",
"error": f"Job {job_name} does not exist",
"job_name": job_name
}
except Exception as check_error:
logger.error(f"Error checking if job {job_name} exists: {check_error}")
# Try to continue anyway
# Start the job
if parameters:
queue_number = server.build_job(job_name, parameters)
else:
queue_number = server.build_job(job_name)
logger.info(f"Job {job_name} build started. Queue number: {queue_number}")
# Wait for job to start
build_number = None
max_retries = 30
retry_count = 0
while retry_count < max_retries:
try:
queue_info = server.get_queue_item(queue_number)
if "executable" in queue_info and queue_info["executable"] is not None:
build_number = queue_info["executable"]["number"]
logger.info(f"Job {job_name} is building. Build number: {build_number}")
break
else:
logger.info("Waiting for job to start...")
await asyncio.sleep(2)
retry_count += 1
except Exception as queue_error:
logger.error(f"Error checking queue status: {queue_error}")
await asyncio.sleep(2)
retry_count += 1
if build_number:
return {
"status": "started",
"queue_number": queue_number,
"build_number": build_number
}
else:
return {
"status": "queued",
"queue_number": queue_number,
"build_number": None,
"message": "Job is still in queue after waiting period"
}
except Exception as e:
logger.error(f"Error starting job {job_name}: {e}")
# Return error information instead of raising exception
return {
"status": "error",
"error": f"Error starting job: {str(e)}",
"job_name": job_name
}
@staticmethod
async def stream_job_output(server, job_name, build_number):
"""
Stream the console output of a Jenkins job.
"""
try:
offset = 0
output_chunks = []
# Stream output until job is complete
max_retries = 60 # 3 minutes max wait time
retries = 0
while retries < max_retries:
try:
# Get build info to check if it's still running
build_info = server.get_build_info(job_name, build_number)
if build_info["building"]:
# Job is still running, get new output
try:
full_output = server.get_build_console_output(job_name, build_number)
new_output = full_output[offset:]
if new_output:
output_chunks.append(new_output)
offset += len(new_output)
except Exception:
pass
# Wait before checking again
await asyncio.sleep(3)
else:
# Job is complete, get final output
try:
full_output = server.get_build_console_output(job_name, build_number)
new_output = full_output[offset:]
if new_output:
output_chunks.append(new_output)
except Exception:
pass
# Return complete output and status
return {
"job_name": job_name,
"build_number": build_number,
"status": build_info.get("result", "UNKNOWN"),
"console_output": "".join(output_chunks),
"complete": True
}
except Exception:
await asyncio.sleep(3)
retries += 1
# If we've reached this point, we've exceeded our retry limit
return {
"job_name": job_name,
"build_number": build_number,
"status": "TIMEOUT",
"console_output": "".join(output_chunks) + "\n[TIMEOUT: Job took too long to complete or there was an error accessing the build]",
"complete": False
}
except Exception as e:
return {
"job_name": job_name,
"build_number": build_number,
"status": "ERROR",
"console_output": f"Error streaming job output: {str(e)}",
"complete": False
}
# ===== Template Management =====
class TemplateUtils:
"""Utility functions for template management."""
@staticmethod
def generate_jenkinsfile_content(template_name, description, agent="any", environment_vars=None, raw_content=None):
"""Generate Jenkinsfile content based on description.
If raw_content is provided, it will be used directly without any formatting changes.
"""
# If raw content is provided, use it directly with no formatting changes
if raw_content:
# Only add the description comment if it doesn't already have one
if "// Description:" not in raw_content:
return f"// Jenkinsfile for {template_name}\n// Description: {description}\n{raw_content}"
return raw_content
# Otherwise, generate a default template
# Check for existing Jenkinsfiles to use as templates/reference
try:
example_files = os.listdir(Config.TEMPLATES_DIR)
if example_files:
example_file = next((f for f in example_files if f.endswith('.Jenkinsfile')), None)
if example_file:
with open(f"{Config.TEMPLATES_DIR}/{example_file}", "r") as file:
pass # Read a template file, but we don't actually use it
except Exception as e:
logger.warning(f"Could not read template Jenkinsfile: {e}")
# Parse description to determine the type of pipeline
lowercase_desc = description.lower()
# Environment section
env_section = ""
if environment_vars:
env_vars_formatted = "\n ".join([f'{var}' for var in environment_vars])
env_section = f"""
environment {{
{env_vars_formatted}
}}"""
# Generate stages based on description
stages = []
# Checkout stage (common for most pipelines)
stages.append("""
stage('Checkout') {
steps {
checkout scm
}
}""")
# Add stages based on description keywords
if any(keyword in lowercase_desc for keyword in ["build", "compile", "package"]):
stages.append("""
stage('Build') {
steps {
echo 'Building...'
sh 'echo "Your build commands here"'
}
}""")
if any(keyword in lowercase_desc for keyword in ["test", "check", "validate"]):
stages.append("""
stage('Test') {
steps {
echo 'Testing...'
sh 'echo "Your test commands here"'
}
}""")
if any(keyword in lowercase_desc for keyword in ["deploy", "publish", "release"]):
stages.append("""
stage('Deploy') {
steps {
echo 'Deploying...'
sh 'echo "Your deployment commands here"'
}
}""")
# Determine if specific custom stage is needed
if "docker" in lowercase_desc or "container" in lowercase_desc:
stages.append("""
stage('Docker Build') {
steps {
echo 'Building Docker image...'
sh 'echo "docker build -t myapp:latest ."'
}
}""")
# Add a stage for the main purpose from the description
# Extract key verb from description (first word)
main_action = description.split()[0].lower() if description else "run"
main_action_clean = ''.join(c for c in main_action if c.isalnum())
# If no specific stages added, add a generic one based on description
if len(stages) <= 1: # Only checkout stage exists
stages.append(f"""
stage('{main_action_clean.capitalize()}') {{
steps {{
echo '{description}'
sh 'echo "Commands to {main_action_clean} will go here"'
}}
}}""")
# Combine all stages
all_stages = "".join(stages)
# Generate the full Jenkinsfile
jenkinsfile = f"""// Jenkinsfile for {template_name}
// Description: {description}
pipeline {{
agent {{{agent}}}
{env_section}
stages {{{all_stages}
}}
post {{
success {{
echo 'Pipeline completed successfully!'
}}
failure {{
echo 'Pipeline failed'
}}
}}
}}
"""
return jenkinsfile
# ===== Tool MCP Server =====
class MiladyOSToolServer:
"""Encapsulates the MCP server for MiladyOS tools."""
def __init__(self, supported_tools: Optional[List[str]] = None):
"""Initialize the server."""
self.tool_registry: Dict[str, Dict[str, Any]] = {}
self.supported_tools = supported_tools or Config.DEFAULT_TOOLS
self.server = None
async def process_tool_metadata(self) -> Dict[str, Dict[str, Any]]:
"""Process tool definitions and create tool registry."""
tool_registry = {}
all_tools = self._define_all_tools()
for tool_id, tool_info in all_tools.items():
# Skip tools not in our supported list (if a list is specified)
if self.supported_tools is not None and tool_id not in self.supported_tools:
continue
# Store tool info
tool_registry[tool_id] = tool_info
logger.info(f"Loaded {len(tool_registry)} tools")
return tool_registry
# CLI Experimenter Jenkinsfile - embedded directly in the code
CLI_EXPERIMENTER_JENKINSFILE = textwrap.dedent('''
pipeline {
agent any
parameters {
string(name: 'COMMAND', description: 'CLI command to execute')
string(name: 'WORKING_DIR', defaultValue: '/workspace', description: 'Working directory')
string(name: 'SESSION_ID', defaultValue: '', description: 'Session ID for tracking')
}
stages {
stage('Execute Command') {
steps {
// Change to working directory
dir(params.WORKING_DIR) {
// Execute the command with output capturing
sh """
echo "==== COMMAND EXECUTION ===="
echo "COMMAND: ${params.COMMAND}"
echo "SESSION: ${params.SESSION_ID}"
echo "WORKING DIR: \\$(pwd)"
echo "TIME: \\$(date)"
echo "==== OUTPUT ===="
${params.COMMAND} 2>&1
EXIT_CODE=\\$?
echo "==== END OUTPUT ===="
echo "EXIT CODE: \\$EXIT_CODE"
"""
}
}
}
}
}
''')
def _define_all_tools(self) -> Dict[str, Dict[str, Any]]:
"""Define all available tools."""
return {
"hello_world": {
"name": "Hello World",
"description": "Say hello from MiladyOS!",
"parameters": {
"type": "object",
"properties": {},
"required": []
}
},
"view_template": {
"name": "View Template",
"description": "View content of a template with line numbers",
"parameters": {
"type": "object",
"properties": {
"template_name": {
"type": "string",
"description": "Name of the template to view (without .Jenkinsfile extension)"
}
},
"required": ["template_name"]
}
},
"edit_template": {
"name": "Edit Template",
"description": "Edit an existing template in the templates directory",
"parameters": {
"type": "object",
"properties": {
"template_name": {
"type": "string",
"description": "Name of the template to edit (without .Jenkinsfile extension)"
},
"content": {
"type": "string",
"description": "New complete content for the template (for full file replacement)"
},
"edits": {
"type": "array",
"description": "List of edit operations to apply",
"items": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["replace", "insert", "delete"],
"description": "Type of edit operation"
},
"start_line": {
"type": "integer",
"description": "Starting line number (1-indexed)"
},
"end_line": {
"type": "integer",
"description": "Ending line number for replace/delete operations"
},
"content": {
"type": "string",
"description": "Content for replace/insert operations"
}
},
"required": ["type", "start_line"]
}
},
"diff_preview": {
"type": "boolean",
"description": "If true, return a diff preview without saving changes",
"default": False
},
"description": {
"type": "string",
"description": "Updated description for the template (optional)"
}
},
"required": ["template_name"]
}
},
"execute_command": {
"name": "Execute Command",
"description": "Execute a CLI command",
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The CLI command to execute"
},
"working_directory": {
"type": "string",
"description": "Directory to execute the command in",
"default": "/workspace"
},
"session_id": {
"type": "string",
"description": "Optional session ID for tracking related commands"
},
"server_name": {
"type": "string",
"description": "Name of the Jenkins server to use (default is 'default')",
"default": "default"
},
"username": {
"type": "string",
"description": "Jenkins username (optional, defaults to admin)"
},
"password": {
"type": "string",
"description": "Jenkins password (optional, defaults to configured password)"
}
},
"required": ["command"]
}
},
"create_template": {
"name": "Create Template",
"description": "Create or modify a template in the templates directory",
"parameters": {
"type": "object",
"properties": {
"template_name": {
"type": "string",
"description": "Name of the template to create (without .Jenkinsfile extension)"
},
"description": {
"type": "string",
"description": "Description of what the pipeline should do"
},
"agent": {
"type": "string",
"description": "Agent to use (default is 'any')",
"default": "any"
},
"environment": {
"type": "array",
"description": "List of environment variables to set",
"items": {
"type": "string"
}
},
"content": {
"type": "string",
"description": "Raw Jenkinsfile content to use without automatic formatting (optional)"
}
},
"required": ["template_name", "description"]
}
},
"list_templates": {
"name": "List Templates",
"description": "List all available pipeline templates",
"parameters": {
"type": "object",
"properties": {},
"required": []
}
},
"deploy_pipeline": {
"name": "Deploy Pipeline",
"description": "Register a template with Jenkins (with version control)",
"parameters": {
"type": "object",
"properties": {
"template_name": {
"type": "string",
"description": "Name of the template to deploy (without .Jenkinsfile extension)"
},
"job_name": {
"type": "string",
"description": "Name of the Jenkins job to create (defaults to template name)"
},
"server_name": {
"type": "string",
"description": "Name of the Jenkins server to deploy to (default is 'default')",
"default": "default"
},
"username": {
"type": "string",
"description": "Jenkins username (optional, defaults to admin)"
},
"password": {
"type": "string",
"description": "Jenkins password (optional, defaults to configured password)"
}
},
"required": ["template_name"]
}
},
"run_pipeline": {
"name": "Run Pipeline",
"description": "Execute a pipeline and record in metadata layer",
"parameters": {
"type": "object",
"properties": {
"template_name": {
"type": "string",
"description": "Name of the template to run (required unless jenkinsfile_content is provided)"
},
"job_name": {
"type": "string",
"description": "Name of the Jenkins job (defaults to template name)"
},
"server_name": {
"type": "string",
"description": "Name of the Jenkins server to run on (default is 'default')",
"default": "default"
},
"parameters": {
"type": "object",
"description": "Parameters to pass to the pipeline"
},
"stream_output": {
"type": "boolean",
"description": "Whether to stream the job output (default is true)",
"default": True
},
"username": {
"type": "string",
"description": "Jenkins username (optional, defaults to admin)"
},
"password": {
"type": "string",
"description": "Jenkins password (optional, defaults to configured password)"
},
"jenkinsfile_content": {
"type": "string",
"description": "Direct Jenkinsfile content to use instead of a template (optional)"
}
},
"required": []
}
},
"get_pipeline_status": {
"name": "Get Pipeline Status",
"description": "Get status from metadata layer (not directly from Jenkins)",
"parameters": {
"type": "object",
"properties": {
"execution_id": {
"type": "string",
"description": "ID of the execution to check"
}
},
"required": ["execution_id"]
}
},
"list_pipeline_runs": {
"name": "List Pipeline Runs",
"description": "Show execution history from metadata",
"parameters": {
"type": "object",
"properties": {
"template_name": {
"type": "string",
"description": "Optional name of the template to filter by"
},
"limit": {
"type": "integer",
"description": "Maximum number of executions to return",
"default": 10
},
"status": {
"type": "string",
"description": "Optional status to filter by (running, complete, failed)",
"enum": ["running", "complete", "failed"]
}
},
"required": []
}
},
"read_query": {
"name": "Milady SQL Query",
"description": "Execute a SELECT query on MiladyOS's internal SQLite database (read-only)",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "SELECT SQL query to execute on MiladyOS internal database"
}
},
"required": ["query"]
}
},
"list_db_tables": {
"name": "Milady DB Tables",
"description": "List all tables in MiladyOS's internal SQLite database",
"parameters": {
"type": "object",
"properties": {},
"required": []
}
},
"describe_db_table": {
"name": "Milady DB Schema",
"description": "Get the schema information for a specific table in MiladyOS's internal database",