MCP

gptr logo

MCP connects tools across applications. gptr can call an existing MCP server’s tools as R functions, or serve its live R session to another agent. A model provider is configured separately; see Language models. All examples here require an existing server or change configuration, so they are shown without being run.

Diagram: gptr as an MCP client and as an MCP server
MCP in both directions. As a client, R sends JSON arguments to a server and receives an R value; as a server, R runs another agent’s code on the objects already in your session and returns text and images.

List first, connect when needed

library(gptr)
gptr_mcp()

The default listing reads configuration and cached counts. It does not start a process or contact a server. It includes gptr’s user and project files and compatible configurations from Claude Code, Claude Desktop, Codex, Cursor, VS Code and Pi. gptr reads those other applications’ files without editing them; their servers are used on request rather than advertised automatically.

Listing tools can connect when the cache is missing or stale. refresh = TRUE reconnects even when tools = FALSE. A stdio connection starts a local program; an HTTP connection contacts its endpoint. Limit inspection to the server you intend to use:

gptr_mcp("catalog", tools = TRUE)
gptr_mcp("catalog", tools = TRUE, refresh = TRUE)

Project servers are listed in an untrusted project but are not started. Review the configuration and command before trusting a project, as described in Configuration.

Register a server

gptr_mcp_add() accepts either command plus args for stdio, or url for Streamable HTTP. It writes gptr’s own configuration and does not connect. Install or configure the server itself using its documentation before registering it. For a server script you already have:

gptr_mcp_add(
  "catalog",
  command = "Rscript",
  args = c("--vanilla", "/absolute/path/to/mcp-server.R"),
  env = c(CATALOG_API_KEY = "${CATALOG_API_KEY}"),
  scope = "user"
)

An R server using a private package library needs that search path explicitly:

gptr_mcp_add(
  "my-r-server",
  command = file.path(R.home("bin"), "Rscript"),
  args = c("--vanilla", "/absolute/path/to/server.R"),
  env = c(R_LIBS = paste(.libPaths(), collapse = .Platform$path.sep)),
  scope = "project"
)

Servers using R’s standard library do not need this setting. MCP child processes receive a filtered environment. Declare only trusted library paths; keep credentials in their separate placeholders.

For an existing HTTP service:

gptr_mcp_add(
  "catalog-http", url = "http://127.0.0.1:8000/mcp",
  headers = c(Authorization = "Bearer ${CATALOG_API_KEY}"),
  scope = "project"
)

scope = "user" stores the entry in mcp.json under tools::R_user_dir("gptr", "config"). scope = "project" uses .gptr/mcp.json, which needs a .gptr/ workspace from gptr_init() and takes effect only once you trust the project (gptr_trust()); gptr_mcp_add() does neither. Secrets in env and headers must use ${VAR} placeholders; gptr expands them from the environment at connection time. Do not put key values in a checked-in file or a recorded command. See Configuration for environment loading and credential storage.

exposure = "r" lists R signatures in the model’s catalog. "direct" declares full model tools, "deferred" makes tools discoverable through peter$search(), and "hidden" omits them from the catalog. The timeout is per request; server progress notifications extend it.

Remove an entry from the same scope in which you added it:

gptr_mcp_remove("catalog", scope = "user")

Removal closes the connection and deletes that gptr entry. An entry in another scope or another application’s configuration can still exist; edit its owning configuration to remove it there.

Peter can find these functions while it works: peter$search("mcp server") lists them, and peter$help("gptr::gptr_mcp_add") reads this help page. A call from model code that changes gptr’s configuration still needs your approval, except in yolo mode.

Call tools as R functions

The tool listing reports each tool’s R signature. Use the names and parameters it actually returns; search below is illustrative and must exist on your server:

peter$help("catalog/search")
result = peter$mcp$catalog$search(query = "normalization")
str(result)

The first call connects if necessary. Server and tool names are normalized into R member names; use the listed signature, or backticks for names that need them. Structured results become R values when possible; otherwise calls return text. A server-reported tool error becomes an R error. Filter a large result before printing or passing it to a model.

Tool arguments cross the connection as serialized data; an external server does not share R’s object bindings. Serving R below lets another agent request computation on live local objects.

Choose a model in Language models, then make an ordinary request. The model uses the same functions inside its r tool:

peter("Find normalization references using the catalog MCP server.")

MCP tools called by model code pass gptr’s permission policies. Server descriptions and results are external data. Read-only annotations lower risk only when the server’s annotations are explicitly trusted; a server calling itself read-only is not a permission grant. To trust them, add "trusted": true to the server’s entry in the user mcp.json (honored nowhere else); the trusted column of gptr_mcp() shows it. User calls to a peter$ helper execute directly, so review their side effects yourself.

The public client currently exposes MCP tools. It does not provide a separate public API for listing or reading MCP resources or invoking MCP prompts. A server may offer those actions as tools, in which case call the advertised tool signature. See Tools and artifacts for gptr’s own file and output helpers.

Authenticate an HTTP server

For an OAuth-capable HTTP server, sign in from an interactive R session:

gptr_login("mcp:catalog-http")
gptr_logout("mcp:catalog-http")

method = "oauth" requests the browser flow; "key" requests masked key entry when supported. The server must support the chosen authentication method. A model tool call does not open a browser for you; an authentication error names the sign-in function to run. Credentials are stored separately from the MCP configuration. A stdio server takes credentials from its env placeholders, or from gptr_login("mcp:<server>", slot = "VAR") for a declared secret entry such as VAR = "${VAR}": the value reaches only that server’s process. A change to the server’s configuration or executable asks you to log in again; changing R’s working directory or an environment variable does not.

Serve your R session

