shared_tools 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +3 -0
  3. data/README.md +594 -42
  4. data/lib/shared_tools/{ruby_llm/mcp → mcp}/github_mcp_server.rb +20 -3
  5. data/lib/shared_tools/mcp/imcp.rb +28 -0
  6. data/lib/shared_tools/mcp/tavily_mcp_server.rb +44 -0
  7. data/lib/shared_tools/mcp.rb +24 -0
  8. data/lib/shared_tools/tools/browser/base_driver.rb +64 -0
  9. data/lib/shared_tools/tools/browser/base_tool.rb +50 -0
  10. data/lib/shared_tools/tools/browser/click_tool.rb +54 -0
  11. data/lib/shared_tools/tools/browser/elements/element_grouper.rb +73 -0
  12. data/lib/shared_tools/tools/browser/elements/nearby_element_detector.rb +109 -0
  13. data/lib/shared_tools/tools/browser/formatters/action_formatter.rb +37 -0
  14. data/lib/shared_tools/tools/browser/formatters/data_entry_formatter.rb +135 -0
  15. data/lib/shared_tools/tools/browser/formatters/element_formatter.rb +52 -0
  16. data/lib/shared_tools/tools/browser/formatters/input_formatter.rb +59 -0
  17. data/lib/shared_tools/tools/browser/inspect_tool.rb +87 -0
  18. data/lib/shared_tools/tools/browser/inspect_utils.rb +51 -0
  19. data/lib/shared_tools/tools/browser/page_inspect/button_summarizer.rb +140 -0
  20. data/lib/shared_tools/tools/browser/page_inspect/form_summarizer.rb +98 -0
  21. data/lib/shared_tools/tools/browser/page_inspect/html_summarizer.rb +37 -0
  22. data/lib/shared_tools/tools/browser/page_inspect/link_summarizer.rb +103 -0
  23. data/lib/shared_tools/tools/browser/page_inspect_tool.rb +55 -0
  24. data/lib/shared_tools/tools/browser/page_screenshot_tool.rb +39 -0
  25. data/lib/shared_tools/tools/browser/selector_generator/base_selectors.rb +28 -0
  26. data/lib/shared_tools/tools/browser/selector_generator/contextual_selectors.rb +140 -0
  27. data/lib/shared_tools/tools/browser/selector_generator.rb +73 -0
  28. data/lib/shared_tools/tools/browser/selector_inspect_tool.rb +67 -0
  29. data/lib/shared_tools/tools/browser/text_field_area_set_tool.rb +45 -0
  30. data/lib/shared_tools/tools/browser/visit_tool.rb +43 -0
  31. data/lib/shared_tools/tools/browser/watir_driver.rb +132 -0
  32. data/lib/shared_tools/tools/browser.rb +27 -0
  33. data/lib/shared_tools/tools/browser_tool.rb +255 -0
  34. data/lib/shared_tools/tools/calculator_tool.rb +169 -0
  35. data/lib/shared_tools/tools/composite_analysis_tool.rb +520 -0
  36. data/lib/shared_tools/tools/computer/base_driver.rb +177 -0
  37. data/lib/shared_tools/tools/computer/mac_driver.rb +103 -0
  38. data/lib/shared_tools/tools/computer.rb +21 -0
  39. data/lib/shared_tools/tools/computer_tool.rb +207 -0
  40. data/lib/shared_tools/tools/data_science_kit.rb +707 -0
  41. data/lib/shared_tools/tools/database/base_driver.rb +17 -0
  42. data/lib/shared_tools/tools/database/postgres_driver.rb +30 -0
  43. data/lib/shared_tools/tools/database/sqlite_driver.rb +29 -0
  44. data/lib/shared_tools/tools/database.rb +9 -0
  45. data/lib/shared_tools/tools/database_query_tool.rb +313 -0
  46. data/lib/shared_tools/tools/database_tool.rb +99 -0
  47. data/lib/shared_tools/tools/devops_toolkit.rb +420 -0
  48. data/lib/shared_tools/tools/disk/base_driver.rb +91 -0
  49. data/lib/shared_tools/tools/disk/base_tool.rb +20 -0
  50. data/lib/shared_tools/tools/disk/directory_create_tool.rb +39 -0
  51. data/lib/shared_tools/tools/disk/directory_delete_tool.rb +39 -0
  52. data/lib/shared_tools/tools/disk/directory_list_tool.rb +37 -0
  53. data/lib/shared_tools/tools/disk/directory_move_tool.rb +40 -0
  54. data/lib/shared_tools/tools/disk/file_create_tool.rb +38 -0
  55. data/lib/shared_tools/tools/disk/file_delete_tool.rb +40 -0
  56. data/lib/shared_tools/tools/disk/file_move_tool.rb +43 -0
  57. data/lib/shared_tools/tools/disk/file_read_tool.rb +40 -0
  58. data/lib/shared_tools/tools/disk/file_replace_tool.rb +44 -0
  59. data/lib/shared_tools/tools/disk/file_write_tool.rb +40 -0
  60. data/lib/shared_tools/tools/disk/local_driver.rb +91 -0
  61. data/lib/shared_tools/tools/disk.rb +17 -0
  62. data/lib/shared_tools/tools/disk_tool.rb +132 -0
  63. data/lib/shared_tools/tools/doc/pdf_reader_tool.rb +79 -0
  64. data/lib/shared_tools/tools/doc.rb +8 -0
  65. data/lib/shared_tools/tools/doc_tool.rb +109 -0
  66. data/lib/shared_tools/tools/docker/base_tool.rb +56 -0
  67. data/lib/shared_tools/tools/docker/compose_run_tool.rb +77 -0
  68. data/lib/shared_tools/tools/docker.rb +8 -0
  69. data/lib/shared_tools/tools/error_handling_tool.rb +403 -0
  70. data/lib/shared_tools/tools/eval/python_eval_tool.rb +209 -0
  71. data/lib/shared_tools/tools/eval/ruby_eval_tool.rb +93 -0
  72. data/lib/shared_tools/tools/eval/shell_eval_tool.rb +64 -0
  73. data/lib/shared_tools/tools/eval.rb +10 -0
  74. data/lib/shared_tools/tools/eval_tool.rb +139 -0
  75. data/lib/shared_tools/tools/secure_tool_template.rb +353 -0
  76. data/lib/shared_tools/tools/version.rb +7 -0
  77. data/lib/shared_tools/tools/weather_tool.rb +197 -0
  78. data/lib/shared_tools/tools/workflow_manager_tool.rb +312 -0
  79. data/lib/shared_tools/tools.rb +16 -0
  80. data/lib/shared_tools/version.rb +1 -1
  81. data/lib/shared_tools.rb +9 -24
  82. metadata +189 -68
  83. data/lib/shared_tools/llm_rb/run_shell_command.rb +0 -23
  84. data/lib/shared_tools/llm_rb.rb +0 -9
  85. data/lib/shared_tools/omniai.rb +0 -9
  86. data/lib/shared_tools/raix/what_is_the_weather.rb +0 -18
  87. data/lib/shared_tools/raix.rb +0 -9
  88. data/lib/shared_tools/ruby_llm/edit_file.rb +0 -71
  89. data/lib/shared_tools/ruby_llm/incomplete/calculator_tool.rb +0 -70
  90. data/lib/shared_tools/ruby_llm/incomplete/composite_analysis_tool.rb +0 -89
  91. data/lib/shared_tools/ruby_llm/incomplete/data_science_kit.rb +0 -128
  92. data/lib/shared_tools/ruby_llm/incomplete/database_query_tool.rb +0 -100
  93. data/lib/shared_tools/ruby_llm/incomplete/devops_toolkit.rb +0 -112
  94. data/lib/shared_tools/ruby_llm/incomplete/error_handling_tool.rb +0 -109
  95. data/lib/shared_tools/ruby_llm/incomplete/secure_tool_template.rb +0 -117
  96. data/lib/shared_tools/ruby_llm/incomplete/weather_tool.rb +0 -110
  97. data/lib/shared_tools/ruby_llm/incomplete/workflow_manager_tool.rb +0 -145
  98. data/lib/shared_tools/ruby_llm/list_files.rb +0 -49
  99. data/lib/shared_tools/ruby_llm/mcp/imcp.rb +0 -15
  100. data/lib/shared_tools/ruby_llm/mcp.rb +0 -12
  101. data/lib/shared_tools/ruby_llm/pdf_page_reader.rb +0 -59
  102. data/lib/shared_tools/ruby_llm/python_eval.rb +0 -194
  103. data/lib/shared_tools/ruby_llm/read_file.rb +0 -40
  104. data/lib/shared_tools/ruby_llm/ruby_eval.rb +0 -77
  105. data/lib/shared_tools/ruby_llm/run_shell_command.rb +0 -49
  106. data/lib/shared_tools/ruby_llm.rb +0 -12
