htm-cli 0.2.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 (52) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +11 -0
  3. data/COMMITS.md +196 -0
  4. data/LICENSE.txt +21 -0
  5. data/README.md +99 -0
  6. data/Rakefile +23 -0
  7. data/bin/htm +18 -0
  8. data/lib/htm/admin/database_commands.rb +489 -0
  9. data/lib/htm/admin/enrich_commands.rb +275 -0
  10. data/lib/htm/admin/entity_commands.rb +203 -0
  11. data/lib/htm/admin/entity_graph.rb +313 -0
  12. data/lib/htm/admin/file_commands.rb +323 -0
  13. data/lib/htm/admin/memory_commands/edit.rb +175 -0
  14. data/lib/htm/admin/memory_commands/entities.rb +189 -0
  15. data/lib/htm/admin/memory_commands/entity_lines.rb +111 -0
  16. data/lib/htm/admin/memory_commands/search.rb +205 -0
  17. data/lib/htm/admin/memory_commands/tag_search.rb +98 -0
  18. data/lib/htm/admin/memory_commands/text.rb +166 -0
  19. data/lib/htm/admin/memory_commands/working_memory.rb +71 -0
  20. data/lib/htm/admin/memory_commands.rb +196 -0
  21. data/lib/htm/admin/tag_commands.rb +352 -0
  22. data/lib/htm/admin/tag_graph.rb +345 -0
  23. data/lib/htm/admin/templates/tag_graph.html +319 -0
  24. data/lib/htm/admin.rb +266 -0
  25. data/lib/htm/cli/config_file.rb +73 -0
  26. data/lib/htm/cli/db.rb +80 -0
  27. data/lib/htm/cli/enrich.rb +52 -0
  28. data/lib/htm/cli/entities.rb +268 -0
  29. data/lib/htm/cli/environment.rb +74 -0
  30. data/lib/htm/cli/error_suggestion.rb +97 -0
  31. data/lib/htm/cli/files.rb +41 -0
  32. data/lib/htm/cli/group.rb +46 -0
  33. data/lib/htm/cli/memory.rb +410 -0
  34. data/lib/htm/cli/memory_command.rb +72 -0
  35. data/lib/htm/cli/robots.rb +82 -0
  36. data/lib/htm/cli/support.rb +46 -0
  37. data/lib/htm/cli/tags.rb +103 -0
  38. data/lib/htm/cli/version.rb +11 -0
  39. data/lib/htm/cli/working_memory.rb +41 -0
  40. data/lib/htm/cli.rb +96 -0
  41. data/lib/htm/mcp/entity_tools.rb +334 -0
  42. data/lib/htm/mcp/file_tools.rb +196 -0
  43. data/lib/htm/mcp/group_tools.rb +466 -0
  44. data/lib/htm/mcp/node_tools.rb +358 -0
  45. data/lib/htm/mcp/resources.rb +192 -0
  46. data/lib/htm/mcp/robot_team_tools.rb +129 -0
  47. data/lib/htm/mcp/server.rb +111 -0
  48. data/lib/htm/mcp/tag_tools.rb +130 -0
  49. data/lib/htm/mcp/tool.rb +40 -0
  50. data/lib/htm/mcp/tool_support.rb +108 -0
  51. data/lib/htm/mcp/tools.rb +461 -0
  52. metadata +181 -0
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'logger'
4
+ require 'fast_mcp'
5
+ require 'ruby_llm'
6
+
7
+ require_relative '../cli/error_suggestion'
8
+ require_relative 'tools'
9
+ require_relative 'node_tools'
10
+ require_relative 'tag_tools'
11
+ require_relative 'entity_tools'
12
+ require_relative 'file_tools'
13
+ require_relative 'robot_team_tools'
14
+ require_relative 'group_tools'
15
+ require_relative 'resources'
16
+
17
+ class HTM
18
+ module MCP
19
+ # Every tool the server registers
20
+ ALL_TOOLS = (TOOLS + NODE_TOOLS + TAG_TOOLS + ENTITY_TOOLS + FILE_TOOLS + ROBOT_TEAM_TOOLS + GROUP_TOOLS).freeze
21
+
22
+ # MCP Server setup and lifecycle management
23
+ module Server
24
+ module_function
25
+
26
+ def start
27
+ check_database_config!
28
+ verify_database_connection!
29
+ configure_logging!
30
+ configure_htm!
31
+
32
+ server = create_server
33
+ register_tools(server)
34
+ register_resources(server)
35
+
36
+ server.start
37
+ end
38
+
39
+ # Exit with how to configure the database when none is configured (env,
40
+ # --config file, ~/.config/htm/htm.yml or defaults)
41
+ def check_database_config!
42
+ return if HTM.config.database_configured?
43
+
44
+ startup_error "Error: Database not configured.",
45
+ "Set HTM_DATABASE__URL or HTM_DATABASE__NAME, or database.url / database.name",
46
+ "in a config file (--config FILE or ~/.config/htm/htm.yml).",
47
+ "Run 'htm env' for details."
48
+ end
49
+
50
+ def verify_database_connection!
51
+ HTM::SequelConfig.establish_connection!
52
+ # Quick connectivity test
53
+ HTM.db.execute("SELECT 1")
54
+ rescue => e
55
+ startup_error "Error: Cannot connect to database.", e.message, "",
56
+ *HTM::CLI::ErrorSuggestion.for_error(e.message)
57
+ end
58
+
59
+ # Print +lines+ to stderr, then exit 1. Not warn: it is silent once HTM
60
+ # sets $VERBOSE to nil, and stdout belongs to the MCP protocol
61
+ def startup_error(*lines)
62
+ $stderr.puts(*lines) # rubocop:disable Style/StderrPuts
63
+ exit 1
64
+ end
65
+
66
+ def configure_logging!
67
+ # IMPORTANT: MCP uses STDIO for JSON-RPC communication.
68
+ # ALL logging must go to STDERR to avoid corrupting the protocol.
69
+ @stderr_logger = Logger.new($stderr)
70
+ @stderr_logger.level = Logger::INFO
71
+ @stderr_logger.formatter = proc do |severity, datetime, _progname, msg|
72
+ "[MCP #{severity}] #{datetime.strftime('%H:%M:%S')} #{msg}\n"
73
+ end
74
+
75
+ # Silent logger for RubyLLM/HTM internals (prevents STDOUT corruption)
76
+ @silent_logger = Logger.new(IO::NULL)
77
+
78
+ # Configure RubyLLM to not log to STDOUT (corrupts MCP protocol)
79
+ RubyLLM.configure do |config|
80
+ config.logger = @silent_logger
81
+ end
82
+
83
+ # Set logger for MCP session
84
+ Session.attach_logger(@stderr_logger)
85
+ end
86
+
87
+ def configure_htm!
88
+ HTM.configure do |config|
89
+ # Job backend now comes from config (defaults to :fiber)
90
+ # Use HTM_JOB__BACKEND=inline or config file to override
91
+ config.logger = @silent_logger # Silent logging for MCP
92
+ end
93
+ end
94
+
95
+ def create_server
96
+ FastMcp::Server.new(
97
+ name: 'htm-memory-server',
98
+ version: HTM::VERSION
99
+ )
100
+ end
101
+
102
+ def register_tools(server)
103
+ ALL_TOOLS.each { |tool| server.register_tool(tool) }
104
+ end
105
+
106
+ def register_resources(server)
107
+ RESOURCES.each { |resource| server.register_resource(resource) }
108
+ end
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'tool'
4
+
5
+ class HTM
6
+ module MCP
7
+ # Tool: Most used tags
8
+ class PopularTagsTool < Tool
9
+ read_only!
10
+ description "List the most used tags, optionally only counting memories from a timeframe"
11
+
12
+ arguments do
13
+ optional(:limit).filled(:integer).description("Maximum number of tags (default: 20)")
14
+ optional(:timeframe).filled(:string).description(
15
+ "Only count memories from this time: natural language ('last week') or ISO8601 'start..end'"
16
+ )
17
+ end
18
+
19
+ def call(limit: 20, timeframe: nil)
20
+ log_info "PopularTagsTool called: limit=#{limit}, timeframe=#{timeframe.inspect}"
21
+
22
+ guarded do
23
+ tags = session_htm.long_term_memory.popular_tags(limit:, timeframe: timeframe_span(timeframe))
24
+
25
+ success(timeframe:, count: tags.length, tags:)
26
+ end
27
+ end
28
+ end
29
+
30
+ # Tool: Tags that appear together
31
+ class TopicRelationshipsTool < Tool
32
+ read_only!
33
+ description "Find pairs of tags that are used together on the same memories, most shared first"
34
+
35
+ arguments do
36
+ optional(:min_shared_nodes).filled(:integer).description("Minimum number of memories a pair shares (default: 2)")
37
+ optional(:limit).filled(:integer).description("Maximum number of pairs (default: 50)")
38
+ end
39
+
40
+ def call(min_shared_nodes: 2, limit: 50)
41
+ log_info "TopicRelationshipsTool called: min_shared_nodes=#{min_shared_nodes}, limit=#{limit}"
42
+
43
+ guarded do
44
+ pairs = session_htm.long_term_memory.topic_relationships(min_shared_nodes:, limit:).map do |row|
45
+ { topic1: row['topic1'], topic2: row['topic2'], shared_nodes: row['shared_nodes'].to_i }
46
+ end
47
+
48
+ success(count: pairs.length, relationships: pairs)
49
+ end
50
+ end
51
+ end
52
+
53
+ # Tool: Memories carrying given tags
54
+ class SearchByTagsTool < Tool
55
+ read_only!
56
+ description "Find memories carrying any or all of the given tags, ranked by relevance"
57
+
58
+ MATCHES = %w[any all].freeze
59
+
60
+ arguments do
61
+ required(:tags).array(:string).description("Exact tag names (e.g., ['database:postgresql', 'performance'])")
62
+ optional(:match).filled(:string).description("'any' (at least one tag, default) or 'all' (every tag)")
63
+ optional(:limit).filled(:integer).description("Maximum number of memories (default: 20)")
64
+ optional(:timeframe).filled(:string).description(
65
+ "Only memories from this time: natural language ('last week') or ISO8601 'start..end'"
66
+ )
67
+ end
68
+
69
+ def call(tags:, match: 'any', limit: 20, timeframe: nil)
70
+ log_info "SearchByTagsTool called: tags=#{tags.inspect}, match=#{match}, limit=#{limit}"
71
+
72
+ guarded do
73
+ raise ArgumentError, "match must be 'any' or 'all'" unless MATCHES.include?(match)
74
+
75
+ filters = HTM::SearchFilters.build(timeframe: normalized_timeframe(timeframe))
76
+ rows = session_htm.long_term_memory.search_by_tags(tags:, match: match.to_sym, limit:, filters:)
77
+ results = recall_entries(rows)
78
+
79
+ success(tags:, match:, count: results.length, results:)
80
+ end
81
+ end
82
+ end
83
+
84
+ # Tool: The tag hierarchy as text, Mermaid or SVG
85
+ class TagTreeTool < Tool
86
+ read_only!
87
+ description "Render the tag hierarchy (or the branch under a prefix) as a text tree, a Mermaid flowchart, or SVG"
88
+
89
+ # How each format draws a tag tree
90
+ RENDERERS = {
91
+ 'text' => ->(dataset, _direction) { HTM::Models::Tag.tree_string(dataset) },
92
+ 'mermaid' => ->(dataset, direction) { HTM::Models::Tag.tree_mermaid(direction:, dataset:) },
93
+ 'svg' => ->(dataset, _direction) { HTM::Models::Tag.tree_svg(dataset:) }
94
+ }.freeze
95
+ FORMATS = RENDERERS.keys.freeze
96
+ DIRECTIONS = %w[TD LR BT RL].freeze
97
+
98
+ arguments do
99
+ optional(:prefix).filled(:string).description("Only the tags under this prefix (e.g., 'database')")
100
+ optional(:format).filled(:string).description("'text' (default), 'mermaid' or 'svg'")
101
+ optional(:direction).filled(:string).description("Mermaid direction: 'TD' (default), 'LR', 'BT' or 'RL'")
102
+ end
103
+
104
+ def call(prefix: nil, format: 'text', direction: 'TD')
105
+ log_info "TagTreeTool called: prefix=#{prefix.inspect}, format=#{format}"
106
+
107
+ guarded do
108
+ raise ArgumentError, "format must be one of: #{FORMATS.join(', ')}" unless FORMATS.include?(format)
109
+ raise ArgumentError, "direction must be one of: #{DIRECTIONS.join(', ')}" unless DIRECTIONS.include?(direction)
110
+
111
+ dataset = prefix ? HTM::Models::Tag.with_prefix(prefix) : HTM::Models::Tag.dataset
112
+
113
+ success(prefix:, format:, tree: render(format, dataset, direction))
114
+ end
115
+ end
116
+
117
+ private
118
+
119
+ def render(format, dataset, direction) = RENDERERS.fetch(format).call(dataset, direction)
120
+ end
121
+
122
+ # Tag analysis tools for registration
123
+ TAG_TOOLS = [
124
+ PopularTagsTool,
125
+ TopicRelationshipsTool,
126
+ SearchByTagsTool,
127
+ TagTreeTool
128
+ ].freeze
129
+ end
130
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fast_mcp'
4
+ require_relative 'tool_support'
5
+
6
+ class HTM
7
+ module MCP
8
+ # Base class for HTM's MCP tools.
9
+ #
10
+ # FastMcp names a tool after its class (HTM::MCP::SetRobotTool becomes
11
+ # HTMMCPSetRobotTool); HTM's tools are named in snake_case without the
12
+ # Tool suffix instead (set_robot, recall, group_remember, ...).
13
+ class Tool < FastMcp::Tool
14
+ include ToolSupport
15
+
16
+ class << self
17
+ # Names each tool after its class; a tool can still call tool_name
18
+ # with a name of its own in its body
19
+ def inherited(tool)
20
+ super
21
+ class_name = tool.name
22
+ tool.tool_name(snake_name(class_name)) if class_name
23
+ end
24
+
25
+ # Marks the tool as only reading memory
26
+ def read_only! = annotations(read_only_hint: true, destructive_hint: false)
27
+
28
+ # Marks the tool as one that can remove data
29
+ def destructive! = annotations(read_only_hint: false, destructive_hint: true)
30
+
31
+ private
32
+
33
+ # HTM::MCP::SetRobotTool => set_robot
34
+ def snake_name(class_name)
35
+ class_name.split('::').last.delete_suffix('Tool').gsub(/(?<=[a-z\d])(?=[A-Z])/, '_').downcase
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'htm/node_view'
4
+
5
+ class HTM
6
+ module MCP
7
+ # Private helpers shared by the MCP tool and resource classes: session
8
+ # access, logging through the session logger and JSON responses; the
9
+ # node, recall and statistics shapes come from HTM::NodeView.
10
+ module ToolSupport
11
+ include HTM::NodeView
12
+
13
+ # The value a caller passes as confirm: to allow a permanent delete
14
+ CONFIRMATION = 'confirmed'
15
+
16
+ # Errors a tool reports as a failure response instead of raising
17
+ TOOL_ERRORS = [HTM::Error, ArgumentError, Sequel::Error, SystemCallError].freeze
18
+
19
+ private
20
+
21
+ def session_htm = Session.htm_instance
22
+
23
+ def log_info(message) = Session.logger&.info(message)
24
+
25
+ def log_warn(message) = Session.logger&.warn(message)
26
+
27
+ def log_error(message) = Session.logger&.error(message)
28
+
29
+ # JSON failure response carrying an error message
30
+ def failure(message) = { success: false, error: message }.to_json
31
+
32
+ # JSON success response
33
+ def success(**fields) = { success: true, **fields }.to_json
34
+
35
+ # Runs the block, turning an HTM, argument or database error into a
36
+ # failure response
37
+ def guarded
38
+ yield
39
+ rescue *TOOL_ERRORS => e
40
+ log_error "#{self.class.name&.split("::")&.last} error: #{e.message}"
41
+ failure(e.message)
42
+ end
43
+
44
+ # True when a destructive operation was confirmed with "confirmed"
45
+ def confirmed?(confirm) = confirm.to_s == CONFIRMATION
46
+
47
+ # The confirm: value HTM expects for a permanent delete
48
+ def htm_confirmation(confirm) = confirmed?(confirm) ? :confirmed : nil
49
+
50
+ # The entity an entity argument names
51
+ #
52
+ # @param reference [String] its name, one of its aliases, or its id
53
+ # @param type [String, nil] the entity's type, for a name several types share
54
+ # @param argument [String] the tool's argument that takes the type, for the error message
55
+ # @return [HTM::Models::Entity] the canonical entity
56
+ # @raise [HTM::NotFoundError] when memory knows no such entity
57
+ # @raise [HTM::EntityError] when no entity has the type, or the name stands for several entities
58
+ def entity_named(reference, type = nil, argument: 'type')
59
+ entity_type!(type)
60
+ one_entity(reference, type, argument)
61
+ end
62
+
63
+ # HTM::EntityLookup.find!, its error for a shared name naming the argument that settles it
64
+ def one_entity(reference, type, argument)
65
+ HTM::EntityLookup.find!(reference, type:)
66
+ rescue HTM::EntityError => e
67
+ raise HTM::EntityError, "#{e.message}#{", or pass #{argument}" unless type}"
68
+ end
69
+
70
+ # The robot_id/robot_name pair for an HTM instance
71
+ def robot_identity(htm) = { robot_id: htm.robot_id, robot_name: htm.robot_name }
72
+
73
+ # The Robot record behind an HTM instance
74
+ def robot_record(htm) = HTM::Models::Robot[htm.robot_id]
75
+
76
+ # Recall +query+ from +memory+ (an HTM or HTM::RobotGroup) as result
77
+ # entries, logging the count under +label+; keywords go to recall_options
78
+ def recall_results(memory, query, label, **)
79
+ results = recall_entries(memory.recall(query, **recall_options(**)))
80
+ log_info "#{label} complete: found #{results.length} memories"
81
+ results
82
+ end
83
+
84
+ # The named robot group, or nil
85
+ def find_group(name) = GroupSession.get_group(name)
86
+
87
+ # JSON failure response for a group missing from this session
88
+ def group_not_found(name) = failure("Group '#{name}' not found in this session")
89
+
90
+ # Yields the named group and returns the block's value, or returns the
91
+ # not-found response when the session has no such group
92
+ def with_group(name)
93
+ group = find_group(name)
94
+ group ? yield(group) : group_not_found(name)
95
+ end
96
+
97
+ # Runs the block with $stdout pointed at $stderr: MCP speaks JSON-RPC on
98
+ # STDOUT, so anything a library prints there would corrupt the protocol
99
+ def quietly
100
+ original = $stdout
101
+ $stdout = $stderr
102
+ yield
103
+ ensure
104
+ $stdout = original
105
+ end
106
+ end
107
+ end
108
+ end