gptr_mcp_serve(tools, envir, port = NULL, stop = FALSE, mode = NULL, advertise = FALSE) exposes a subset of inspect, r, read, edit and write from the current R process. It requires the optional packages httpuv, later and openssl. inspect runs R code only when gptr classifies it as read-only (risk level 0, see gptr_risk()) and refuses anything else without running it, so a client can run it without asking you; r runs what your permission settings allow. Choose the environment whose objects the other agent should be able to inspect or change:

workspace = new.env()
workspace$measurements = data.frame(value = c(2, 3, 5))
server = gptr_mcp_serve(tools = c("r", "read"), envir = workspace)
server$url
server$config$codex
server$stop()

The handle provides $url, $port, $token_env, $config and $stop(). $config contains client snippets for Codex, Claude Code, Claude Desktop and Cursor. Printed snippets redact the token; as.character(server$config$claude_code) produces the actual configuration text for deliberate copying. Treat that text as a credential. The Codex snippet supplies $args and $env for the client process; it is not a command to paste without its environment.

One server runs per R process, bound to 127.0.0.1 with a bearer token. It serves requests at R’s top-level idle prompt or during an outermost gptr wait. Serving pauses while Peter’s own prompt waits, in every console, while other R code runs, and during nested tool waits. Rscript, knitr, Quarto and a Jupyter kernel have no idle prompt: there a request waits for the next gptr wait, such as peter$sh() or gptr_wait(), and is not answered between Jupyter cells, so a client may time out. Serve from an interactive R console.

In Peter, enter /mcp serve to start or reuse the server and return to R’s prompt. A new server uses the chat’s workspace and permission mode. Leave R at its prompt while the client works; resume the chat with gptr_last() |> peter(). Get the running handle and its client configuration with server = gptr_mcp_serve(); server$config. A running server retains its original workspace and mode; stop and restart it to change them. Direct gptr_mcp_serve() calls use mode, or else the configured default mode, independently of a chat’s explicit mode. Calls use a dedicated gptr session, and an action that needs a new approval is refused in a background callback. Approve a specific needed action interactively through your permission settings before retrying. In "manual" mode a client can only read, because everything else needs your approval; in "auto" mode, the default, it can also create and change objects, while critical actions are still refused.

Let local agents find the session

A client on the same computer can find a served session without your copying its address and token, for example gptr Agent in Claude Code, Codex or Biorouter (next section):

gptr_mcp_serve(envir = globalenv(), mode = "auto", advertise = TRUE)

advertise = TRUE, or a label such as advertise = "cohort study", writes a discovery record, serve-<pid>.json in file.path(tools::R_user_dir("gptr", "cache"), "mcp-serve"). It holds the address and the token, R’s process id, the working folder, the label (by default the folder’s name), the mode and the served tools. On Unix only you can read it (mode 0600 in a folder of mode 0700); on Windows your user profile’s permissions protect it. gptr removes it when the server stops, when gptr is unloaded or R exits, and removes the records of R processes that are gone when it next loads. Treat it as a credential: any program running as you can read it while the server runs, and gptr’s permission gate treats reading it as reading a secret. Its path always ends in R/gptr/mcp-serve/serve-<pid>.json, so a tool that keeps credential files away from agents can match it.

Work from Claude Code, Codex or Biorouter

gptr Agent connects an agent outside R to an advertised session. It lives in the gptragent/ folder of gptr’s repository, ships with each gptr release and runs with uv, which supplies Python when your computer has none. Install it once in the agent you use:

# Claude Code
claude plugin marketplace add Broccolito/gptr
claude plugin install gptr@gptr
# Codex (start a new thread afterwards)
codex plugin marketplace add Broccolito/gptr
codex plugin add gptr@gptr

In Biorouter, install gptr Agent from the BAAM marketplace, or gptragent.brxt from gptr’s GitHub releases with biorouter extension install gptragent.brxt. Biorouter updates it with each gptr release.

Then serve the session as above and ask the agent about your objects. It gets three tools: sessions lists the advertised sessions and attaches to one (it asks which when there are several), inspect runs code gptr classifies as read-only, and r runs other code through your permission settings in the server’s mode, returning plots as images. A bundled skill tells the model to look first, never reload data and change objects in place. With gptr 1.0 or 1.1, which cannot advertise, the sessions tool prints the line that loads gptr Agent’s attach.R helper.

The agent’s calls are recorded as Peter’s are. Each r call that ran (of one that stopped part-way, the expressions that ran) is kept on the server’s session, gptr_last(), so gptr_last() |> peter() continues after it. While gptr_doc() binds a document, the call is also written into it as a direct R line; an inspect call is left out unless it changed objects, and nothing is written in plan mode or for a refused call. gptr_export() then gives a plain script of the agent’s work:

gptr_doc("agent.R")
gptr_mcp_serve(envir = globalenv(), mode = "auto", advertise = "cohort study")
# ... the agent works in the session ...
gptr_mcp_serve(stop = TRUE)
gptr_export("agent.R", "analysis.R")

A call waits while R runs other code and gives up after 280 seconds at most (Biorouter allows 300); stopping the agent does not stop R code, so press Esc or Ctrl-C in R. The agent reaches sessions on the same computer only.

Child-process waits cooperate with the reactor. Inside an R tool, they still run neither HTTP callbacks nor sibling R tools. If a child needs this same R session’s MCP server, start it with peter$bg() and let the current R tool return before waiting for it.

Serving r permits code execution in the supplied environment; a separate environment helps organize objects but is not an operating-system sandbox. The R tool can use its already-loaded objects without an intermediate dataset file, while returned text and images leave R through the connection. See Execution model for the provider context boundary. The server exposes tools, not an MCP resource or prompt catalog. Stop it with server$stop() or gptr_mcp_serve(stop = TRUE) when finished. For interactive approvals and recorded R work, see Interactive console and Record, replay and export.