返回市场
MCP红宝石服务器

MCP红宝石服务器

作者:sergiobayona11 星标更新:2025-10-31

项目介绍

VectorMCP

Gem 版本 文档 构建状态 可维护性 许可证: MIT

VectorMCP 是一个实现模型上下文协议(MCP)服务器端规范的 Ruby 宝石。它提供了一个框架,用于创建暴露工具、资源、提示和根目录给大型语言模型客户端的 MCP 服务器。

为什么选择 VectorMCP?

  • 🛡️ 安全第一:内置的输入验证和模式检查防止注入攻击
  • ⚡ 生产就绪:强大的错误处理、全面的测试套件和经过验证的可靠性
  • 🔌 多种传输方式:标准输入输出(stdio)适用于命令行工具,服务器发送事件(SSE)适用于网络应用
  • 📦 零配置:开箱即用,具有合理的默认设置
  • 🔄 完全兼容:实现了完整的 MCP 规范

快速开始

gem install vector_mcp
require 'vector_mcp'

# 创建一个服务器
server = VectorMCP.new(name: 'MyApp', version: '1.0.0')

# 添加一个工具
server.register_tool(
  name: 'greet',
  description: '向某人问好',
  input_schema: {
    type: 'object',
    properties: { name: { type: 'string' } },
    required: ['name']
  }
) { |args| "Hello, #{args['name']}!" }

# 启动服务器
server.run  # 默认使用 stdio 传输

就这样! 您的 MCP 服务器已经准备好连接到 Claude Desktop、自定义客户端或任何兼容 MCP 的应用程序。

传输选项

命令行工具(stdio)

适用于桌面应用和基于进程的集成:

server.run  # 默认:stdio 传输

网络应用(HTTP + SSE)

适用于网络应用和基于浏览器的客户端:

server.run(transport: :sse, port: 8080)

通过服务器发送事件连接至 http://localhost:8080/sse

核心特性

工具(函数)

暴露可以被大型语言模型调用的函数:

server.register_tool(
  name: 'calculate',
  description: '执行基本数学运算',
  input_schema: {
    type: 'object',
    properties: {
      operation: { type: 'string', enum: ['add', 'subtract', 'multiply'] },
      a: { type: 'number' },
      b: { type:  'number' }
    },
    required: ['operation', 'a', 'b']
  }
) do |args|
  case args['operation']
  when 'add' then args['a'] + args['b']
  when 'subtract' then args['a'] - args['b']
  when 'multiply' then args['a'] * args['b']
  end
end

资源(数据源)

提供大型语言模型可以读取的数据:

server.register_resource(
  uri: 'file://config.json',
  name: '应用配置',
  description: '当前应用设置'
) { File.read('config.json') }

提示(模板)

创建可重用的提示模板:

server.register_prompt(
  name: 'code_review',
  description: '审查代码的最佳实践',
  arguments: [
    { name: 'language', description: '编程语言', required: true },
    { name: 'code', description: '要审查的代码', required: true }
  ]
) do |args|
  {
    messages: [{
      role: 'user',
      content: {
        type: 'text',
        text: "Review this #{args['language']} code:\n\n#{args['code']}"
      }
    }]
  }
end

安全特性

VectorMCP 提供了全面的、可选的安全措施,适用于生产应用:

内置输入验证

所有输入都会自动根据您的模式进行验证:

# 这个工具受到无效输入的保护
server.register_tool(
  name: 'process_user',
  input_schema: {
    type: 'object',
    properties: {
      email: { type: 'string', format: 'email' },
      age: { type: 'integer', minimum: 0, maximum: 150 }
    },
    required: ['email']
  }
) { |args| "Processing #{args['email']}" }

# 无效输入会自动被拒绝:
# ❌ { email: "not-an-email" }     -> 验证错误
# ❌ { age: -5 }                   -> 缺少必填字段
# ✅ { email: "user@example.com" } -> 验证通过

认证与授权

使用灵活的认证策略来保护您的 MCP 服务器:

# API 密钥认证
server.enable_authentication!(
  strategy: :api_key,
  keys: ["your-secret-key", "another-key"]
)

# JWT 令牌认证
server.enable_authentication!(
  strategy: :jwt,
  secret: ENV["JWT_SECRET"]
)

# 自定义认证逻辑
server.enable_authentication!(strategy: :custom) do |request|
  api_key = request[:headers]["X-API-Key"]
  User.find_by(api_key: api_key) ? { user_id: user.id } : false
end

细粒度授权

控制对工具、资源和提示的访问:

server.enable_authorization! do
  # 工具级别的访问控制
  authorize_tools do |user, action, tool|
    case user[:role]
    when "admin" then true
    when "user" then !tool.name.start_with?("admin_")
    else false
    end
  end
  
  # 资源级别的权限
  authorize_resources do |user, action, resource|
    user[:tenant_id] == resource.tenant_id
  end