@@ -1,89 +0,0 @@
1
- # composite_analysis_tool.rb - Tool that uses other tools
2
- require 'ruby_llm/tool'
3
-
4
- module Tools
5
- class CompositeAnalysis < RubyLLM::Tool
6
- def self.name = "composite_analysis"
7
-
8
- description <<~DESCRIPTION
9
- Perform comprehensive multi-stage data analysis by orchestrating multiple specialized tools
10
- to provide complete insights from various data sources. This composite tool automatically
11
- determines the appropriate data fetching method (web scraping for URLs, file reading for
12
- local paths), analyzes data structure and content, generates statistical insights,
13
- and suggests appropriate visualizations based on the data characteristics.
14
- Ideal for exploratory data analysis workflows where you need a complete picture
15
- from initial data loading through final insights.
16
- DESCRIPTION
17
-
18
- param :data_source,
19
- desc: <<~DESC,
20
- Primary data source to analyze. Can be either a local file path or a web URL.
21
- For files: Use relative or absolute paths to CSV, JSON, XML, or text files.
22
- For URLs: Use complete HTTP/HTTPS URLs to accessible data endpoints or web pages.
23
- The tool automatically detects the source type and uses appropriate fetching methods.
24
- Examples: './data/sales.csv', '/home/user/data.json', 'https://api.example.com/data'
25
- DESC
26
- type: :string,
27
- required: true
28
-
29
- def execute(data_source:)
30
- results = {}
31
-
32
- begin
33
- # Step 1: Fetch data using appropriate tool
34
- if data_source.start_with?('http')
35
- results[:data] = fetch_web_data(data_source)
36
- else
37
- results[:data] = read_file_data(data_source)
38
- end
39
-
40
- # Step 2: Analyze data structure
41
- results[:structure] = analyze_data_structure(results[:data])
42
-
43
- # Step 3: Generate insights
44
- results[:insights] = generate_insights(results[:data], results[:structure])
45
-
46
- # Step 4: Create visualizations if applicable
47
- if results[:structure][:numeric_columns]&.any?
48
- results[:visualizations] = suggest_visualizations(results[:structure])
49
- end
50
-
51
- {
52
- success: true,
53
- analysis: results,
54
- data_source: data_source,
55
- analyzed_at: Time.now.iso8601
56
- }
57
- rescue => e
58
- {
59
- success: false,
60
- error: e.message,
61
- data_source: data_source,
62
- partial_results: results
63
- }
64
- end
65
- end
66
-
67
- private
68
-
69
- def fetch_web_data(url)
70
- # Use shared web tools or custom HTTP client
71
- end
72
-
73
- def read_file_data(file_path)
74
- # Use shared file tools
75
- end
76
-
77
- def analyze_data_structure(data)
78
- # Implementation for data structure analysis
79
- end
80
-
81
- def generate_insights(data, structure)
82
- # Implementation for insight generation
83
- end
84
-
85
- def suggest_visualizations(structure)
86
- # Implementation for visualization suggestions
87
- end
88
- end
89
- end
@@ -1,128 +0,0 @@
1
- # data_science_kit.rb - Analytics and ML tools
2
- require 'ruby_llm/tool'
3
-
4
- module Tools
5
- class DataScienceKit < RubyLLM::Tool
6
- def self.name = "data_science_kit"
7
-
8
- description <<~DESCRIPTION
9
- Comprehensive data science and analytics toolkit for performing statistical analysis,
10
- machine learning tasks, and data exploration on various data sources. This tool provides
11
- a unified interface for common data science operations including descriptive statistics,
12
- correlation analysis, time series analysis, clustering algorithms, and predictive modeling.
13
- It automatically handles data loading, validation, preprocessing, and result formatting.
14
- Supports multiple data formats and provides detailed analysis results with visualizations
15
- recommendations and statistical significance testing where applicable.
16
- DESCRIPTION
17
-
18
- param :analysis_type,
19
- desc: <<~DESC,
20
- Type of data science analysis to perform:
21
- - 'statistical_summary': Descriptive statistics, distributions, outlier detection
22
- - 'correlation_analysis': Correlation matrices, feature relationships, dependency analysis
23
- - 'time_series': Trend analysis, seasonality detection, forecasting
24
- - 'clustering': K-means, hierarchical clustering, cluster analysis
25
- - 'prediction': Regression analysis, classification, predictive modeling
26
- Each analysis type requires specific data formats and optional parameters.
27
- DESC
28
- type: :string,
29
- required: true,
30
- enum: ["statistical_summary", "correlation_analysis", "time_series", "clustering", "prediction"]
31
-
32
- param :data_source,
33
- desc: <<~DESC,
34
- Data source specification for analysis. Can be:
35
- - File path: Relative or absolute path to CSV, JSON, Excel, or Parquet files
36
- - Database query: SQL SELECT statement for database-sourced data
37
- - API endpoint: HTTP URL for REST API data sources
38
- The tool automatically detects the format and applies appropriate parsing.
39
- Examples: './sales_data.csv', 'SELECT * FROM transactions', 'https://api.company.com/data'
40
- DESC
41
- type: :string,
42
- required: true
43
-
44
- param :parameters,
45
- desc: <<~DESC,
46
- Hash of analysis-specific parameters and configuration options:
47
- - statistical_summary: confidence_level, include_quartiles, outlier_method
48
- - correlation_analysis: method (pearson/spearman), significance_level
49
- - time_series: date_column, value_column, frequency, forecast_periods
50
- - clustering: n_clusters, algorithm (kmeans/hierarchical), distance_metric
51
- - prediction: target_column, feature_columns, model_type, validation_split
52
- Default empty hash uses standard parameters for each analysis type.
53
- DESC
54
- type: :hash,
55
- default: {}
56
-
57
- def execute(analysis_type:, data_source:, parameters: {})
58
- begin
59
- # Load and validate data
60
- data = load_data(data_source)
61
- validate_data_for_analysis(data, analysis_type)
62
-
63
- # Perform analysis
64
- result = case analysis_type
65
- when "statistical_summary"
66
- generate_statistical_summary(data, parameters)
67
- when "correlation_analysis"
68
- perform_correlation_analysis(data, parameters)
69
- when "time_series"
70
- analyze_time_series(data, parameters)
71
- when "clustering"
72
- perform_clustering(data, parameters)
73
- when "prediction"
74
- generate_predictions(data, parameters)
75
- end
76
-
77
- {
78
- success: true,
79
- analysis_type: analysis_type,
80
- result: result,
81
- data_summary: summarize_data(data),
82
- analyzed_at: Time.now.iso8601
83
- }
84
- rescue => e
85
- {
86
- success: false,
87
- error: e.message,
88
- analysis_type: analysis_type,
89
- data_source: data_source
90
- }
91
- end
92
- end
93
-
94
- private
95
-
96
- def load_data(source)
97
- # Implementation for data loading from various sources
98
- end
99
-
100
- def validate_data_for_analysis(data, analysis_type)
101
- # Implementation for data validation
102
- end
103
-
104
- def generate_statistical_summary(data, parameters)
105
- # Implementation for statistical summary
106
- end
107
-
108
- def perform_correlation_analysis(data, parameters)
109
- # Implementation for correlation analysis
110
- end
111
-
112
- def analyze_time_series(data, parameters)
113
- # Implementation for time series analysis
114
- end
115
-
116
- def perform_clustering(data, parameters)
117
- # Implementation for clustering
118
- end
119
-
120
- def generate_predictions(data, parameters)
121
- # Implementation for prediction
122
- end
123
-
124
- def summarize_data(data)
125
- # Implementation for data summary
126
- end
127
- end
128
- end
@@ -1,100 +0,0 @@
1
- # database_query_tool.rb - Database interaction example
2
- require 'ruby_llm/tool'
3
- require 'sequel'
4
-
5
- module Tools
6
- class DatabaseQuery < RubyLLM::Tool
7
- def self.name = "database_query"
8
-
9
- description <<~DESCRIPTION
10
- Execute safe, read-only database queries with automatic connection management and security controls.
11
- This tool is designed for secure data retrieval operations only, restricting access to SELECT statements
12
- to prevent any data modification. It includes automatic connection pooling, query result limiting,
13
- and comprehensive error handling. The tool supports multiple database configurations through
14
- environment variables and ensures all connections are properly closed after use.
15
- Perfect for AI-assisted data analysis and reporting workflows where read-only access is required.
16
- DESCRIPTION
17
-
18
- param :query,
19
- desc: <<~DESC,
20
- SQL SELECT query to execute against the database. Only SELECT statements are permitted
21
- for security reasons - INSERT, UPDATE, DELETE, and DDL statements will be rejected.
22
- The query should be well-formed SQL appropriate for the target database system.
23
- Examples: 'SELECT * FROM users WHERE active = true', 'SELECT COUNT(*) FROM orders'.
24
- Table and column names should match the database schema exactly.
25
- DESC
26
- type: :string,
27
- required: true
28
-
29
- param :database,
30
- desc: <<~DESC,
31
- Database configuration name to use for the connection. This corresponds to environment
32
- variables like DATABASE_URL, STAGING_DATABASE_URL, etc. The tool will look for
33
- an environment variable named {DATABASE_NAME}_DATABASE_URL (uppercase).
34
- Default is 'default' which looks for DEFAULT_DATABASE_URL environment variable.
35
- Common values: 'default', 'staging', 'analytics', 'reporting'.
36
- DESC
37
- type: :string,
38
- default: "default"
39
-
40
- param :limit,
41
- desc: <<~DESC,
42
- Maximum number of rows to return from the query to prevent excessive memory usage
43
- and long response times. The tool automatically adds a LIMIT clause if one is not
44
- present in the original query. Set to a reasonable value based on expected data size.
45
- Minimum: 1, Maximum: 10000, Default: 100. For large datasets, consider using
46
- pagination or more specific WHERE clauses.
47
- DESC
48
- type: :integer,
49
- default: 100
50
-
51
- def execute(query:, database: "default", limit: 100)
52
- begin
53
- # Security: Only allow SELECT queries
54
- normalized_query = query.strip.downcase
55
- unless normalized_query.start_with?('select')
56
- raise "Only SELECT queries are allowed for security"
57
- end
58
-
59
- db = connect_to_database(database)
60
- limited_query = add_limit_to_query(query, limit)
61
-
62
- results = db[limited_query].all
63
-
64
- {
65
- success: true,
66
- query: limited_query,
67
- row_count: results.length,
68
- data: results,
69
- database: database,
70
- executed_at: Time.now.iso8601
71
- }
72
- rescue => e
73
- {
74
- success: false,
75
- error: e.message,
76
- query: query,
77
- database: database
78
- }
79
- ensure
80
- db&.disconnect
81
- end
82
- end
83
-
84
- private
85
-
86
- def connect_to_database(database_name)
87
- # Implementation depends on your database setup
88
- connection_string = ENV["#{database_name.upcase}_DATABASE_URL"]
89
- raise "Database connection not configured for #{database_name}" unless connection_string
90
-
91
- Sequel.connect(connection_string)
92
- end
93
-
94
- def add_limit_to_query(query, limit)
95
- # Add LIMIT clause if not present
96
- query += " LIMIT #{limit}" unless query.downcase.include?('limit')
97
- query
98
- end
99
- end
100
- end
@@ -1,112 +0,0 @@
1
- # devops_toolkit.rb - System administration tools
2
- require 'ruby_llm/tool'
3
- require 'securerandom'
4
-
5
- module Tools
6
- class DevOpsToolkit < RubyLLM::Tool
7
- def self.name = "devops_toolkit"
8
-
9
- description <<~DESCRIPTION
10
- Comprehensive DevOps and system administration toolkit for managing application deployments,
11
- monitoring system health, and performing operational tasks across different environments.
12
- This tool provides secure, audited access to common DevOps operations including deployments,
13
- rollbacks, health checks, log analysis, and metrics collection. It includes built-in safety
14
- mechanisms for production environments, comprehensive logging for compliance, and support
15
- for multiple deployment environments. All operations are logged and require appropriate
16
- permissions and confirmations for sensitive environments.
17
- DESCRIPTION
18
-
19
- param :operation,
20
- desc: <<~DESC,
21
- Specific DevOps operation to perform:
22
- - 'deploy': Deploy application code to the specified environment
23
- - 'rollback': Revert to the previous stable deployment version
24
- - 'health_check': Perform comprehensive health and status checks
25
- - 'log_analysis': Analyze application and system logs for issues
26
- - 'metric_collection': Gather and report system and application metrics
27
- Each operation has specific requirements and safety checks.
28
- DESC
29
- type: :string,
30
- required: true,
31
- enum: ["deploy", "rollback", "health_check", "log_analysis", "metric_collection"]
32
-
33
- param :environment,
34
- desc: <<~DESC,
35
- Target environment for the DevOps operation:
36
- - 'development': Local or shared development environment (minimal restrictions)
37
- - 'staging': Pre-production environment for testing (moderate restrictions)
38
- - 'production': Live production environment (maximum restrictions and confirmations)
39
- Production operations require explicit confirmation via the 'production_confirmed' option.
40
- DESC
41
- type: :string,
42
- default: "staging",
43
- enum: ["development", "staging", "production"]
44
-
45
- param :options,
46
- desc: <<~DESC,
47
- Hash of operation-specific options and parameters:
48
- - For deploy: version, branch, rollback_on_failure, notification_channels
49
- - For rollback: target_version, confirmation_required
50
- - For health_check: services_to_check, timeout_seconds
51
- - For log_analysis: time_range, log_level, search_patterns
52
- - For metric_collection: metric_types, time_window, output_format
53
- Production operations require 'production_confirmed: true' for safety.
54
- DESC
55
- type: :hash,
56
- default: {}
57
-
58
- def execute(operation:, environment: "staging", options: {})
59
- # Security: Require explicit production confirmation
60
- if environment == "production" && !options[:production_confirmed]
61
- return {
62
- success: false,
63
- error: "Production operations require explicit confirmation",
64
- required_option: "production_confirmed: true"
65
- }
66
- end
67
-
68
- case operation
69
- when "deploy"
70
- perform_deployment(environment, options)
71
- when "rollback"
72
- perform_rollback(environment, options)
73
- when "health_check"
74
- perform_health_check(environment, options)
75
- when "log_analysis"
76
- analyze_logs(environment, options)
77
- when "metric_collection"
78
- collect_metrics(environment, options)
79
- end
80
- end
81
-
82
- private
83
-
84
- def perform_deployment(environment, options)
85
- # Implementation for deployment logic
86
- {
87
- success: true,
88
- operation: "deploy",
89
- environment: environment,
90
- deployed_at: Time.now.iso8601,
91
- deployment_id: SecureRandom.uuid,
92
- details: "Deployment completed successfully"
93
- }
94
- end
95
-
96
- def perform_rollback(environment, options)
97
- # Implementation for rollback logic
98
- end
99
-
100
- def perform_health_check(environment, options)
101
- # Implementation for health check logic
102
- end
103
-
104
- def analyze_logs(environment, options)
105
- # Implementation for log analysis logic
106
- end
107
-
108
- def collect_metrics(environment, options)
109
- # Implementation for metric collection logic
110
- end
111
- end
112
- end
@@ -1,109 +0,0 @@
1
- # error_handling_tool.rb - Comprehensive error handling
2
- require 'ruby_llm/tool'
3
- require 'securerandom'
4
-
5
- module Tools
6
- class RobustTool < RubyLLM::Tool
7
- def self.name = 'robust_tool'
8
-
9
- description <<~DESCRIPTION
10
- Reference tool demonstrating comprehensive error handling patterns and resilience strategies
11
- for robust tool development. This tool showcases best practices for handling different
12
- types of errors including validation errors, network failures, authorization issues,
13
- and general exceptions. It implements retry mechanisms with exponential backoff,
14
- proper resource cleanup, detailed error categorization, and user-friendly error messages.
15
- Perfect as a template for building production-ready tools that need to handle
16
- various failure scenarios gracefully.
17
- DESCRIPTION
18
-
19
- def execute(**params)
20
- begin
21
- validate_preconditions(params)
22
- result = perform_operation(params)
23
- validate_postconditions(result)
24
-
25
- {
26
- success: true,
27
- result: result,
28
- metadata: operation_metadata
29
- }
30
- rescue ValidationError => e
31
- handle_validation_error(e, params)
32
- rescue NetworkError => e
33
- handle_network_error(e, params)
34
- rescue AuthorizationError => e
35
- handle_authorization_error(e, params)
36
- rescue StandardError => e
37
- handle_general_error(e, params)
38
- ensure
39
- cleanup_resources
40
- end
41
- end
42
-
43
- private
44
-
45
- def validate_preconditions(params)
46
- # Check all preconditions before execution
47
- end
48
-
49
- def perform_operation(params)
50
- # Main operation logic with retry mechanism
51
- retry_count = 0
52
- max_retries = 3
53
-
54
- begin
55
- # Operation implementation
56
- rescue RetryableError => e
57
- retry_count += 1
58
- if retry_count <= max_retries
59
- sleep(2 ** retry_count) # Exponential backoff
60
- retry
61
- else
62
- raise e
63
- end
64
- end
65
- end
66
-
67
- def handle_validation_error(error, params)
68
- {
69
- success: false,
70
- error_type: "validation",
71
- error: error.message,
72
- suggestions: error.suggestions,
73
- provided_params: params.keys
74
- }
75
- end
76
-
77
- def handle_network_error(error, params)
78
- {
79
- success: false,
80
- error_type: "network",
81
- error: "Network operation failed",
82
- retry_suggested: true,
83
- retry_after: 30
84
- }
85
- end
86
-
87
- def handle_authorization_error(error, params)
88
- {
89
- success: false,
90
- error_type: "authorization",
91
- error: "Access denied",
92
- documentation_url: "https://docs.example.com/auth"
93
- }
94
- end
95
-
96
- def handle_general_error(error, params)
97
- {
98
- success: false,
99
- error_type: "general",
100
- error: error.message,
101
- support_reference: SecureRandom.uuid
102
- }
103
- end
104
-
105
- def cleanup_resources
106
- # Clean up any allocated resources
107
- end
108
- end
109
- end
@@ -1,117 +0,0 @@
1
- # secure_tool_template.rb - Security best practices
2
- require 'ruby_llm/tool'
3
- require 'timeout'
4
-
5
- module Tools
6
- class SecureTool < RubyLLM::Tool
7
- def self.name = 'secure_tool'
8
-
9
- description <<~DESCRIPTION
10
- Template tool demonstrating comprehensive security best practices for safe tool development.
11
- This tool serves as a reference implementation for secure tool design, including input
12
- validation, output sanitization, permission checks, rate limiting, audit logging,
13
- timeout mechanisms, and proper error handling. It provides a complete security framework
14
- that can be adapted for other tools that handle sensitive data or perform privileged
15
- operations. All security violations are logged for monitoring and compliance purposes.
16
- DESCRIPTION
17
-
18
- # Input validation
19
- param :user_input,
20
- desc: <<~DESC,
21
- User-provided input string that will be processed with comprehensive security validation.
22
- Input is automatically sanitized and validated against multiple security criteria:
23
- - Maximum length of 1000 characters to prevent buffer overflow attacks
24
- - Character whitelist allowing only alphanumeric, spaces, hyphens, underscores, and dots
25
- - Automatic removal of potentially dangerous characters and sequences
26
- - Rate limiting to prevent abuse and denial-of-service attacks
27
- All input validation failures are logged for security monitoring.
28
- DESC
29
- type: :string,
30
- required: true,
31
- validator: ->(value) {
32
- # Custom validation logic
33
- raise "Input too long" if value.length > 1000
34
- raise "Invalid characters" unless value.match?(/\A[a-zA-Z0-9\s\-_\.]+\z/)
35
- true
36
- }
37
-
38
- def execute(user_input:)
39
- begin
40
- # 1. Sanitize inputs
41
- sanitized_input = sanitize_input(user_input)
42
-
43
- # 2. Validate permissions
44
- validate_permissions
45
-
46
- # 3. Rate limiting
47
- check_rate_limits
48
-
49
- # 4. Audit logging
50
- log_tool_usage(sanitized_input)
51
-
52
- # 5. Execute with timeout
53
- result = execute_with_timeout(sanitized_input)
54
-
55
- # 6. Sanitize outputs
56
- sanitized_result = sanitize_output(result)
57
-
58
- {
59
- success: true,
60
- result: sanitized_result,
61
- executed_at: Time.now.iso8601
62
- }
63
- rescue SecurityError => e
64
- log_security_violation(e, user_input)
65
- {
66
- success: false,
67
- error: "Security violation: Access denied",
68
- violation_logged: true
69
- }
70
- rescue => e
71
- {
72
- success: false,
73
- error: "Tool execution failed: #{e.message}"
74
- }
75
- end
76
- end
77
-
78
- private
79
-
80
- def sanitize_input(input)
81
- # Remove potentially dangerous characters
82
- # Validate against whitelist
83
- input.gsub(/[^\w\s\-\.]/, '')
84
- end
85
-
86
- def validate_permissions
87
- # Check user permissions
88
- # Validate environment access
89
- # Verify resource limits
90
- end
91
-
92
- def check_rate_limits
93
- # Implement rate limiting logic
94
- end
95
-
96
- def log_tool_usage(input)
97
- # Audit logging for compliance
98
- end
99
-
100
- def execute_with_timeout(input, timeout: 30)
101
- # Implement timeout mechanism
102
- Timeout::timeout(timeout) do
103
- # Actual tool logic here
104
- end
105
- end
106
-
107
- def sanitize_output(output)
108
- # Remove sensitive information from output
109
- # Validate output format
110
- output
111
- end
112
-
113
- def log_security_violation(error, input)
114
- # Log security violations for monitoring
115
- end
116
- end
117
- end