The MCPR (Model Context Protocol Tools for R) package addresses a fundamental limitation in the current paradigm of AI-assisted R programming. Existing AI agents operate in a stateless execution model, invoking Rscript for each command, which is antithetical to the iterative, state-dependent nature of serious data analysis. An analytical workflow is a cumulative process of exploration, modelling,
Add this skill
npx mdskills install phisanti/mcprEnables stateful R session management for AI agents with persistent workspace and plotting capabilities
12<!-- README.md is generated from README.Rmd. Please edit that file -->34# MCPR: A Practical Framework for Stateful Human-AI Collaboration in R <a href="https://phisanti.github.io/MCPR/" alt="MCPR"><img src="man/figures/logo.png" alt="MCPR logo" align="right" width="120" /></a>56<!-- badges: start -->78[](https://lifecycle.r-lib.org/articles/stages.html#experimental)10[](https://github.com/phisanti/MCPR/actions/workflows/R-CMD-check.yaml)11[](https://app.codecov.io/gh/phisanti/MCPR?branch=main)13[](https://github.com/phisanti/MCPR/releases)15<!-- badges: end -->1617The MCPR (Model Context Protocol Tools for R) package addresses a18fundamental limitation in the current paradigm of AI-assisted R19programming. Existing AI agents operate in a stateless execution model,20invoking `Rscript` for each command, which is antithetical to the21iterative, state-dependent nature of serious data analysis. An22analytical workflow is a cumulative process of exploration, modelling,23and validation that can span hours or days. Moreover, intermediate steps24can involve heavy computation, and small changes in downstream code such25as plot aesthetics require running the entire script again. MCPR aims to26tackle this issue by enabling AI agents to establish persistent,27interactive sessions within a live R environment, thereby preserving28workspace state and enabling complex, multi-step analytical workflows.2930<figure>31<img src="man/figures/mcpr_demo.gif" alt="MCPR Demo" />32<figcaption aria-hidden="true">MCPR Demo</figcaption>33</figure>3435## Quick Start3637Get up and running with MCPR in under 2 minutes:3839``` r40# 1. Install MCPR41remotes::install_github("phisanti/MCPR")4243# 2. Start an R session and make it discoverable44library(MCPR)45mcpr_session_start()4647# 3. In your AI agent (Claude, etc.), connect to the session48# The agent will use: manage_r_sessions("list") then manage_r_sessions("join", session_id)4950# 4. Now your AI agent can run R code in your live session!51# Example: execute_r_code("summary(mtcars)")52```5354**That’s it!** Your AI agent can now execute R code, create plots, and55inspect your workspace while preserving all session state.5657## Core capabilities5859MCPR’s design is guided by principles of modularity, robustness, and60practicality.6162- **Communication Protocol:** MCPR uses JSON-RPC 2.0 over `nanonext`63 sockets, providing a lightweight, asynchronous, and reliable messaging64 layer. This choice ensures cross-platform compatibility and65 non-blocking communication suitable for an interactive environment.66- **Tool-Based Design:** Functionality is exposed to the AI agent as a67 discrete set of tools (create_plot, execute_r_code, etc.). This68 modular approach simplifies the agent’s interaction logic and provides69 clear, well-defined endpoints for R operations.70- **Session Management:** A central `mcpr_session_start()` function acts71 as a listener, making an R session discoverable on the local machine.72 The `manage_r_sessions` tool provides the service discovery mechanism73 for agents to find and connect to these listeners.74- **Graphics Subsystem:** Plot generation leverages `httpgd` when75 available for high-performance, off-screen rendering. A fallback to76 standard R graphics devices (grDevices) ensures broad compatibility.77 The system includes intelligent token management to prevent oversized78 image payloads.7980## Installation8182The first requirement is to have R installed and then install the MCPR83package from GitHub:8485``` r86if (!require("remotes")) install.packages("remotes")8788remotes::install_github("phisanti/MCPR")89```9091Next, you should install the MCP server to give the agent access to the92tools included in the package. System integration is designed to be93straightforward, with both automated and manual pathways.9495### Automated Setup9697A convenience function, `install_mcpr()`, is provided to handle package98installation and agent-specific MCP configuration. Supported agents99include Claude, Gemini, Copilot, and Codex.100101``` r102library(MCPR)103install_mcpr(agent = "claude") # Supported agents: 'claude', 'gemini', 'copilot', 'codex'104```105106### Manual MCP Configuration107108For Claude Desktop, configure `claude_desktop_config.json`. You can109likely find it in one of these locations depending on your OS:110111**macOS**:112`~/Library/Application Support/Claude/claude_desktop_config.json`113**Windows**: `%APPDATA%\Claude\claude_desktop_config.json` **Linux**:114`~/.config/claude/claude_desktop_config.json`115116Then, add the following MCP server configuration:117118``` json119{120 "mcpServers": {121 "mcpr": {122 "command": "R",123 "args": ["--quiet", "--slave", "-e", "MCPR::mcpr_server()"]124 }125 }126}127```128129### Supported agents130131Currently, MCPR supports configuration for the following AI agents with132the given configuration paths (note that these are approximate and might133vary based on OS and installation):134135- **Claude:** Claude Desktop config at136 `~/Library/Application Support/Claude/claude_desktop_config.json`137 (macOS), `%APPDATA%/Claude/claude_desktop_config.json` (Windows), or138 `~/.config/Claude/claude_desktop_config.json` (Linux).139- **Gemini:** Global settings at `~/.gemini/settings.json` (use140 `./.gemini/settings.json` for a project-local setup).141- **Copilot:** Workspace configuration at `.vscode/mcp.json` (user-level142 fallback at `~/.config/Code/User/mcp.json` or143 `%APPDATA%/Code/User/mcp.json`).144- **Codex:** Global TOML configuration at `~/.codex/config.toml`.145146## Usage Pattern147148The intended workflow is simple and user-centric.1491501. The user starts an R session and invokes `mcpr_session_start()` to151 enable connections.1522. The user instructs their AI agent to connect.1533. The agent uses `manage_r_sessions('list')` to find the session ID154 and `manage_r_sessions('join', session=ID)` to connect.1554. The user can now interact with the agent, making requests regarding156 their R session. The agent can now use `execute_r_code`,157 `create_plot`, and `view` to collaboratively assist the user with158 their analysis, maintaining full context throughout the interaction.159160## Agent tools161162The philosophy in the development of the MCPR package is to provide the163agent with few, well-defined tools that can be composed to perform164complex tasks. The goal was to give the agent the ability to manage165multiple R sessions (`manage_r_sessions`), to run R code in the session166(`execute_r_code`), see the graphical data (`create_plot`), and inspect167the session (`view`). We believe these are flexible enough to accomplish168any task in R. See the details below.169170### `execute_r_code(code)`171172**Purpose**: Execute arbitrary R code within session context173**Input**: Character string containing R expressions174**Output**: Structured response with results, output, warnings, and175errors176177``` r178execute_r_code("179 library(dplyr)180 data <- mtcars %>%181 filter(mpg > 20) %>%182 select(mpg, cyl, wt)183 nrow(data)184")185```186187### `create_plot(expr, width, height, format)`188189**Purpose**: Generate visualizations with AI-optimized output190**Input**: R plotting expression, dimensions, format specification191**Output**: Base64-encoded image with metadata and token usage192information193194``` r195create_plot("196 library(ggplot2)197 ggplot(mtcars, aes(wt, mpg)) +198 geom_point() +199 geom_smooth(method = 'lm')200", width = 600, height = 450)201```202203### `manage_r_sessions(action, session)`204205**Purpose**: Session discovery and management206**Actions**:207208- `"list"`: Enumerate active sessions with metadata209- `"join"`: Connect to specific session by ID210- `"start"`: Launch new R session process211212``` r213manage_r_sessions("list") # Show available sessions214manage_r_sessions("join", 2) # Connect to session 2215manage_r_sessions("start") # Create new session216```217218### `view(what, max_lines)`219220**Purpose**: Environment introspection and debugging221**what**:222223- `'session'`: Object summaries with statistical metadata224- `'terminal'`: Command history for workflow reproducibility225- `'workspace'`: File system context226- `'installed_packages'`: Available libraries227228## Common errors229230- **Connection Failed:** Ensure `mcpr_session_start()` is running in R.231 Set the `MCPTOOLS_LOG_FILE` environment variable to a valid path and232 inspect logs for detailed error messages.233- **Tools Not Found:** Confirm the path in `user_mcp.json` is correct234 and that the agent has been restarted. Manually install the MCP server235 to verify the setup.236- **Plotting Errors:** Ensure the plotting expression is valid and that237 all necessary libraries are loaded, and install `httpgd`.238239If these issues persist, please open an issue on the GitHub repository240with relevant logs and context.241242## Acknowledgments243244We thank [Simon P. Couch](https://github.com/simonpcouch)245([mcptools](https://github.com/posit-dev/mcptools)) for the inspiration246to use nanonext and [Aleksander247Dietrichson](https://github.com/dietrichson)248([mcpr](https://github.com/chi2labs/mcpr)) for the idea of using249roxygen2 for parsing tools.250251------------------------------------------------------------------------252253This project is licensed under the Creative Commons Attribution 4.0254International License.255
Full transparency — inspect the skill content before installing.