Логотип VectorMCP

VectorMCP

Сообщество
sergiobayona

A server implementation for the Model Context Protocol (MCP) in Ruby.

Издательsergiobayona
Репозиторийvector_mcp
ЯзыкRuby
Форки
3
Звёзды
13
Доступные инструменты
0
Тип транспортаstdio
Категории
ЛицензияMIT
Ссылки
  • Подключайте инструменты к рабочим процессам с ИИ

    VectorMCP предоставляет возможности MCP, доступные совместимым ИИ-клиентам и агентам.

  • Доступные инструменты: 0

    Ниже представлены доступные для вызова действия с названиями и описаниями, если сервер их предоставляет.

  • Готовая конфигурация для копирования

    Используйте примеры конфигурации, чтобы настроить этот сервер в предпочитаемом MCP-клиенте.

  • Показатели интереса к открытому проекту

    Звёзды: 13, форки: 3 — в связанном репозитории.

VectorMCP

Gem Version Docs Build Status Maintainability License: MIT

VectorMCP is a Ruby implementation of the Model Context Protocol (MCP) server-side specification. It gives you a framework for exposing tools, resources, prompts, roots, sampling, middleware, and security over the MCP streamable HTTP transport.

Highlights

  • Streamable HTTP is the built-in transport, with session management, resumability, and MCP 2025-11-25 compliance
  • Class-based tools via VectorMCP::Tool, plus the original block-based register_tool API
  • Rack and Rails mounting through server.rack_app
  • Opt-in authentication and authorization, structured logging, and middleware hooks
  • Request-scoped identity: every request is dispatched through its own invocation, so concurrent requests on one session can never observe each other's headers or auth
  • Image-aware tools/resources/prompts, roots, and server-initiated sampling
  • Token-based field anonymization middleware to keep sensitive values out of LLM context

Requirements

  • Ruby 3.2+

Installation

bash
gem install vector_mcp
ruby
gem "vector_mcp"

Quick Start

ruby
require "vector_mcp"

class Greet < VectorMCP::Tool
  description "Say hello to someone"
  param :name, type: :string, desc: "Name to greet", required: true

  def call(args, _session)
    "Hello, #{args["name"]}!"
  end
end

server = VectorMCP::Server.new(name: "MyApp", version: "1.0.0")
server.register(Greet)
server.run(port: 8080)

The class-based DSL is optional. The existing block-based API still works:

ruby
server.register_tool(
  name: "echo",
  description: "Echo back the supplied text",
  input_schema: {
    type: "object",
    properties: { text: { type: "string" } },
    required: ["text"]
  }
) { |args| args["text"] }

Rack and Rails

VectorMCP can run as a standalone HTTP server or be mounted inside an existing Rack app:

ruby
require "vector_mcp"

server = VectorMCP::Server.new(name: "MyApp", version: "1.0.0")
server.register(Greet)

MCP_APP = server.rack_app

In Rails, mount it in config/routes.rb:

ruby
mount MCP_APP => "/mcp"

For ActiveRecord-backed tools, opt into VectorMCP::Rails::Tool:

ruby
require "vector_mcp/rails/tool"

class FindUser < VectorMCP::Rails::Tool
  description "Find a user by id"
  param :id, type: :integer, required: true

  def call(args, _session)
    user = find!(User, args[:id])
    { id: user.id, email: user.email }
  end
end

See docs/rails-setup-guide.md for a full setup guide.

Tools, Resources, and Prompts

Expose callable tools:

