Agent skill

mcp-rails

Implement Model Context Protocol (MCP) in Rails applications. Use when building AI agents that need to connect to MCP servers, expose Rails apps as MCP servers, or manage MCP subprocess containers via Docker. Covers JSON-RPC transport, OAuth 2.1 PKCE authentication, SSE streaming, and multi-worker process coordination.

Stars 0
Forks 0

Install this agent skill to your Project

npx add-skill https://github.com/rbarazi/agent-skills/tree/main/skills/mcp-rails

Metadata

Additional technical details for this skill

author
agentify
version
1.0

SKILL.md

MCP Rails Implementation

Implement a complete Model Context Protocol stack in Rails, enabling your app to:

  • Connect to external MCP servers as a client
  • Expose itself as an MCP server for Claude Desktop, VS Code, etc.
  • Manage subprocess MCP servers via Docker containers

Quick Decision Guide

What do you need?

Goal Start With
Connect to external MCP tools Client Core
Build an MCP server in Rails Server Implementation
Create multi-tool MCP server Tools and Schemas
Add UI widgets to tool results UI Widget Pipeline
Run MCP servers as Docker containers Docker Supervisor
Add OAuth to MCP connections OAuth Flow

Architecture Overview

┌─────────────────────────────────────────────────────────────┐
│                     Your Rails App                          │
├─────────────────────────────────────────────────────────────┤
│  MCP Client Layer              │  MCP Server Layer          │
│  ┌─────────────────────┐       │  ┌─────────────────────┐   │
│  │ MCPClient           │       │  │ BaseMCPServer       │   │
│  │ - Remote HTTP/SSE   │       │  │ - JSON-RPC Handler  │   │
│  │ - Subprocess Docker │       │  │ - Tool Registry     │   │
│  │ - OAuth PKCE Flow   │       │  │ - Resource Support  │   │
│  └─────────────────────┘       │  └─────────────────────┘   │
│           │                    │            │               │
│           ▼                    │            ▼               │
│  ┌─────────────────────┐       │  ┌─────────────────────┐   │
│  │ Transport Layer     │       │  │ MCP::ServersController│  │
│  │ - HTTP Transport    │       │  │ - POST /mcp/:name/  │   │
│  │ - SSE Transport     │       │  │ - GET /mcp/:name/sse│   │
│  │ - Subprocess I/O    │       │  │ - OAuth Auth        │   │
│  └─────────────────────┘       │  └─────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

Implementation Order

Phase 1: Client Core (2-3 hours)

  1. Read Client Core
  2. Run scaffold: ruby scripts/scaffold_mcp_client.rb
  3. Implement basic JSON-RPC communication

Phase 2: Transport Layer (2-3 hours)

  1. Read Transport Layer
  2. Choose transport strategy: HTTP-first, SSE-first, or subprocess
  3. Implement transport abstraction

Phase 3: OAuth Flow (Optional, 3-4 hours)

  1. Read OAuth Flow
  2. Implement PKCE discovery and token exchange
  3. Add token storage to your tool configuration model

Phase 4: Docker Supervisor (Optional, 4-6 hours)

  1. Read Docker Supervisor
  2. Implement process lifecycle management
  3. Add multi-worker coordination via database locks

Phase 5: Server Implementation (4-6 hours)

  1. Read Server Implementation
  2. Create BaseMCPServer DSL
  3. Implement JSON-RPC controller

Key Files to Create

app/
├── services/
│   ├── mcp_client.rb                    # Core client
│   ├── mcp_client/
│   │   ├── session.rb                   # Session management
│   │   ├── oauth_flow.rb                # OAuth PKCE
│   │   └── transport/
│   │       ├── json_rpc_transport.rb    # Base interface
│   │       ├── remote_http_transport.rb # HTTP transport
│   │       ├── remote_sse_transport.rb  # SSE transport
│   │       └── subprocess_transport.rb  # Docker transport
│   └── mcp_docker_process_supervisor.rb # Container management
├── controllers/mcp/
│   └── servers_controller.rb            # MCP server endpoints
├── mcp_servers/
│   └── base_mcp_server.rb               # Server DSL
└── models/mcp/
    ├── client.rb                        # Client registration
    └── client_session.rb                # Session tracking

