Skip to content

Commit 1a505dd

Browse files
committed
Nicer returns
1 parent b1ec42c commit 1a505dd

3 files changed

Lines changed: 61 additions & 1 deletion

File tree

lib/tool_forge.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# frozen_string_literal: true
22

3+
require 'json'
34
require 'zeitwerk'
45

56
loader = Zeitwerk::Loader.for_gem(warn_on_extra_files: false)

lib/tool_forge/tool_definition.rb

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,18 @@ def to_mcp_tool
8484

8585
define_singleton_method(:call) do |server_context:, **args|
8686
result = definition.execute_block.call(**args)
87-
MCP::Tool::Response.new([{ type: 'text', text: result.to_s }])
87+
88+
# Smart formatting for different return types
89+
result_text = case result
90+
when String
91+
result
92+
when Hash, Array
93+
JSON.pretty_generate(result)
94+
else
95+
result.to_s
96+
end
97+
98+
MCP::Tool::Response.new([{ type: 'text', text: result_text }])
8899
end
89100
end
90101
end

spec/tool_forge/tool_definition_to_mcp_spec.rb

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,4 +134,52 @@
134134
expect(schema[:properties]['arr'][:type]).to eq('array')
135135
expect(schema[:properties]['obj'][:type]).to eq('object')
136136
end
137+
138+
describe 'return value formatting' do
139+
it 'returns strings as-is' do
140+
tool = described_class.new(:string_tool) do
141+
description 'Returns a string'
142+
execute { 'Hello, World!' }
143+
end
144+
145+
tool_class = tool.to_mcp_tool
146+
result = tool_class.call(server_context: nil)
147+
expect(result.content.first[:text]).to eq('Hello, World!')
148+
end
149+
150+
it 'formats hashes as pretty JSON' do
151+
tool = described_class.new(:hash_tool) do
152+
description 'Returns a hash'
153+
execute { { name: 'Alice', age: 30 } }
154+
end
155+
156+
tool_class = tool.to_mcp_tool
157+
result = tool_class.call(server_context: nil)
158+
parsed = JSON.parse(result.content.first[:text])
159+
expect(parsed).to eq('name' => 'Alice', 'age' => 30)
160+
end
161+
162+
it 'formats arrays as pretty JSON' do
163+
tool = described_class.new(:array_tool) do
164+
description 'Returns an array'
165+
execute { [1, 2, 3, 4, 5] }
166+
end
167+
168+
tool_class = tool.to_mcp_tool
169+
result = tool_class.call(server_context: nil)
170+
parsed = JSON.parse(result.content.first[:text])
171+
expect(parsed).to eq([1, 2, 3, 4, 5])
172+
end
173+
174+
it 'converts other objects to strings' do
175+
tool = described_class.new(:number_tool) do
176+
description 'Returns a number'
177+
execute { 42 }
178+
end
179+
180+
tool_class = tool.to_mcp_tool
181+
result = tool_class.call(server_context: nil)
182+
expect(result.content.first[:text]).to eq('42')
183+
end
184+
end
137185
end

0 commit comments

Comments
 (0)