Class: Parse::Agent::MCPServer
- Inherits:
-
Object
- Object
- Parse::Agent::MCPServer
- Defined in:
- lib/parse/agent/mcp_server.rb
Overview
MCP (Model Context Protocol) HTTP Server for Parse Stack. Enables external AI agents (Claude, LM Studio, etc.) to interact with Parse data over HTTP using the MCP protocol specification.
Since the Rack refactor this class is a thin WEBrick wrapper around MCPRackApp. Embedded deployments (Sinatra, Rails) should mount MCPRackApp directly with their own agent factory; this class remains for standalone server deployments and back-compat.
Constant Summary collapse
- PROTOCOL_VERSION =
MCP Protocol version
MCPDispatcher::PROTOCOL_VERSION
- CAPABILITIES =
Server capabilities
MCPDispatcher::CAPABILITIES
- MAX_BODY_SIZE =
Maximum allowed request body size (1 MB) — kept as a back-compat constant.
MCPRackApp::DEFAULT_MAX_BODY_SIZE
- MAX_JSON_NESTING =
Maximum JSON nesting depth — kept as a back-compat constant.
MCPRackApp::MAX_JSON_NESTING
- MCP_API_KEY_HEADER =
HTTP header for MCP API key authentication
"X-MCP-API-Key"- LOOPBACK_HOSTS =
Create a new MCP server instance
Loopback hosts that are safe to bind to without an API key.
%w[127.0.0.1 ::1 localhost].freeze
- MIN_PUBLIC_API_KEY_LENGTH =
Shortest API key accepted for a non-loopback bind.
16
Class Attribute Summary collapse
-
.default_port ⇒ Object
Returns the value of attribute default_port.
Instance Attribute Summary collapse
-
#agent ⇒ Parse::Agent
readonly
The template agent used by the /tools listing endpoint and as a settings source for per-request agents.
-
#host ⇒ String
readonly
The host to bind to.
-
#port ⇒ Integer
readonly
The port number.
Class Method Summary collapse
- .normalize_api_key(key) ⇒ Object
-
.require_webrick! ⇒ true
Load WEBrick for the standalone server, raising a LoadError that explains the fix when the application does not bundle it.
-
.run(port: nil, permissions: :readonly, session_token: nil, host: "127.0.0.1", api_key: nil, rate_limiter: nil, allowed_hosts: nil) ⇒ Object
Start the MCP server (blocking).
-
.strip_unicode_space(str) ⇒ String?
The API key to enforce, or nil when none is configured.
Instance Method Summary collapse
-
#initialize(port: 3001, host: "127.0.0.1", permissions: :readonly, session_token: nil, api_key: nil, rate_limiter: nil, pre_auth_rate_limiter: nil, allowed_origins: nil, require_custom_header: nil, allowed_hosts: nil) ⇒ MCPServer
constructor
A new instance of MCPServer.
-
#start ⇒ Object
Start the HTTP server (blocking).
-
#stop ⇒ Object
Stop the server.
Constructor Details
#initialize(port: 3001, host: "127.0.0.1", permissions: :readonly, session_token: nil, api_key: nil, rate_limiter: nil, pre_auth_rate_limiter: nil, allowed_origins: nil, require_custom_header: nil, allowed_hosts: nil) ⇒ MCPServer
Returns a new instance of MCPServer.
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 |
# File 'lib/parse/agent/mcp_server.rb', line 161 def initialize(port: 3001, host: "127.0.0.1", permissions: :readonly, session_token: nil, api_key: nil, rate_limiter: nil, pre_auth_rate_limiter: nil, allowed_origins: nil, require_custom_header: nil, allowed_hosts: nil) if rate_limiter && !rate_limiter.respond_to?(:check!) raise ArgumentError, "rate_limiter must respond to #check!" end if pre_auth_rate_limiter && !pre_auth_rate_limiter.respond_to?(:check!) raise ArgumentError, "pre_auth_rate_limiter must respond to #check!" end # One normalization for every check below: surrounding whitespace is # stripped and a key that is empty after stripping counts as no key. # A whitespace-only key used to pass the non-loopback bind check # (`" ".to_s.empty?` is false) and then disable request auth # (`" ".present?` is false), leaving a public endpoint open. # An explicit blank `api_key:` does not hide a configured # MCP_API_KEY. effective_api_key = self.class.normalize_api_key(api_key) || self.class.normalize_api_key(ENV["MCP_API_KEY"]) # NEW-MCP-1: a non-loopback bind without an API key is an unauthenticated # network-exposed JSON-RPC endpoint. Refuse to start. Operators who # genuinely want this — e.g., behind a reverse proxy that handles # auth — should bind to localhost and let the proxy forward, or # set MCP_API_KEY explicitly even when "the proxy authenticates" # (defense in depth). if !LOOPBACK_HOSTS.include?(host.to_s) && effective_api_key.nil? raise ArgumentError, "MCPServer refuses to bind non-loopback host #{host.inspect} without an api_key. " \ "Set MCP_API_KEY in the environment, pass api_key: explicitly, or use a loopback " \ "host (one of: #{LOOPBACK_HOSTS.join(", ")})." end # A short key on a public bind is guessable. Warn rather than refuse # in a patch release so existing deployments keep starting. if !LOOPBACK_HOSTS.include?(host.to_s) && effective_api_key.length < MIN_PUBLIC_API_KEY_LENGTH warn "[Parse::Agent::MCPServer:SECURITY] api_key for non-loopback host #{host.inspect} " \ "is shorter than #{MIN_PUBLIC_API_KEY_LENGTH} characters. Use a long random key " \ "(for example SecureRandom.hex(32))." end @port = port @host = host @api_key = effective_api_key @permissions = @session_token = session_token # Shared limiter across requests so per-request agents (built in # agent_factory) don't reset their window on every call. The # rate-limit budget is a server-level resource, not a per-Agent one. @shared_rate_limiter = rate_limiter || RateLimiter.new # Template agent for the /tools listing endpoint and for inspection # via #agent. NOT used for live request dispatch — see agent_factory. @agent = Parse::Agent.new( permissions: @permissions, session_token: @session_token, rate_limiter: @shared_rate_limiter, ) @server = nil # The Rack app does the heavy lifting. Its agent_factory enforces the # API key and constructs a FRESH Parse::Agent per request so the # per-instance state (@conversation_history, @operation_log, token # counters) cannot leak between requests. # pre_auth_rate_limiter: closes NEW-MCP-6 — runs before the factory # is invoked so an empty or malformed body can't amplify into a # Parse Server round-trip. # NEW-9: on an unauthenticated loopback dev bind with no explicit CSRF # gate configured, enable a loopback-only Origin policy by default to # mitigate browser DNS-rebinding (a malicious page resolving a hostname # to 127.0.0.1 and POSTing to the agent). The attacker page always # carries a non-loopback Origin and is refused; native (no-Origin) # clients and real local browser UIs are unaffected. Skipped when an # API key is set (auth already gates) or the operator configured the # Origin/custom-header gates themselves. loopback_csrf_default = LOOPBACK_HOSTS.include?(host.to_s) && @api_key.to_s.empty? && allowed_origins.nil? && require_custom_header.nil? if loopback_csrf_default warn "[Parse::Agent::MCPServer] Binding #{host}:#{port} without an API key. " \ "Enabling a loopback-only Origin policy to mitigate browser DNS-rebinding. " \ "For anything beyond local single-user dev set MCP_API_KEY (or pass api_key:), " \ "and/or configure allowed_origins:/require_custom_header:." end @rack_app = MCPRackApp.new( agent_factory: method(:agent_factory), pre_auth_rate_limiter: pre_auth_rate_limiter, allowed_origins: allowed_origins, require_custom_header: require_custom_header, loopback_csrf_default: loopback_csrf_default, # DNS-rebinding: on a loopback bind, refuse any request whose Host # header is not a loopback host or listed in allowed_hosts:. loopback_bind: LOOPBACK_HOSTS.include?(host.to_s), allowed_hosts: allowed_hosts, ) end |
Class Attribute Details
.default_port ⇒ Object
Returns the value of attribute default_port.
66 67 68 |
# File 'lib/parse/agent/mcp_server.rb', line 66 def default_port @default_port end |
Instance Attribute Details
#agent ⇒ Parse::Agent (readonly)
Returns the template agent used by the /tools listing endpoint and as a settings source for per-request agents. Hot tools in MCP requests run against fresh per-request instances; do NOT share this object across threads for mutable state inspection.
106 107 108 |
# File 'lib/parse/agent/mcp_server.rb', line 106 def agent @agent end |
#host ⇒ String (readonly)
Returns the host to bind to.
100 101 102 |
# File 'lib/parse/agent/mcp_server.rb', line 100 def host @host end |
#port ⇒ Integer (readonly)
Returns the port number.
97 98 99 |
# File 'lib/parse/agent/mcp_server.rb', line 97 def port @port end |
Class Method Details
.normalize_api_key(key) ⇒ Object
155 156 157 158 159 |
# File 'lib/parse/agent/mcp_server.rb', line 155 def self.normalize_api_key(key) return nil if key.nil? stripped = strip_unicode_space(key.to_s) stripped.empty? ? nil : stripped end |
.require_webrick! ⇒ true
Load WEBrick for the standalone server, raising a LoadError that explains the fix when the application does not bundle it.
265 266 267 268 269 270 271 272 273 274 |
# File 'lib/parse/agent/mcp_server.rb', line 265 def self.require_webrick! return true if defined?(::WEBrick::HTTPServer) require "webrick" true rescue LoadError => e raise LoadError, "Parse::Agent::MCPServer#start needs the webrick gem, which is not a " \ "dependency of parse-stack-next. Add `gem \"webrick\"` to your Gemfile, " \ "or mount Parse::Agent::MCPRackApp in your own Rack server " \ "(Puma, Falcon, ...). (#{e.})" end |
.run(port: nil, permissions: :readonly, session_token: nil, host: "127.0.0.1", api_key: nil, rate_limiter: nil, allowed_hosts: nil) ⇒ Object
Start the MCP server (blocking)
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
# File 'lib/parse/agent/mcp_server.rb', line 77 def run(port: nil, permissions: :readonly, session_token: nil, host: "127.0.0.1", api_key: nil, rate_limiter: nil, allowed_hosts: nil) unless Parse::Agent.mcp_enabled? raise "MCP server not enabled. Call Parse::Agent.enable_mcp! first" end server = new( port: port || @default_port, permissions: , session_token: session_token, host: host, api_key: api_key, rate_limiter: rate_limiter, allowed_hosts: allowed_hosts, ) server.start end |
.strip_unicode_space(str) ⇒ String?
The API key to enforce, or nil when none is configured. Surrounding whitespace (ASCII or Unicode) is stripped, and a blank result is no key. Strip leading and trailing whitespace of any kind (ASCII or Unicode) with a linear scan from each end.
147 148 149 150 151 152 153 |
# File 'lib/parse/agent/mcp_server.rb', line 147 def self.strip_unicode_space(str) first = 0 last = str.length first += 1 while first < last && str[first].match?(/[[:space:]]/) last -= 1 while last > first && str[last - 1].match?(/[[:space:]]/) str[first...last] end |
Instance Method Details
#start ⇒ Object
Start the HTTP server (blocking)
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
# File 'lib/parse/agent/mcp_server.rb', line 277 def start self.class.require_webrick! @server = WEBrick::HTTPServer.new( Port: @port, BindAddress: @host, Logger: WEBrick::Log.new($stdout, WEBrick::Log::INFO), AccessLog: [[::File.open(::File::NULL, "w"), ""]], # Suppress access log ) setup_routes trap("INT") { stop } trap("TERM") { stop } puts "Parse MCP Server starting on http://#{@host}:#{@port}" puts "Permissions: #{@agent.}" puts "Tools available: #{@agent.allowed_tools.join(", ")}" @server.start end |
#stop ⇒ Object
Stop the server
299 300 301 |
# File 'lib/parse/agent/mcp_server.rb', line 299 def stop @server&.shutdown end |