micro_mcp 0.1.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.
data/Cargo.toml ADDED
@@ -0,0 +1,7 @@
1
+ # This Cargo.toml is here to let externals tools (IDEs, etc.) know that this is
2
+ # a Rust project. Your extensions dependencies should be added to the Cargo.toml
3
+ # in the ext/ directory.
4
+
5
+ [workspace]
6
+ members = ["./ext/micro_mcp"]
7
+ resolver = "2"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Erwin Kroon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # MicroMcp
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/micro_mcp`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ ```bash
14
+ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
15
+ ```
16
+
17
+ If bundler is not being used to manage dependencies, install the gem by executing:
18
+
19
+ ```bash
20
+ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/ekroon/micro_mcp.
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "standard/rake"
9
+
10
+ require "rb_sys/extensiontask"
11
+
12
+ task build: :compile
13
+
14
+ GEMSPEC = Gem::Specification.load("micro_mcp.gemspec")
15
+
16
+ RbSys::ExtensionTask.new("micro_mcp", GEMSPEC) do |ext|
17
+ ext.lib_dir = "lib/micro_mcp"
18
+ end
19
+
20
+ # Add Rust test task
21
+ desc "Run Rust tests"
22
+ task :test_rust do
23
+ Dir.chdir("ext/micro_mcp") do
24
+ sh "cargo test --lib"
25
+ end
26
+ end
27
+
28
+ # Add Rust lint task
29
+ desc "Run Rust linting with clippy"
30
+ task :lint_rust do
31
+ Dir.chdir("ext/micro_mcp") do
32
+ sh "cargo clippy -- -D warnings"
33
+ end
34
+ end
35
+
36
+ task default: %i[compile test test_rust lint_rust standard]
@@ -0,0 +1,21 @@
1
+ [package]
2
+ name = "micro_mcp"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+ authors = ["Erwin Kroon <123574+ekroon@users.noreply.github.com>"]
6
+ license = "MIT"
7
+ publish = false
8
+
9
+ [lib]
10
+ crate-type = ["cdylib"]
11
+
12
+ [dependencies]
13
+ async-trait = "0.1.88"
14
+ magnus = { version = "0.7", features = ["rb-sys"] }
15
+ rb-sys = { version = "*", default-features = false, features = [
16
+ "stable-api-compiled-fallback",
17
+ ] }
18
+ rust-mcp-sdk = "0.4.3"
19
+ serde = "1.0.219"
20
+ serde_json = "1.0.140"
21
+ tokio = "1.45.1"
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "mkmf"
4
+ require "rb_sys/mkmf"
5
+
6
+ create_rust_makefile("micro_mcp/micro_mcp")
@@ -0,0 +1,12 @@
1
+ mod utils;
2
+ mod server;
3
+
4
+ use magnus::{function, prelude::*, Error, Ruby};
5
+
6
+ #[magnus::init]
7
+ fn init(ruby: &Ruby) -> Result<(), Error> {
8
+ let module = ruby.define_module("MicroMcpNative")?;
9
+ module.define_singleton_method("start_server", function!(server::start_server, 0))?;
10
+ module.define_singleton_method("register_tool", function!(server::register_tool, 3))?;
11
+ Ok(())
12
+ }
@@ -0,0 +1,188 @@
1
+ use rust_mcp_sdk::{
2
+ mcp_server::{server_runtime, ServerHandler, ServerRuntime},
3
+ schema::{
4
+ schema_utils::CallToolError, CallToolRequest, CallToolResult, Implementation,
5
+ InitializeResult, ListToolsRequest, ListToolsResult, RpcError, ServerCapabilities,
6
+ ServerCapabilitiesTools, LATEST_PROTOCOL_VERSION, Tool, ToolInputSchema,
7
+ },
8
+ McpServer, StdioTransport, TransportOptions,
9
+ };
10
+ use tokio::runtime::Runtime;
11
+ use async_trait::async_trait;
12
+ use std::sync::{Mutex, OnceLock};
13
+ use std::collections::HashMap;
14
+
15
+ use magnus::{block::Proc, Error, Ruby};
16
+
17
+ use crate::utils::nogvl;
18
+
19
+ static RUNTIME: OnceLock<Runtime> = OnceLock::new();
20
+
21
+ type ToolHandler = RubyHandler;
22
+
23
+ #[derive(Clone)]
24
+ struct RubyHandler(Proc);
25
+
26
+ // SAFETY: We only call the stored Proc while holding the GVL.
27
+ unsafe impl Send for RubyHandler {}
28
+ unsafe impl Sync for RubyHandler {}
29
+
30
+ #[derive(Clone)]
31
+ struct ToolEntry {
32
+ tool: Tool,
33
+ handler: ToolHandler,
34
+ }
35
+
36
+ static TOOLS: OnceLock<Mutex<HashMap<String, ToolEntry>>> = OnceLock::new();
37
+
38
+ fn tools() -> &'static Mutex<HashMap<String, ToolEntry>> {
39
+ TOOLS.get_or_init(|| Mutex::new(HashMap::new()))
40
+ }
41
+
42
+ pub fn register_tool(_ruby: &Ruby, name: String, description: Option<String>, handler: Proc) -> Result<(), Error> {
43
+ let tool = Tool {
44
+ annotations: None,
45
+ description,
46
+ input_schema: ToolInputSchema::new(Vec::new(), None),
47
+ name: name.clone(),
48
+ };
49
+
50
+ let handler_fn = RubyHandler(handler);
51
+
52
+ let mut map = tools().lock().unwrap();
53
+ map.insert(
54
+ name,
55
+ ToolEntry {
56
+ tool,
57
+ handler: handler_fn,
58
+ },
59
+ );
60
+ Ok(())
61
+ }
62
+
63
+
64
+ pub struct MyServerHandler;
65
+
66
+ #[async_trait]
67
+ impl ServerHandler for MyServerHandler {
68
+ async fn handle_list_tools_request(
69
+ &self,
70
+ _request: ListToolsRequest,
71
+ _runtime: &dyn McpServer,
72
+ ) -> Result<ListToolsResult, RpcError> {
73
+ let tools = {
74
+ let map = tools().lock().unwrap();
75
+ map.values().map(|t| t.tool.clone()).collect()
76
+ };
77
+ Ok(ListToolsResult {
78
+ tools,
79
+ meta: None,
80
+ next_cursor: None,
81
+ })
82
+ }
83
+
84
+ async fn handle_call_tool_request(
85
+ &self,
86
+ request: CallToolRequest,
87
+ _runtime: &dyn McpServer,
88
+ ) -> Result<CallToolResult, CallToolError> {
89
+ let map = tools().lock().unwrap();
90
+ match map.get(request.tool_name()) {
91
+ Some(entry) => {
92
+ let proc = entry.handler.0;
93
+ let text_result: Result<String, Error> =
94
+ crate::utils::with_gvl(|| proc.call::<_, String>(()));
95
+ match text_result {
96
+ Ok(text) => Ok(CallToolResult::text_content(text, None)),
97
+ Err(e) => Err(CallToolError::new(std::io::Error::other(e.to_string()))),
98
+ }
99
+ }
100
+ None => Err(CallToolError::unknown_tool(request.tool_name().to_string())),
101
+ }
102
+ }
103
+ }
104
+
105
+ pub fn start_server() -> String {
106
+ let runtime = RUNTIME
107
+ .get_or_init(|| Runtime::new().expect("Failed to create Tokio runtime"));
108
+
109
+ let _ = nogvl(|| runtime.block_on(async {
110
+ let server_details = InitializeResult {
111
+ server_info: Implementation {
112
+ name: "Hello World MCP Server".to_string(),
113
+ version: "0.1.0".to_string(),
114
+ },
115
+ capabilities: ServerCapabilities {
116
+ tools: Some(ServerCapabilitiesTools { list_changed: None }),
117
+ ..Default::default()
118
+ },
119
+ meta: None,
120
+ instructions: Some("server instructions...".to_string()),
121
+ protocol_version: LATEST_PROTOCOL_VERSION.to_string(),
122
+ };
123
+
124
+ let handler = MyServerHandler {};
125
+ let transport = StdioTransport::new(TransportOptions::default())?;
126
+ let server: ServerRuntime =
127
+ server_runtime::create_server(server_details, transport, handler);
128
+
129
+ server.start().await
130
+ }));
131
+
132
+ "Ok".into()
133
+ }
134
+
135
+ #[cfg(test)]
136
+ mod tests {
137
+ use rust_mcp_sdk::{
138
+ mcp_client::client_runtime,
139
+ schema::{CallToolRequestParams, ClientCapabilities, Implementation, InitializeRequestParams, LATEST_PROTOCOL_VERSION},
140
+ McpClient, StdioTransport, TransportOptions,
141
+ };
142
+ use async_trait::async_trait;
143
+
144
+ struct TestClientHandler;
145
+ #[async_trait]
146
+ impl rust_mcp_sdk::mcp_client::ClientHandler for TestClientHandler {}
147
+
148
+ #[tokio::test]
149
+ async fn hello_world_tool_works() {
150
+ let transport = StdioTransport::create_with_server_launch(
151
+ "ruby",
152
+ vec![
153
+ "-I".into(),
154
+ "../../lib".into(),
155
+ "../../bin/mcp".into(),
156
+ "../../test/support/say_hello_tool.rb".into(),
157
+ ],
158
+ None,
159
+ TransportOptions::default(),
160
+ )
161
+ .unwrap();
162
+
163
+ let client_details = InitializeRequestParams {
164
+ capabilities: ClientCapabilities::default(),
165
+ client_info: Implementation {
166
+ name: "test-client".into(),
167
+ version: "0.1.0".into(),
168
+ },
169
+ protocol_version: LATEST_PROTOCOL_VERSION.into(),
170
+ };
171
+
172
+ let client = client_runtime::create_client(client_details, transport, TestClientHandler);
173
+
174
+ client.clone().start().await.unwrap();
175
+
176
+ let tools = client.list_tools(None).await.unwrap();
177
+ assert_eq!(tools.tools.len(), 1);
178
+ assert_eq!(tools.tools[0].name, "say_hello_world");
179
+
180
+ let result = client
181
+ .call_tool(CallToolRequestParams { name: "say_hello_world".into(), arguments: None })
182
+ .await
183
+ .unwrap();
184
+ let text = result.content[0].as_text_content().unwrap().text.clone();
185
+ assert_eq!(text, "Hello World!");
186
+ }
187
+ }
188
+
@@ -0,0 +1,52 @@
1
+ use std::{ffi::c_void, mem::MaybeUninit, ptr::null_mut};
2
+ use rb_sys::{rb_thread_call_with_gvl, rb_thread_call_without_gvl};
3
+
4
+ unsafe extern "C" fn call_without_gvl<F, R>(arg: *mut c_void) -> *mut c_void
5
+ where
6
+ F: FnMut() -> R,
7
+ R: Sized,
8
+ {
9
+ let arg = arg as *mut (&mut F, &mut MaybeUninit<R>);
10
+ let (func, result) = unsafe { &mut *arg };
11
+ result.write(func());
12
+ null_mut()
13
+ }
14
+
15
+ pub fn nogvl<F, R>(mut func: F) -> R
16
+ where
17
+ F: FnMut() -> R,
18
+ R: Sized,
19
+ {
20
+ let result = MaybeUninit::uninit();
21
+ let arg_ptr = &(&mut func, &result) as *const _ as *mut c_void;
22
+ unsafe {
23
+ rb_thread_call_without_gvl(Some(call_without_gvl::<F, R>), arg_ptr, None, null_mut());
24
+ result.assume_init()
25
+ }
26
+ }
27
+
28
+ unsafe extern "C" fn call_with_gvl<F, R>(arg: *mut c_void) -> *mut c_void
29
+ where
30
+ F: FnOnce() -> R,
31
+ R: Sized,
32
+ {
33
+ let arg = arg as *mut Option<(F, *mut MaybeUninit<R>)>;
34
+ // SAFETY: pointer is valid and owned by caller
35
+ let (func, result) = unsafe { (*arg).take().unwrap() };
36
+ unsafe { (*result).write(func()) };
37
+ null_mut()
38
+ }
39
+
40
+ pub fn with_gvl<F, R>(func: F) -> R
41
+ where
42
+ F: FnOnce() -> R,
43
+ R: Sized,
44
+ {
45
+ let mut result = MaybeUninit::uninit();
46
+ let mut data: Option<(F, *mut MaybeUninit<R>)> = Some((func, &mut result));
47
+ let arg_ptr = &mut data as *mut _ as *mut c_void;
48
+ unsafe {
49
+ rb_thread_call_with_gvl(Some(call_with_gvl::<F, R>), arg_ptr);
50
+ result.assume_init()
51
+ }
52
+ }
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MicroMcp
4
+ module Server
5
+ def self.start
6
+ thread = Thread.new do
7
+ MicroMcpNative.start_server
8
+ rescue => e
9
+ warn "Error starting server: #{e.message}"
10
+ end
11
+
12
+ begin
13
+ thread.join
14
+ rescue Interrupt
15
+ puts "\nShutting down server..."
16
+ thread.kill
17
+ end
18
+
19
+ puts "Server stopped."
20
+ Process.kill("KILL", Process.pid)
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MicroMcp
4
+ module ToolRegistry
5
+ def self.register_tool(name:, description: nil, &block)
6
+ raise ArgumentError, "block required" unless block
7
+
8
+ MicroMcpNative.register_tool(name, description, block)
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MicroMcp
4
+ VERSION = "0.1.0"
5
+ end
data/lib/micro_mcp.rb ADDED
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "micro_mcp/version"
4
+ require_relative "micro_mcp/micro_mcp"
5
+ require_relative "micro_mcp/tool_registry"
6
+ require_relative "micro_mcp/server"
7
+
8
+ module MicroMcp
9
+ class Error < StandardError; end
10
+ # Your code goes here...
11
+
12
+ def self.start_server
13
+ Server.start
14
+ end
15
+ end
data/sig/micro_mcp.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module MicroMcp
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,79 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: micro_mcp
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Erwin Kroon
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rb_sys
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: 0.9.91
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: 0.9.91
26
+ description: ''
27
+ email:
28
+ - 123574+ekroon@users.noreply.github.com
29
+ executables: []
30
+ extensions:
31
+ - ext/micro_mcp/extconf.rb
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".devcontainer/devcontainer.json"
35
+ - ".standard.yml"
36
+ - ".vscode/mcp.json"
37
+ - AGENTS.md
38
+ - CHANGELOG.md
39
+ - Cargo.lock
40
+ - Cargo.toml
41
+ - LICENSE.txt
42
+ - README.md
43
+ - Rakefile
44
+ - ext/micro_mcp/Cargo.toml
45
+ - ext/micro_mcp/extconf.rb
46
+ - ext/micro_mcp/src/lib.rs
47
+ - ext/micro_mcp/src/server.rs
48
+ - ext/micro_mcp/src/utils.rs
49
+ - lib/micro_mcp.rb
50
+ - lib/micro_mcp/server.rb
51
+ - lib/micro_mcp/tool_registry.rb
52
+ - lib/micro_mcp/version.rb
53
+ - sig/micro_mcp.rbs
54
+ homepage: https://github.com/ekroon/micro_mcp
55
+ licenses:
56
+ - MIT
57
+ metadata:
58
+ allowed_push_host: https://rubygems.org
59
+ homepage_uri: https://github.com/ekroon/micro_mcp
60
+ source_code_uri: https://github.com/ekroon/micro_mcp
61
+ changelog_uri: https://github.com/ekroon/micro_mcp/blob/main/CHANGELOG.md
62
+ rdoc_options: []
63
+ require_paths:
64
+ - lib
65
+ required_ruby_version: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: 3.1.0
70
+ required_rubygems_version: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: 3.3.11
75
+ requirements: []
76
+ rubygems_version: 3.6.7
77
+ specification_version: 4
78
+ summary: Simple gem for quick MCP server creation
79
+ test_files: []