db/migrate/
├── create_mcp_clients.rb
└── create_mcp_client_sessions.rb

Output Checklist

When implementation is complete, verify:

  • MCP client can initialize sessions and persist Mcp-Session-Id
  • Client can list tools (tools/list) and call tools (tools/call)
  • Transport fallback works (HTTP → SSE or vice versa)
  • OAuth-enabled tools trigger PKCE flow when unauthorized
  • Subprocess mode starts Docker containers with health checks
  • Multi-worker coordination prevents duplicate supervisors
  • Rails app exposes /mcp/:server JSON-RPC endpoint
  • Optional SSE endpoint at /mcp/:server/sse streams responses
  • UI resources return correct mimeType and uri formats

Common Pitfalls

  1. Missing Mcp-Session-Id header: Always send session ID after initialize call
  2. Ignoring transport fallback: When HTTP returns 404/405, try SSE transport
  3. Treating OAuth tools like legacy tools: Must return WWW-Authenticate challenge on missing token
  4. Failing to release locks for stale supervisors: Implement timeout-based cleanup
  5. Embedding UI resources without correct format: Ensure mimeType and uri follow spec
  6. Not handling OAuth token refresh: Tokens expire, implement refresh or re-auth flow
  7. Process coordination race conditions: Use database locks for subprocess ownership

Testing Notes

Client Testing

  • Initialize session and assert Mcp-Session-Id persists across requests
  • Exercise both HTTP and SSE transport paths
  • Simulate OAuth 401 challenge and verify token exchange flow
  • Test transport fallback when primary transport fails

Server Testing

  • Validate JSON-RPC success and error envelope formats
  • Confirm scope enforcement on protected tools
  • Test session creation, extension, and expiration
  • Verify tool registration and discovery

Subprocess Testing

  • Start supervisor and wait for ready state
  • Kill process and verify restart or failure marking
  • Simulate multi-worker contention for supervisor ownership
  • Test cleanup of stale containers

References

  • Client Core - JSON-RPC client implementation
  • Transport Layer - HTTP, SSE, subprocess transports
  • OAuth Flow - PKCE discovery and token exchange
  • Docker Supervisor - Container lifecycle
  • Server Implementation - Building MCP servers
  • Session Management - Client sessions
  • Multi-Worker Coordination - Database locks
  • Host Integration - Tool configuration and app wiring
  • UI Resources - Rich client rendering resources
  • Testing - Test strategies and examples
  • Tools and Schemas - Multi-tool server patterns
  • UI Widget Pipeline - Widget template hydration

Expand your agent's capabilities with these related and highly-rated skills.

rbarazi/agent-skills

test-auth-helpers

Implement authentication testing patterns with RSpec, FactoryBot, and test helpers for Rails applications. Use when writing controller specs, system tests, or request specs that require authenticated users and multi-tenant account context.

0 0
Explore
rbarazi/agent-skills

multi-tenant-accounts

Implement multi-tenant architecture using an Account model as the tenant boundary. Use when building SaaS applications, team-based apps, or any system where data must be isolated between organizations/accounts.

0 0
Explore
rbarazi/agent-skills

user-management

Implement user CRUD operations within an account with permission controls and feature flags. Use when building team member management, user administration, or account user settings in multi-tenant Rails applications.

0 0
Explore
rbarazi/agent-skills

oauth21-provider

Implement an RFC-compliant OAuth 2.1 authorization server in Rails applications. Use when building apps that need to authorize third-party clients (like MCP clients, API consumers, or external integrations) using industry-standard OAuth flows with PKCE, dynamic client registration, and token management.

0 0
Explore
rbarazi/agent-skills

password-reset-flow

Implement secure password reset with Rails 8's built-in token generation. Use when building "forgot password" functionality with email verification and time-limited reset tokens.

0 0
Explore
rbarazi/agent-skills

code-pattern-extraction

Extract reusable design and implementation patterns from codebases into Skills. Use when asked to analyze code for patterns, document architectural decisions, create transferrable implementation guides, or extract knowledge into Skills. Transforms working implementations into comprehensive, reusable Skills that can be applied to new projects.

0 0
Explore

Didn't find tool you were looking for?

Be as detailed as possible for better results