end

传输安全

安全措施无缝地应用于所有传输层:

  • Stdio:模拟头部信息以适应桌面应用
  • SSE:支持完整的 HTTP 头部和查询参数
  • 请求管道:自动认证和授权检查

👉 完整安全指南 →

我们的全面安全文档涵盖了认证策略、授权政策、会话管理以及实际案例。

实际案例

文件系统服务器

server.register_tool(
  name: 'read_file',
  description: '读取文本文件',
  input_schema: {
    type: 'object',
    properties: { path: { type: 'string' } },
    required: ['path']
  }
) { |args| File.read(args['path']) }

数据库查询工具

server.register_tool(
  name: 'search_users',
  description: '按名字搜索用户',
  input_schema: {
    type: 'object',
    properties: { 
      query: { type: 'string', minLength: 1 },
      limit: { type: 'integer', minimum: 1, maximum: 100 }
    },
    required: ['query']
  }
) do |args|
  User.where('name ILIKE ?', "%#{args['query']}%")
      .limit(args['limit'] || 10)
      .to_json
end

API 集成

server.register_tool(
  name: 'get_weather',
  description: '获取城市的当前天气',
  input_schema: {
    type: 'object',
    properties: { city: { type: 'string' } },
    required: ['city']
  }
) do |args|
  response = HTTP.get("https://api.weather.com/current", params: { city: args['city'] })
  response.parse
end

高级用法

<details> <summary><strong>文件系统根目录及安全性</strong></summary>

定义安全的文件系统边界:

# 注册允许的目录
server.register_root_from_path('./src', name: '源代码')
server.register_root_from_path('./docs', name: '文档')

# 工具可以在这些边界内安全操作
server.register_tool(
  name: 'list_files',
  input_schema: {
    type: 'object', 
    properties: { root_uri: { type: 'string' } },
    required: ['root_uri']
  }
) do |args|
  root = server.roots[args['root_uri']]
  raise '无效根目录' unless root
  Dir.entries(root.path).reject { |f| f.start_with?('.') }
end
</details> <details> <summary><strong>LLM 抽样(服务器 → 客户端)</strong></summary>

向连接的 LLM 发送请求:

server.register_tool(
  name: 'generate_summary',
  input_schema: {
    type: 'object',
    properties: { text: { type: 'string' } },
    required: ['text']
  }
) do |args, session|
  result = session.sample(
    messages: [{ 
      role: 'user', 
      content: { type: 'text', text: "Summarize: #{args['text']}" }
    }],
    max_tokens: 100
  )
  result.text_content
end
</details> <details> <summary><strong>自定义错误处理</strong></summary>

使用正确的 MCP 错误类型:

server.register_tool(name: 'risky_operation') do |args|
  if args['dangerous']
    raise VectorMCP::InvalidParamsError.new('不允许危险操作')
  end
  
  begin
    perform_operation(args)
  rescue SomeError => e
    raise VectorMCP::InternalError.new('操作失败')
  end
end
</details> <details> <summary><strong>会话信息</strong></summary>

访问客户端上下文:

server.register_tool(name: 'client_info') do |args, session|
  {
    client: session.client_info&.dig('name'),
    capabilities: session.client_capabilities,
    initialized: session.initialized?
  }
end
</details>

集成示例

Claude Desktop

添加到您的 Claude Desktop 配置中:

{
  "mcpServers": {
    "my-ruby-server": {
      "command": "ruby",
      "args": ["path/to/my_server.rb"]
    }
  }
}

网络应用

// 连接到 SSE 端点
const eventSource = new EventSource('http://localhost:8080/sse');

eventSource.addEventListener('endpoint', (event) => {
  const { uri } = JSON.parse(event.data);
  
  // 发送 MCP 请求
  fetch(uri, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 1,
      method: 'tools/call',
      params: { name: 'greet', arguments: { name: 'World' } }
    })
  });
});

为什么选择 VectorMCP?

🏆 经过实战考验:在生产应用中服务于数千次请求

⚡ 性能:优化为低延迟和高吞吐量

🛡️ 默认安全:全面的输入验证防止常见攻击

📖 文档齐全:丰富的示例和清晰的 API 文档

🔧 可扩展:易于定制和扩展以满足特定需求

🤝 社区活跃:积极开发和响应的维护者

示例与资源

安装与设置

gem install vector_mcp

# 或在您的 Gemfile 中
gem 'vector_mcp'

贡献

欢迎在 GitHub 上提交 bug 报告和拉取请求。

许可证

作为开源项目,遵循 MIT 许可证