语义工具匹配服务器

Legion-MCP是一个模型上下文协议服务器,提供语义工具匹配、观察管道、上下文编译、分层行为智能、工具治理和远程服务器联邦等功能。

  • by LegionIO
  • Ruby
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 LegionIO/legion-mcp

使用说明

军团mcp

LegionIO框架的模型上下文协议(MCP)服务器。提供语义工具匹配、观察管道、上下文编译、分层行为智能(第0/1/2层路由)、工具治理、延迟工具加载和远程服务器联盟的MCP客户端池。

版本: 0.9.1 许可证阿帕奇-2.0 红宝石: >= 3.4

提取自 军团 用于独立的版本控制和重用。

安装

gem 'legion-mcp'

或者在Gemfile中:

gem 'legion-mcp', '~> 0.9'

建筑

Legion::MCP
├── Server              # MCP::Server builder, governance-aware build; tool list sourced via DeferredRegistry
├── Auth                # JWT + API key authentication
├── Utils               # Pure-function summarization and formatting helpers
├── ToolGovernance      # Risk-tier tool filtering + invocation audit
├── ToolAdapter         # Adapts Legion::Tools::Base to MCP SDK format; handles :mcp_remote dispatch
├── DeferredRegistry    # Reads deferred/always-loaded tools from Settings::Extensions at request time
├── ContextCompiler     # Keyword + semantic tool matching (60/40 blend), 17 categories
├── EmbeddingIndex      # In-memory vector cache for semantic matching
├── Observer            # Instrumentation: counters, ring buffer, intent tracking, pattern promotion
├── UsageFilter         # Frequency/recency/keyword scoring for dynamic tool filtering
├── DynamicInjector     # Context-aware tool injection/removal with tools/list_changed notification
├── CatalogDispatcher   # Dispatch layer routing MCP calls through Legion::Ingress
├── Patterns::Store     # 3-layer degrading storage (L0 memory -> L1 cache -> L2 SQLite)
├── Patterns::Schema    # Portable pattern format with trust-level confidence capping
├── Patterns::Exchange  # Bulk import/export of patterns via JSON files
├── Patterns::Gossip    # AMQP-based pattern sharing between instances
├── Patterns::Compiler  # Compressed tool definitions and compiled workflows
├── TierRouter          # Confidence-gated tier selection (0/1/2)
├── ContextGuard        # Staleness, rapid-fire, anomaly detection guards
├── StateTracker        # In-memory state snapshots with delta diff computation
├── StructuralIndex     # Precomputed index of extensions, runners, actors, and tools
├── ToolQuality         # Docstring quality audit, category resolution, capability matrix
├── GapDetector         # Unmatched intents, high-failure tools, stale candidate detection
├── SelfGenerate        # Gap detection + publication cycles with cooldown
├── OverrideBroadcast   # Mesh-wide override confirmation via RabbitMQ
├── TracingContext       # Thread-local conversation/request/exchange/trace ID propagation
├── Client::Pool        # Remote MCP server connections; registers tools into Settings::Extensions
├── Client::Connection  # stdio and HTTP transport connections with TTL-cached tool lists
├── Client::ServerRegistry # Static and dynamic server registration with health tracking
├── Tools/              # 10 MCP-specific + 18 legion-data CRUD tools; extension tools via Settings::Extensions
└── Resources/          # RunnerCatalog, ExtensionInfo

工具注册表

  • MCP特定工具 (10个工具): do_action, discover_tools, plan_action, structural_index, tool_audit, state_diff, search_sessions, skill_list, skill_describe, skill_invoke, skill_cancel
  • 军团数据CRUD (18个工具): run_task, describe_runner,列出/获取/删除任务, get_task_logsCRUD链/关系/时间表
  • 扩展工具:通过自动发现 Legion::Settings::Extensions 在运行时;未作为静态文件发货
  • 远程MCP工具:通过从远程服务器获取 Client::Pool.all_tools,注册到 Settings::Extensions 和 dispatch_type: :mcp_remote

分层行为智能

请求流经三个层,每个层的延迟和能力都在增加:

级别 信心 发生了什么 延迟
0 >=0.8 缓存模式匹配,无LLM <5ms
1 0.6-0.8 本地/车队型号提示 ~100ms
2 <0.6 全云LLM ~1-3s

