LLM agents (MCP)

A context gives a model the result of an interpretation (Context export); an MCP server lets the model run the interpretation itself. Petrophys ships a Model Context Protocol (MCP) server for LLM applications such as Claude Desktop, Claude Code, Cursor and VS Code. Through it, a model loads wells, interprets them, reads the trace, plots logs and calls any public function of the library, on your machine. It uses the same workflow as the Python API.

What a model can call

Here the server runs in-process, and the MCP Python client sends the same requests a real client sends:

import tempfile

import pandas as pd
from mcp import Client
from petrophys.mcp import create_server

workspace = tempfile.TemporaryDirectory()
server = create_server(roots=[workspace.name])  # the folders the model may use

async with Client(server) as client:
    tools = (await client.list_tools()).tools
pd.DataFrame([{"Tool": tool.name, "What it does": tool.description.splitlines()[0],
               "Changes state": not tool.annotations.read_only_hint} for tool in tools])
Tool What it does Changes state
0 list_sample_wells List the bundled sample wells by collection, with what each is good for. False
1 interpretation_settings Look up interpret_well settings (name, default, unit, accepted values). False
2 load_well Load a well file and summarize it. True
3 load_sample_well Load a bundled sample well; returns the same summary as load_well. True
4 list_loaded List the wells and interpretation runs held in this session, with their ids. False
5 describe_well Summarize a loaded well again (same content as load_well) without reloading it. False
6 check_data_quality Data-quality report with a recommended fix for every problem. False
7 curve_statistics Statistics of curves over a depth window: valid count, min, P10, median, mean, P90, max. False
8 curve_values Curve values versus depth, decimated, for inspecting a short interval. False
9 interpret_well Run the full interpretation (petrophys.interpret) on a well and summarize it. True
10 interpret_wells Interpret several wells with the same settings and compare them in one call. True
11 run_workflow Run your own recipe of steps (petrophys.workflow.Workflow) on a well. True
12 workflow_step_kinds List run_workflow step kinds with their parameters and defaults. False
13 explain_step Method, input and output curves, parameters and decisions of one step of a run. False
14 summarize_zones Per-zone table of a run: top, bottom, gross, net reservoir, net pay, NTG, and PHIE, False
15 spectral_gamma Interpret spectral gamma ray (K, Th, U): Th/U depositional environment, clay index. False
16 plot_well Render a multi-track log plot (PNG) of a depth window, with formation tops. False
17 export_results Write an interpretation or workflow run to LAS, CSV or JSON. True
18 find_functions Search every public Petrophys function by what it does. False
19 describe_function Parameters of one library function and how to give each in call_function. False
20 call_function Run any public Petrophys function on a well (find_functions, describe_function). True

The server also offers the resources petrophys://guide, petrophys://settings and petrophys://workflow-steps, and an interpretation_report prompt.

Install

The server needs Python 3.10 or newer.

python -m pip install "petrophys[mcp]"
petrophys-mcp check --root /path/to/wells     # installation, folders and a test session

Connect a client on your machine

Local clients start the server themselves over stdio. Let petrophys-mcp config write the exact settings: it uses absolute paths, so it works whatever the client’s PATH is. --root names the folders the server may read wells from and write exports to (repeatable); the bundled sample wells are always readable.

petrophys-mcp config claude-code --root /path/to/wells   # prints the `claude mcp add ...` command
petrophys-mcp config claude-desktop --root /path/to/wells

Paste the printed mcpServers entry into claude_desktop_config.json and restart Claude Desktop.

petrophys-mcp config cursor --root /path/to/wells    # .cursor/mcp.json
petrophys-mcp config vscode --root /path/to/wells    # .vscode/mcp.json
petrophys-mcp config codex --root /path/to/wells     # ~/.codex/config.toml

Deploy over HTTP

