MCPR

MCPR

Stateful Human-AI Collaboration and Persistent R Sessions

16
Stars
5
Forks
16
Watchers
2
Issues
MCPR enables AI agents to establish interactive, persistent sessions within a live R environment, allowing for stateful, multi-step analytical workflows. By leveraging JSON-RPC 2.0 over `nanonext` sockets, it facilitates robust, asynchronous communication and exposes R session functionalities as modular tools. The framework includes session management, service discovery, and advanced plot rendering capabilities, making it ideal for collaborative and iterative data analysis.

Key Features

Persistent, stateful R session management for AI agents
JSON-RPC 2.0 protocol over asynchronous nanonext sockets
Service discovery and session joining for remote agents
Tool-based modular access to R session functionality
Live execution of R code and graphics generation
Support for advanced graphics rendering with httpgd and standard devices
Robust token and image payload management
Cross-platform compatibility
Non-blocking, reliable messaging infrastructure
Automatic workspace state preservation for iterative workflows

Use Cases

Enabling AI copilots to assist with complex, multi-step R analysis
Allowing remote AI agents to execute code in an interactive R environment
Automating repetitive analytical tasks through persistent context
Collaborative data science sessions between human users and AI agents
Efficient iterative modeling and exploration with session state retention
Automated plot and graphics generation for R projects
Managing heavy computational workflows without loss of context
Inspecting and manipulating the R workspace remotely via AI tools
Developing AI-powered R IDE extensions for enhanced productivity
Integrating context-aware analytics into interactive R applications

README

MCPR: A Practical Framework for Stateful Human-AI Collaboration in R

Lifecycle:
experimental R-CMD-check Codecov test
coverage GitHub release (latest by
date)

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, and validation that can span hours or days. Moreover, intermediate steps can involve heavy computation, and small changes in downstream code such as plot aesthetics require running the entire script again. MCPR aims to tackle this issue by enabling AI agents to establish persistent, interactive sessions within a live R environment, thereby preserving workspace state and enabling complex, multi-step analytical workflows.

Quick Start

Get up and running with MCPR in under 2 minutes:

r
# 1. Install MCPR
remotes::install_github("phisanti/MCPR")

# 2. Start an R session and make it discoverable
library(MCPR)
mcpr_session_start()

# 3. In your AI agent (Claude, etc.), connect to the session
# The agent will use: manage_r_sessions("list") then manage_r_sessions("join", session_id)

# 4. Now your AI agent can run R code in your live session!
# Example: execute_r_code("summary(mtcars)")

That’s it! Your AI agent can now execute R code, create plots, and inspect your workspace while preserving all session state.

Core capabilities

MCPR’s design is guided by principles of modularity, robustness, and practicality.

  • Communication Protocol: MCPR uses JSON-RPC 2.0 over nanonext sockets, providing a lightweight, asynchronous, and reliable messaging layer. This choice ensures cross-platform compatibility and non-blocking communication suitable for an interactive environment.
  • Tool-Based Design: Functionality is exposed to the AI agent as a discrete set of tools (create_plot, execute_r_code, etc.). This modular approach simplifies the agent’s interaction logic and provides clear, well-defined endpoints for R operations.
  • Session Management: A central mcpr_session_start() function acts as a listener, making an R session discoverable on the local machine. The manage_r_sessions tool provides the service discovery mechanism for agents to find and connect to these listeners.
  • Graphics Subsystem: Plot generation leverages httpgd when available for high-performance, off-screen rendering. A fallback to standard R graphics devices (grDevices) ensures broad compatibility. The system includes intelligent token management to prevent oversized image payloads.

Installation

The first requirement is to have R installed and then install the MCPR package from GitHub:

r
if (!require("remotes")) install.packages("remotes")

remotes::install_github("phisanti/MCPR")

Next, you should install the MCP server to give the agent access to the tools included in the package. System integration is designed to be straightforward, with both automated and manual pathways.

Automated Setup

A convenience function, install_mcpr(), is provided to handle package installation and agent-specific MCP configuration.