模式生命周期

  1. 观察者 记录MCP工具调用中的意图+工具对
  2. 在3次成功观察后,提拔候选人 Pattern商店 (种子置信度0.5)
  3. 成功执行会增加信心(+0.02),失败会降低信心(-0.05)
  4. 一旦置信度达到0.8, TierRouter 服务于第0层的模式

上下文保护程序

在提供Tier 0响应之前, ContextGuard 检查:

  • 陈旧:模式在>1小时内未命中
  • 速射的:10分钟内有>5个请求(可能循环)
  • 异常:2次以上连续失误(模式可能已过时)

如果任何警卫触发,请求将升级到第1级。

存储层

PatternStore在3层中优雅地降级:

层 后端 要求
L0 内存哈希 始终可用
L1 军团::缓存(memcached/redis) defined?(Legion::Cache)
L2 军团::数据::本地(SQLite) defined?(Legion::Data::Local)

所有的坚持都包含在内 begin/rescue => nil --失败的写入永远不会阻止第0层。

工具

28个内置MCP工具 legion.* 命名空间(10个MCP特定+18个军团数据CRUD)。扩展拥有的工具在运行时通过以下方式自动发现 Legion::Settings::Extensions.

工具 目的
legion.do 自然语言意图路由(0级快速路径)
legion.tools 按类别、意图或模式解析进行动态工具发现
legion.plan 带LLM叙事的多步骤工作流程规划
legion.structural_index 预计算的扩展/运行器/执行器/工具的结构索引
legion.tool_audit 注册工具的质量审核(摘要/矩阵/问题)
legion.state_diff 自给定时间戳以来的德尔塔州轮询
legion.search_sessions 按关键字搜索过去的对话会话
legion.skill.list 列出所有已注册的法学硕士技能
legion.skill.describe 描述一项特定技能
legion.skill.invoke 调用对话技能
legion.skill.cancel 取消当前技能运行
legion.run_task 通过点符号执行runner函数
legion.describe_runner 运行程序/功能发现
legion.list_tasks / get_task / delete_task / get_task_logs 任务CRUD+日志
legion.list_chains / create_chain / update_chain / delete_chain 连锁经营
legion.list_relationships / create_* / update_* / delete_* 关系CRUD
legion.list_schedules / create_* / update_* / delete_* 计划CRUD

资源

URI 描述
legion://runners 所有已注册的extension.runner.function路径
legion://extensions/{name} 扩展详细信息模板

MCP客户端(联邦)

通过stdio或HTTP传输连接到远程MCP服务器:

# Via settings (loaded at boot)
# settings/mcp.json:
# { "mcp": { "servers": { "code_server": { "transport": "stdio", "command": "npx @example/mcp-server" } } } }

Legion::MCP::Client.boot

# Or register at runtime
Legion::MCP::Client.register(:my_server, transport: :http, url: 'http://localhost:9393/mcp')

# All remote tools are registered into Settings::Extensions with dispatch_type: :mcp_remote
tools = Legion::MCP::Client::Pool.all_tools

用法

独立MCP服务器

require 'legion/mcp'

server = Legion::MCP.server
server.start

军团内部

# stdio transport (default)
legionio mcp stdio

# HTTP transport
legionio mcp http --port 9393

0级直接使用

result = Legion::MCP::TierRouter.route(
  intent: "list all running tasks",
  params: { status: "running" },
  context: {}
)

case result[:tier]
when 0 then puts "Cached: #{result[:response]}"
when 1 then puts "Escalate to local model"
when 2 then puts "Escalate to cloud LLM"
end

身份范围服务器

server = Legion::MCP.server_for(token: jwt_token)
# Returns governance-filtered tool set based on JWT claims

配置

所有配置都是可选的,可以通过读取 Legion::Settings 如果可用:

{
  "mcp": {
    "auth": {
      "enabled": false,
      "require_auth": false,
      "jwt_secret": null,
      "jwt_algorithm": "HS256",
      "jwt_issuer": "legion",
      "allowed_api_keys": []
    },
    "governance": {
      "enabled": false,
      "audit_invocations": true,
      "tool_risk_tiers": {}
    },
    "deferred_loading": {
      "enabled": true,
      "always_loaded": []
    },
    "dynamic_tools": {
      "enabled": false,
      "max_injected": 10
    },
    "tier0": {
      "guards": {
        "max_stale_seconds": 3600,
        "rapid_fire_threshold": 5,
        "rapid_fire_window_seconds": 600
      }
    },
    "auto_expose_runners": false,
    "servers": {},
    "cold_start": {
      "patterns_path": null
    },
    "roles": {}
  }
}