ruby
server.register_tool(
  name: "calculate",
  description: "Performs basic math",
  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

Expose readable resources:

ruby
server.register_resource(
  uri: "file://config.json",
  name: "App Configuration",
  description: "Current application settings"
) { File.read("config.json") }

Define prompt templates:

ruby
server.register_prompt(
  name: "code_review",
  description: "Reviews code for best practices",
  arguments: [
    { name: "language", description: "Programming language", required: true },
    { name: "code", description: "Code to review", required: true }
  ]
) do |args|
  {
    messages: [{
      role: "user",
      content: {
        type: "text",
        text: "Review this #{args["language"]} code:\n\n#{args["code"]}"
      }
    }]
  }
end

VectorMCP::Tool also supports type: :date and type: :datetime, which are validated as strings in JSON Schema and coerced to Date and Time before #call runs.

Handlers that take a second argument receive the per-request invocation, which exposes session identity, the request's headers/params, and the authenticated user in one place:

ruby
server.register_tool(
  name: "whoami",
  description: "Reports the caller's identity",
  input_schema: { type: "object", properties: {} }
) do |_args, invocation|
  {
    session: invocation.id,
    user: invocation.user,
    api_key_header: invocation.request_header("X-API-Key")
  }
end

Resource handlers get the same invocation as their second argument (it also answers the familiar user / authenticated? / can? queries, so handlers written against the older security-context argument keep working unchanged).

Security and Middleware

VectorMCP keeps security opt-in, but the primitives are built in:

ruby
server.enable_authentication!(
  strategy: :api_key,
  keys: [ENV.fetch("MCP_API_KEY")],
  rate_limit: { max_attempts: 10, window_seconds: 60 }
)

server.enable_authorization! do
  authorize_tools do |user, _action, tool|
    user[:role] == "admin" || !tool.name.start_with?("admin_")
  end
end

Custom authentication works too:

ruby
server.enable_authentication!(strategy: :custom) do |request|
  api_key = request[:headers]["X-API-Key"]
  user = User.find_by(api_key: api_key)
  user ? { user_id: user.id, role: user.role } : false
end

When authentication is enabled, VectorMCP applies it centrally to built-in and custom request/notification handlers. Only initialize, ping, and the initialized notification are public; HTTP GET streams and DELETE session requests also require credentials.

For public deployments, enable authentication failure limiting with rate_limit: true (10 attempts per 60 seconds by default), or provide max_attempts, window_seconds, and max_entries. Repeated failures are tracked by client IP and a one-way credential fingerprint; blocked requests return HTTP 429, JSON-RPC -32029, and Retry-After. The limiter is in-process, so multi-process or distributed deployments should also enforce a shared limit at the proxy or gateway. Generate API keys with at least 256 bits of entropy—for example, ruby -rsecurerandom -e 'puts SecureRandom.hex(32)'—and load them from a secret manager or environment variable.

For MCP clients that speak OAuth 2.1 (e.g. Claude Desktop), pass a resource_metadata_url: to turn on RFC 9728 discovery. Unauthenticated requests to /mcp return 401 with a WWW-Authenticate header pointing at the configured metadata document, and the client drives the rest of the OAuth dance automatically. See docs/oauth_resource_server.md for the feature reference and docs/rails_oauth_integration.md for a full Rails + Doorkeeper recipe.

Middleware can hook into tool, resource, prompt, sampling, auth, and transport events, including before_auth, after_auth, on_auth_error, before_request, after_response, and on_transport_error.

See security/README.md for the full security guide.

Field Anonymization

Keep sensitive string values out of the LLM context by substituting them with stable opaque tokens. Values are tokenized on outbound tool results and restored on inbound tool arguments, so the LLM sees only tokens while your handlers receive the original data.

ruby
anonymizer = VectorMCP::Middleware::Anonymizer.new(
  store: VectorMCP::TokenStore.new,
  field_rules: [
    { pattern: /email/i, prefix: "EMAIL" },
    { pattern: /\bssn\b/i, prefix: "SSN" }
  ]
)
anonymizer.install_on(server)

Transport Notes

  • VectorMCP ships with streamable HTTP as its built-in transport
  • POST /mcp accepts a single JSON-RPC request, notification, or response; batch arrays are rejected
  • GET /mcp opens an SSE stream for server-initiated messages
  • DELETE /mcp terminates the session
  • The server advertises MCP protocol 2025-11-25 and accepts 2025-03-26 and 2024-11-05 headers for compatibility
  • Default allowed origins are restricted to localhost and loopback addresses
  • POST bodies are capped at 16 MiB by default; configure max_body_bytes: on run or rack_app when needed
  • For mounted Rack apps, configure the same limit in the fronting web server or reverse proxy so requests are rejected before Rack buffering

Initialize a session with curl:

bash
curl -X POST http://localhost:8080/mcp \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"curl","version":"1.0"}}}'

More Features

  • Roots via register_root and register_root_from_path
  • Image resources and image-aware tools/prompts
  • Structured logging with component loggers
  • Server-initiated sampling with streaming/tool-call support
  • Middleware-driven request shaping and observability

Documentation

Contributing

Bug reports and pull requests are welcome on GitHub.

License

Available as open source under the MIT License.

Установка

TypingMind
Требования:

Node.js 18+

{
  "mcpServers": {
    "sergiobayona-vector_mcp": {
      "command": "",
      "args": []
    }
  }
}

Используйте MCP VectorMCP с разными ИИ-моделями

TypingMind подключает инструменты MCP на уровне рабочего пространства, поэтому после подключения VectorMCP вы можете использовать их с разными моделями ИИ в TypingMind, не настраивая подключение отдельно для каждой модели. Эта интеграция MCP работает локально на вашем устройстве через коннектор MCP TypingMind.

Руководство по настройке локального коннектора

Выберите этот способ, если серверу MCP нужен доступ к локальным файлам, приложениям или закрытым ресурсам на вашем компьютере.

1

Откройте настройки MCP

В TypingMind откройте «Настройки», затем «Расширенные настройки», перейдите в раздел «Протокол контекста модели» и выберите «Настроить коннектор».

  1. Откройте TypingMind в браузере.
  2. Нажмите значок настроек.
  3. Перейдите в «Расширенные настройки».
  4. Откройте раздел «Протокол контекста модели».
  5. Нажмите «Настроить коннектор» и выберите «Это устройство».
Экран настройки коннектора MCP в TypingMind с выбранным вариантом «Это устройство»
2

Выполните команду коннектора

Выберите «Это устройство», скопируйте команду из TypingMind и выполните её в терминале. Не останавливайте процесс, пока используете MCP.

  1. Скопируйте команду настройки, показанную в TypingMind.
  2. Откройте «Терминал» в macOS или Windows Terminal в Windows.
  3. Вставьте и выполните команду.
  4. Подтвердите установку пакета, если терминал запросит разрешение продолжить.
  5. Не закрывайте окно терминала и не останавливайте процесс, пока используете инструменты MCP.
3

Добавьте VectorMCP как сервер

Когда статус коннектора сменится на «Готов», нажмите «Изменить серверы» и вставьте конфигурацию сервера MCP.

  1. Дождитесь, пока статус коннектора сменится на «Готов».
  2. Нажмите «Изменить серверы».
  3. Вставьте конфигурацию сервера MCP для VectorMCP.
  4. Сохраните список серверов.
  5. Обновите статус, если хотите убедиться, что коннектор по-прежнему готов к работе.
Настройки MCP в TypingMind с активным сервером и кнопкой «Изменить серверы»
{
  "mcpServers": {
    "sergiobayona-vector_mcp": {
      "command": "npx",
      "args": [
        "-y",
        "vector_mcp"
      ]
    }
  }
}
4

Используйте подключение с разными моделями

Сохраните список серверов, откройте раздел «Плагины», включите инструменты MCP для VectorMCP, затем выберите любую поддерживаемую модель ИИ в TypingMind и используйте инструменты в чате или назначьте их ИИ-агенту.

  1. Откройте страницу «Плагины» в TypingMind.
  2. Включите инструменты MCP для VectorMCP.
  3. Начните чат и выберите модель ИИ, которую хотите использовать.
  4. Используйте инструменты MCP в чате или назначьте их ИИ-агенту.
  5. При необходимости переключайтесь на другую модель ИИ без повторного подключения MCP.
Чат TypingMind с включёнными инструментами MCP и выбранной ИИ-моделью
Можете помочь мне с этой задачей с помощью VectorMCP?
VectorMCP
Конечно. Я всё прочитал.
Вот что я нашёл с помощью VectorMCP.

Часто задаваемые вопросы

Для чего используется сервер MCP VectorMCP?

VectorMCP — это сервер MCP, который позволяет совместимым ИИ-клиентам подключаться к внешним инструментам и получать контекст. В TypingMind достаточно один раз добавить этот сервер MCP, чтобы его инструменты стали доступны в вашем рабочем пространстве с ИИ.

Можно ли использовать сервер MCP VectorMCP с несколькими ИИ-моделями в TypingMind?

Да. TypingMind подключает инструменты MCP на уровне рабочего пространства, поэтому вы можете использовать VectorMCP с разными ИИ-моделями, например Claude, ChatGPT, Gemini или другими моделями, настроенными в TypingMind, без отдельной настройки сервера MCP для каждой модели.

Зачем использовать MCP VectorMCP с TypingMind?

TypingMind — один из лучших интерфейсов для чата с LLM: он объединяет разные ИИ-модели, промпты, плагины, ИИ-агентов, ключи API и инструменты MCP в одном рабочем пространстве. Подключив VectorMCP, вы сможете использовать его инструменты MCP с предпочитаемыми моделями, сохраняя удобную организацию работы с чатами в TypingMind.

Как подключить сервер MCP VectorMCP к TypingMind?

VectorMCP работает через локальный коннектор MCP TypingMind. Этот вариант лучше всего подходит, когда серверу MCP нужен доступ к локальным файлам, настольным приложениям, инструментам командной строки или закрытым ресурсам на вашем компьютере.

Какие инструменты предоставляет сервер MCP VectorMCP в TypingMind?

VectorMCP предоставляет возможности MCP, которые можно включить на странице «Плагины» в TypingMind и использовать в чате или назначить ИИ-агентам.

Нужно ли передавать TypingMind свои ключи API для использования сервера MCP VectorMCP?

Нет. TypingMind ориентирован прежде всего на локальную работу и позволяет вам контролировать выбор провайдеров моделей, ключи API, промпты и конфигурацию MCP. Если VectorMCP требует аутентификации, при создании подключения добавьте необходимые заголовки, настройки OAuth или локальную конфигурацию для этого сервера MCP.

Похожие серверы MCP

Все

Создайте свою рабочую ИИ-среду сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