Use HTTP when the model is not on your machine: a server shared by a team, a container, or a hosted model (OpenAI’s Responses API, ChatGPT connectors) that reaches the server by URL. Clients send a bearer token; the server refuses to listen beyond localhost without one. One server process holds one set of loaded wells and interpretations: every client of an HTTP server sees and can use the wells and runs of the others, so run a server per user when that matters.

petrophys-mcp serve --http --root /path/to/wells --token auto
# Petrophys MCP server (http) at http://127.0.0.1:8000/mcp   (the generated token is printed)

Add --host 0.0.0.0 to accept other machines. Behind a proxy or tunnel, pass its domain with --allowed-host. GET /healthz answers without a token.

export PETROPHYS_MCP_TOKEN=$(python -c "import secrets; print(secrets.token_urlsafe(32))")
mkdir -p wells && docker compose up -d           # uses the repository's docker-compose.yml

The container serves http://localhost:8000/mcp, reads wells from ./wells and writes exports there.

A hosted model needs a public HTTPS URL, from a reverse proxy or a tunnel to the server. Then:

petrophys-mcp config openai --url https://<your-host>/mcp --token <TOKEN>

prints the {"type": "mcp", ...} entry for tools=[...] in the Responses API. Without a public URL, examples/mcp_openai_agent.py connects an OpenAI model to a local server: python examples/mcp_openai_agent.py "Interpret sample well 30/6-5 ...".

petrophys-mcp config claude-code --url https://<your-host>/mcp --token <TOKEN>
petrophys-mcp config vscode --url https://<your-host>/mcp --token <TOKEN>
petrophys-mcp check --url https://<your-host>/mcp --token <TOKEN>

check opens a real session against the running server and reports a rejected token plainly.

Then ask, for example: “Load the sample well 30_6-5, interpret it with Rw = 0.07 ohm.m at 230 degF, and summarize net pay in the Brent Group.”

Pin the calculations

Interpretations use the library’s "current" calculations unless the settings of a tool call set calculation_profile. An evaluation harness that must reproduce the GeoLink eval package can make "geolink" the server’s default (calculation profiles):

petrophys-mcp serve --calculation-profile geolink --root /path/to/wells
PETROPHYS_CALCULATION_PROFILE=geolink petrophys-mcp serve --root /path/to/wells   # the same

For a server that a client starts, set PETROPHYS_CALCULATION_PROFILE in the environment of the client’s server entry. A calculation_profile in a tool call’s settings still wins. Only the MCP server reads the variable: pp.interpret and petrophys-context ignore it. petrophys-mcp check reports the profile the variable sets, or current.

A live session

Each call below opens its own short connection, because an open connection cannot span notebook cells. The server keeps loaded wells between calls.

from base64 import b64decode

from IPython.display import Image


async def call(tool, **arguments):
    async with Client(server) as client:
        return await client.call_tool(tool, arguments)

Load a sample well with its formations and lithology. The answer gives the well’s identifier, its logged interval, depth unit, curves and formations:

well = (await call("load_sample_well", name="30_6-5", with_geology=True)).structured_content
well["well_id"], well["top"], well["bottom"], well["depth_unit"], len(well["curves"]), len(well["formations"])
('30_6-5', 176.61, 3556.08, 'm', 20, 20)

Interpret with the Rw the user supplied, summarizing the Brent Group window. The answer also lists skipped_steps and warnings, each with its reason:

run = (await call("interpret_well", well_id="30_6-5",
                  settings={"rw": 0.07, "rw_meas_temp": "230 degF"},  # Rw (ohm.m) at 230 degF
                  summary_top=2841, summary_bottom=2958)).structured_content
run["interpretation_id"], run["status"], run["resolved"], run["net_thickness"]
('30_6-5/run-1',
 'interpreted',
 {'matrix_type': 'sandstone', 'lithology_domain': 'clastic'},
 {'gross': 117.04,
  'net_rock': 70.56,
  'net_reservoir': 57.91,
  'net_pay': 23.01,
  'depth_unit': 'm'})