依赖项

宝石 必需 用途
mcp (~>0.8) 是 MCP服务器SDK
legion-data (>=1.4) 是 后续模型,迁移
legion-json (>=1.2) 是 JSON序列化
legion-logging (>=1.4.3) 是 通过助手进行结构化日志记录
legion-settings (>=1.4.0) 是 配置+设置::扩展
legion-cache 可选 L1模式缓存(memcached/redis)
legion-llm 可选 语义匹配嵌入,第1/2层LLM

防范策略

所有可选依赖项都使用 defined?() 警卫:

  • defined?(Legion::Cache) 用于L1缓存操作
  • defined?(Legion::Data::Local) 用于L2 SQLite持久化
  • defined?(Legion::LLM) 用于嵌入生成和分层LLM路由
  • defined?(Legion::Settings::Extensions) 用于中央工具注册表
  • defined?(Legion::MCP::EmbeddingIndex) 用于语义匹配
  • defined?(Legion::MCP::TierRouter) 对于第0层路由

每次存储写入都会被封装 begin/rescue => nil --失败的持久性永远不会阻止第0层。

关键约定

  • Legion::JSON.load 回报 符号键 --使用 body[:data],不 body['data']
  • Legion::JSON.dump 只取1个位置arg——显式包装kwargs {}
  • ::Process 和 ::JSON 必须在内部明确 Legion:: 命名空间
  • Legion::MCP.server 是一个记忆的单例调用 Legion::MCP.reset! 在测试中
  • MCP工具命名: legion.snake_case_name (点名称空间)
  • 每个救援区都在呼叫 handle_exception(e, level:, handled:, operation:)
  • 通过登录 extend Legion::Logging::Helper (模块)或 include Legion::Logging::Helper (班级/班级<<自我)

发展

bundle install
bundle exec rspec       # 0 failures
bundle exec rubocop -A  # auto-fix
bundle exec rubocop     # lint check

文件映射

路径 目的
lib/legion/mcp.rb 入口点: Legion::MCP.server 单体工厂
lib/legion/mcp/version.rb Legion::MCP::VERSION 常数
lib/legion/mcp/utils.rb 纯函数摘要和格式化助手
lib/legion/mcp/server.rb MCP:服务器构建器,具有治理意识的构建;从设置中读取工具::扩展
lib/legion/mcp/auth.rb JWT+neneneba API密钥认证
lib/legion/mcp/patterns.rb 13个Tier 0模式布线模块的桶形文件
lib/legion/mcp/discovery.rb 12个工具发现和自适应模块的桶文件
lib/legion/mcp/tool_adapter.rb MCP:ToolAdapter——封装MCP SDK的工具;句柄:mcp_远程调度
lib/legion/mcp/deferred_registry.rb 延迟/始终加载的工具列表管理
lib/legion/mcp/catalog_dispatcher.rb 通过Legion::Ingress进行调度层路由
lib/legion/mcp/dynamic_injector.rb 上下文感知工具注入/移除
lib/legion/mcp/client.rb 客户端启动/关闭、服务器注册
lib/legion/mcp/client/pool.rb 连接池;all_tools注册到设置::扩展中
lib/legion/mcp/client/connection.rb stdio/HTTP传输连接
lib/legion/mcp/client/server_registry.rb 服务器健康跟踪和注册
lib/legion/mcp/tools/do_action.rb 具有0级快速路径的自然语言意图路由
lib/legion/mcp/tools/discover_tools.rb 基于上下文的动态工具发现
lib/legion/mcp/tools/run_task.rb 通过点符号执行runner函数
lib/legion/mcp/tools/plan_action.rb 具有行动分解的代理规划
lib/legion/mcp/tools/skills.rb 技能列表/描述/调用/取消工具
lib/legion/mcp/tools/structural_index.rb 查询预先计算的结构索引
lib/legion/mcp/tools/tool_audit.rb 审核注册工具质量
lib/legion/mcp/tools/state_diff.rb 自时间戳以来更改了系统状态
lib/legion/mcp/tools/search_sessions.rb 搜索过去的对话会话
lib/legion/mcp/resources/runner_catalog.rb legion://runners 资源
lib/legion/mcp/resources/extension_info.rb legion://extensions/{name} 资源模板

许可证

阿帕奇-2.0