r
library(MCPR)
install_mcpr(agent = "claude") # Supported agents: 'claude', 'gemini', 'copilot'

Manual MCP Configuration

For Claude Desktop, configure claude_desktop_config.json. You can likely find it in one of these locations depending on your OS:

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json Windows: %APPDATA%\Claude\claude_desktop_config.json Linux: ~/.config/claude/claude_desktop_config.json

Then, add the following MCP server configuration:

json
{
  "mcpServers": {
    "mcpr": {
      "command": "R",
      "args": ["--quiet", "--slave", "-e", "MCPR::mcpr_server()"]
    }
  }
}

Usage Pattern

The intended workflow is simple and user-centric.

  1. The user starts an R session and invokes mcpr_session_start() to enable connections.
  2. The user instructs their AI agent to connect.
  3. The agent uses manage_r_sessions('list') to find the session ID and manage_r_sessions('join', session=ID) to connect.
  4. The user can now interact with the agent, making requests regarding their R session. The agent can now use execute_r_code, create_plot, and view to collaboratively assist the user with their analysis, maintaining full context throughout the interaction.

Agent tools

The philosophy in the development of the MCPR package is to provide the agent with few, well-defined tools that can be composed to perform complex tasks. The goal was to give the agent the ability to manage multiple R sessions (manage_r_sessions), to run R code in the session (execute_r_code), see the graphical data (create_plot), and inspect the session (view). We believe these are flexible enough to accomplish any task in R. See the details below.

execute_r_code(code)

Purpose: Execute arbitrary R code within session context
Input: Character string containing R expressions
Output: Structured response with results, output, warnings, and errors