assumptions says in plain words what the numbers rest on, and review_notes what to confirm with the user; this run has no review notes. The net-pay lines give the cutoffs of each lithology family and the samples left out of net reservoir and pay (evaporite, coal, halite recognized by its log response, bad hole), with the net pay each removed over the whole well, not just the summary window:

run["assumptions"] + run["review_notes"]
['Rw 0.07 ohm.m at 230 degF, given in settings; 0.06241-0.1967 ohm.m at formation temperature (Arps)',
 'Rmf 0.08 ohm.m from the LAS header at an ASSUMED 75 degF (affects SXO and invasion only)',
 'Formation temperature: linear_gradient_from_BHT, BHT 258.8 degF at 3556.08 m, surface 68 degF',
 'Matrix: sandstone (endpoints vary with the lithology log: external_lithology)',
 'Lithology domain: clastic',
 'Clay volume: linear, GR clean 20 / shale 115.313 API (picks bounded to 20/100 API)',
 'Saturation model: archie+simandoux (requested auto), m=2, n=2, a by lithology',
 'Net-pay cutoffs: clastic VCL < 0.4, PHIE > 0.08, SW < 0.6; carbonate VCL < 0.3, PHIE > 0.045, SW < 0.7',
 'Not net reservoir or pay: coal_log_signature (3.81 m of net pay removed, whole well); bad hole (53.93 m of net pay removed, whole well)']

A bad setting fails before anything runs, with a message the model can act on:

bad = await call("interpret_well", well_id="30_6-5",
                 settings={"rw": 0.07, "hc_type": "gass"})
print(bad.content[0].text)
Error executing tool interpret_well: Invalid DynamicWorkflowConfig:
  - hc_type='gass' is not valid; use one of: oil, gas (did you mean 'gas'?)

Summarize the Brent Group window:

zones = (await call("summarize_zones", interpretation_id=run["interpretation_id"],
                    top=2841, bottom=2958)).structured_content
pd.DataFrame(zones["zones"])[
    ["zone_name", "gross_thickness", "net_pay", "avg_phie", "avg_sw", "avg_vcl"]].round(3)
zone_name gross_thickness net_pay avg_phie avg_sw avg_vcl
0 2841-2958 117.04 23.01 0.216 0.254 0.059

Plot the reservoir; plot_well returns a PNG the client shows to the model and the user:

figure = await call("plot_well", target_id=run["interpretation_id"],
                    top=2841, bottom=2958, dpi=72,
                    tracks=["GAMMA / HOLE", "POROSITY", "SATURATION", "FLAGS"])
Image(data=b64decode(figure.content[0].data), width=640)

Every library function

The tools above cover the everyday work. Three more reach every other public function of the library: saturation and porosity models, estimates, classifications, calibrations, checks and plots. The server reads them from the installed library, so a function added to Petrophys can be called without a change to the server.

Find a function by what it computes. Each hit lists the inputs it needs:

found = (await call("find_functions", query="bulk volume water", limit=3)).structured_content
pd.DataFrame(found["found"])[["name", "module", "needs"]]
name module needs
0 calculate_bvw evaluation.bvw.bvw_module [phie (a curve name on the well (PHIE), or one number), sw (a curve name on the well (SW), or one number)]
1 buckles_plot visualization.charts []
2 bound_water_volume interpretation.porosity.effective_porosity [vcl (a curve name on the well (VCL) in v/v, or one number)]

Describe it. With a target_id, the answer names the curves of that well that fit each input and gives an example call:

described = (await call("describe_function", name="calculate_bvw",
                        target_id=run["interpretation_id"])).structured_content
described["example"]
{'name': 'calculate_bvw',
 'arguments': {'phie': 'PHIE', 'sw': 'SW'},
 'target_id': '30_6-5/run-1'}

Call it over the Brent Group window. A result with one value per depth sample becomes a curve on the well, and its statistics come back:

bvw = (await call("call_function", name="calculate_bvw", target_id=run["interpretation_id"],
                  arguments={"phie": "PHIE", "sw": "SW"}, top=2841, bottom=2958)).structured_content
bvw["result_id"], bvw["result"]
('fn-1',
 {'curve': 'CALCULATE_BVW',
  'valid': 768,
  'min': 0.0,
  'p10': 0.0,
  'median': 0.04367,
  'mean': 0.0592,
  'p90': 0.1465,
  'max': 0.2148})

Every result is kept under a result_id, which a later call takes as an input. Here the core plugs of the well become core data, and the core data go into a calibration against the log porosity:

core = (await call("call_function", name="core_data", target_id="30_6-5")).structured_content
calibration = (await call("call_function", name="calibrate_porosity", target_id=run["interpretation_id"],
                          arguments={"core": core["result_id"]})).structured_content
calibration["inputs"], sorted(calibration["result"])
({'well': 'the well 30_6-5/run-1 (a copy)', 'core': 'the result fn-2'},
 ['bias',
  'core_values',
  'intercept',
  'log_values',
  'n_points',
  'property_name',
  'r_squared',
  'rmse',
  'slope',
  'type'])

A plot comes back as a PNG, like plot_well’s:

pickett = await call("call_function", name="pickett_plot", target_id=run["interpretation_id"],
                     arguments={"rw": 0.07}, top=2841, bottom=2958, dpi=72)
Image(data=b64decode(pickett.content[0].data), width=480)

call_function reads each input as the kind the library declares for it:

The function takes

Give

a curve

its name on the well (its values between top and bottom), or one number used at every sample

a mask

a curve (non-zero is true) or a condition such as "VCL < 0.35 and PHIE > 0.1"

the well, its depths, a depth window

nothing: the server fills them from target_id, top and bottom (the well is passed as a copy)

a choice or a switch

one of the listed values (any case), or true/false

an object: core data, a fitted model, a calibration

the result_id of the call that made it (fn-2, or fn-2.model for a part), or JSON for a mapping, a table or a dataclass; core data can also be a core table file

a file

a path inside the allowed folders

Curves are named after the function, or store_as; an existing curve is never replaced. A well comes back as a new well id. A function that needs Python code as an input, such as a function to sample, is named as such and not called.

Every response is compact JSON that carries the well’s depth unit. Data-quality problems, such as a curve in the wrong unit, come back in warnings. The MCP tutorial adds explain_step and export_results.

Good practice and troubleshooting

Situation

What to do

Rw unknown

Rw rarely comes from logs alone. The server tells models to ask for it; give it, with its temperature, when you know it

Reviewing an answer

ask the model to report warnings and skipped_steps: they show which results rest on assumptions

A method the tools do not name

the model finds it with find_functions; describe_function shows what it needs

Whole-well totals

ask for a reservoir window (summary_top/summary_bottom) or per-formation results: one Rw serves the whole well, so shallow overburden with fresher water, where no lithology code applies, can still be flagged as marginal pay

File access

keep --root to the folders the model may use; exports overwrite files of the same name there

The Petrophys MCP server needs the MCP SDK

pip install "petrophys[mcp]" (Python 3.10+)

... is outside the folders this server may access

add the folder with --root or PETROPHYS_MCP_ROOTS (:-separated on Linux and macOS, ; on Windows)

The client shows no Petrophys tools

run petrophys-mcp check --root <folder>, then the configured command in a terminal: it should wait without errors. Logs go to standard error, which clients show in their MCP logs

HTTP clients get 401

the client must send Authorization: Bearer <token>; petrophys-mcp check --url ... --token ... confirms the token

Hosted model cannot reach the server

it needs a public HTTPS URL (proxy or tunnel); pass that domain with --allowed-host

Next

The guide ends here. The tutorials go further: tutorial 20 runs a full MCP session (load, interpret, explain, summarize, plot, export), and the foundations lessons build the interpretation one physical quantity at a time.