r
execute_r_code("
  library(dplyr)
  data <- mtcars %>% 
    filter(mpg > 20) %>%
    select(mpg, cyl, wt)
  nrow(data)
")

create_plot(expr, width, height, format)

Purpose: Generate visualizations with AI-optimized output
Input: R plotting expression, dimensions, format specification
Output: Base64-encoded image with metadata and token usage information

r
create_plot("
  library(ggplot2)
  ggplot(mtcars, aes(wt, mpg)) + 
    geom_point() + 
    geom_smooth(method = 'lm')
", width = 600, height = 450)

manage_r_sessions(action, session)

Purpose: Session discovery and management
Actions:

  • "list": Enumerate active sessions with metadata
  • "join": Connect to specific session by ID
  • "start": Launch new R session process
r
manage_r_sessions("list")        # Show available sessions
manage_r_sessions("join", 2)     # Connect to session 2
manage_r_sessions("start")       # Create new session

view(what, max_lines)

Purpose: Environment introspection and debugging
what:

  • 'session': Object summaries with statistical metadata
  • 'terminal': Command history for workflow reproducibility
  • 'workspace': File system context
  • 'installed_packages': Available libraries

Common errors

  • Connection Failed: Ensure mcpr_session_start() is running in R. Set the MCPTOOLS_LOG_FILE environment variable to a valid path and inspect logs for detailed error messages.
  • Tools Not Found: Confirm the path in user_mcp.json is correct and that the agent has been restarted. Manually install the MCP server to verify the setup.
  • Plotting Errors: Ensure the plotting expression is valid and that all necessary libraries are loaded, and install httpgd.

If these issues persist, please open an issue on the GitHub repository with relevant logs and context.

Acknowledgments

We thank Simon P. Couch (mcptools) for the inspiration to use nanonext and Aleksander Dietrichson (mcpr) for the idea of using roxygen2 for parsing tools.


This project is licensed under the Creative Commons Attribution 4.0 International License.

Star History

Star History Chart

Repository Owner

phisanti
phisanti

User

Repository Details

Language R
Default Branch main
Size 5,302 KB
Contributors 1
License Creative Commons Attribution Share Alike 4.0 International
MCP Verified Nov 12, 2025

Programming Languages

R
97.96%
CSS
2.04%

Topics

data-analysis mcp mcp-server r

Join Our Newsletter

Stay updated with the latest AI tools, news, and offers by subscribing to our weekly newsletter.

We respect your privacy. Unsubscribe at any time.

Related MCPs

Discover similar Model Context Protocol servers

  • ApeRAG

    ApeRAG

    Hybrid RAG platform with MCP integration for intelligent knowledge management

    ApeRAG is a production-ready Retrieval-Augmented Generation (RAG) platform that integrates graph-based, vector, and full-text search capabilities. It enables the construction of knowledge graphs and supports MCP (Model Context Protocol), allowing AI assistants direct interaction with knowledge bases. Features include advanced document parsing, multimodal processing, intelligent agent workflows, and enterprise management tools. Deployment is streamlined via Docker and Kubernetes, with extensive support for customization and scalability.

    • 920
    • MCP
    • apecloud/ApeRAG
  • Agentic Long-Term Memory with Notion Integration

    Agentic Long-Term Memory with Notion Integration

    Production-ready agentic long-term memory and Notion integration with Model Context Protocol support.

    Agentic Long-Term Memory with Notion Integration enables AI agents to incorporate advanced long-term memory capabilities using both vector and graph databases. It offers comprehensive Notion workspace integration along with a production-ready Model Context Protocol (MCP) server supporting HTTP and stdio transports. The tool facilitates context management, tool discovery, and advanced function chaining for complex agentic workflows.

    • 4
    • MCP
    • ankitmalik84/Agentic_Longterm_Memory
  • GhidraMCP

    GhidraMCP

    AI-powered binary analysis through Model Context Protocol integration with Ghidra

    GhidraMCP is a Ghidra plugin that implements the Model Context Protocol (MCP), enabling seamless connectivity between Ghidra and AI-powered assistants for advanced binary analysis. It allows users to interact with binaries using natural language, automate security and code analysis, and retrieve detailed program insights through a socket-based architecture. The plugin offers functions for exploring binary structures, analyzing memory layouts, and identifying vulnerabilities, providing a flexible and efficient reverse engineering workflow.

    • 77
    • MCP
    • 13bm/GhidraMCP
  • Box MCP Server (Remote)

    Box MCP Server (Remote)

    Securely connect AI agents to Box content and Box AI using the Model Context Protocol.

    Box MCP Server (Remote) enables AI agent platforms to securely interact with Box data and AI-powered tools via the Model Context Protocol. It supports OAuth-based authentication and provides various capabilities, including user identification, file and folder operations, and access to Box AI tools. The service exposes an endpoint for easy integration by MCP-compatible clients while ensuring data never leaves the Box environment. It offers both admin console and developer console setup options and comprehensive documentation for connection.

    • 0
    • MCP
    • box/mcp-server-box-remote
  • MCP Server for Data Exploration

    MCP Server for Data Exploration

    Interactive Data Exploration and Analysis via Model Context Protocol

    MCP Server for Data Exploration enables users to interactively explore and analyze complex datasets using prompt templates and tools within the Model Context Protocol ecosystem. Designed as a personal Data Scientist assistant, it facilitates the conversion of raw data into actionable insights without manual intervention. Users can load CSV datasets, run Python scripts, and generate tailored reports and visualizations through an AI-powered interface. The server integrates directly with Claude Desktop, supporting rapid setup and seamless usage for both macOS and Windows.

    • 503
    • MCP
    • reading-plus-ai/mcp-server-data-exploration
  • MetaTrader MCP Server

    MetaTrader MCP Server

    Let AI assistants trade for you using natural language.

    MetaTrader MCP Server is a bridge that connects AI assistants such as Claude and ChatGPT to the MetaTrader 5 trading platform via the Model Context Protocol (MCP). It enables users to perform trading actions on MetaTrader 5 through natural language instructions. The system supports real-time data access, full account management, and secure local credential handling, offering both MCP and REST API interfaces.

    • 120
    • MCP
    • ariadng/metatrader-mcp-server
  • Didn't find tool you were looking for?

    Be as detailed as possible for better results