Skip to main content
Glama
gabrielserrao

pyResToolbox MCP Server

rachford_rice_flash

Calculate vapor fraction and phase compositions for two-phase equilibrium in petroleum systems using the Rachford-Rice equation. Essential for separator design and compositional analysis.

Instructions

Solve Rachford-Rice equation for vapor-liquid equilibrium.

PHASE BEHAVIOR TOOL - Calculates vapor fraction (beta) and phase compositions for two-phase flash at specified pressure and temperature. Essential for compositional analysis, separator design, and phase behavior calculations.

Parameters:

  • zis (list, required): Overall mole fractions of components (0-1). Must sum to 1.0. Length must match Kis. Example: [0.5, 0.3, 0.2] for 3 components.

  • Kis (list, required): Equilibrium ratios (K-values) for components. Ki = yi/xi where yi = vapor mole fraction, xi = liquid mole fraction. Length must match zis. Example: [2.5, 1.8, 0.6]. K > 1 = light component.

Rachford-Rice Equation: Σ[zi(Ki - 1) / (1 + β(Ki - 1))] = 0

Where:

  • zi = overall mole fraction of component i

  • Ki = equilibrium ratio (yi/xi) for component i

  • β = vapor mole fraction (0 to 1)

Phase Behavior:

  • β = 0: All liquid (subcooled)

  • 0 < β < 1: Two-phase (vapor + liquid)

  • β = 1: All vapor (superheated)

K-Value Behavior:

  • K > 1: Component prefers vapor phase (light components)

  • K = 1: Component equally distributed (critical component)

  • K < 1: Component prefers liquid phase (heavy components)

  • K-values depend on pressure, temperature, and composition

Solution Method: Iterative Newton-Raphson method with bounds checking (0 ≤ β ≤ 1). Converges rapidly for well-posed problems. Typically converges in 3-10 iterations.

Applications:

  • Gas-Oil Separator Design: Determine separator conditions for phase split

  • Phase Envelope: Calculate bubble/dew points and phase boundaries

  • Compositional Simulation: Flash calculations in compositional models

  • EOS Flash: Solve equation of state flash calculations

  • Surface Facility Design: Design separation trains and processing units

  • Material Balance: Phase split in material balance calculations

Returns: Dictionary with:

  • vapor_fraction (float): Vapor mole fraction β (0-1)

  • liquid_composition (list): Liquid phase mole fractions xi

  • vapor_composition (list): Vapor phase mole fractions yi

  • method (str): "Rachford-Rice (Newton-Raphson)"

  • note (str): Interpretation guidance

  • inputs (dict): Echo of input parameters

Common Mistakes:

  • Mole fractions don't sum to 1.0 (must normalize)

  • K-values don't match components (length mismatch)

  • K-values at wrong P-T conditions (must match flash conditions)

  • Using weight fractions instead of mole fractions

  • Not accounting for non-hydrocarbon components

  • K-values from wrong correlation/EOS

Example Usage:

{
    "zis": [0.5, 0.3, 0.2],
    "Kis": [2.5, 1.8, 0.6]
}

Result: β ≈ 0.3-0.5 (two-phase), with light components enriched in vapor, heavy components enriched in liquid.

Note: Rachford-Rice equation assumes ideal mixing. For real systems, K-values must account for non-ideality (activity coefficients, fugacity). K-values are typically obtained from EOS (Peng-Robinson, Soave-Redlich-Kwong) or correlations (Wilson, Standing). Always ensure K-values match flash conditions.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
requestYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The main handler function for the 'rachford_rice_flash' tool. It is decorated with @mcp.tool() and implements the core logic by calling simtools.rr_solver with the request parameters and formatting the response.
    @mcp.tool()
    def rachford_rice_flash(request: RachfordRiceRequest) -> dict:
        """Solve Rachford-Rice equation for vapor-liquid equilibrium.
    
        **PHASE BEHAVIOR TOOL** - Calculates vapor fraction (beta) and phase compositions
        for two-phase flash at specified pressure and temperature. Essential for
        compositional analysis, separator design, and phase behavior calculations.
    
        **Parameters:**
        - **zis** (list, required): Overall mole fractions of components (0-1).
          Must sum to 1.0. Length must match Kis. Example: [0.5, 0.3, 0.2] for 3 components.
        - **Kis** (list, required): Equilibrium ratios (K-values) for components.
          Ki = yi/xi where yi = vapor mole fraction, xi = liquid mole fraction.
          Length must match zis. Example: [2.5, 1.8, 0.6]. K > 1 = light component.
    
        **Rachford-Rice Equation:**
        Σ[zi(Ki - 1) / (1 + β(Ki - 1))] = 0
    
        Where:
        - zi = overall mole fraction of component i
        - Ki = equilibrium ratio (yi/xi) for component i
        - β = vapor mole fraction (0 to 1)
    
        **Phase Behavior:**
        - β = 0: All liquid (subcooled)
        - 0 < β < 1: Two-phase (vapor + liquid)
        - β = 1: All vapor (superheated)
    
        **K-Value Behavior:**
        - K > 1: Component prefers vapor phase (light components)
        - K = 1: Component equally distributed (critical component)
        - K < 1: Component prefers liquid phase (heavy components)
        - K-values depend on pressure, temperature, and composition
    
        **Solution Method:**
        Iterative Newton-Raphson method with bounds checking (0 ≤ β ≤ 1).
        Converges rapidly for well-posed problems. Typically converges in 3-10 iterations.
    
        **Applications:**
        - **Gas-Oil Separator Design:** Determine separator conditions for phase split
        - **Phase Envelope:** Calculate bubble/dew points and phase boundaries
        - **Compositional Simulation:** Flash calculations in compositional models
        - **EOS Flash:** Solve equation of state flash calculations
        - **Surface Facility Design:** Design separation trains and processing units
        - **Material Balance:** Phase split in material balance calculations
    
        **Returns:**
        Dictionary with:
        - **vapor_fraction** (float): Vapor mole fraction β (0-1)
        - **liquid_composition** (list): Liquid phase mole fractions xi
        - **vapor_composition** (list): Vapor phase mole fractions yi
        - **method** (str): "Rachford-Rice (Newton-Raphson)"
        - **note** (str): Interpretation guidance
        - **inputs** (dict): Echo of input parameters
    
        **Common Mistakes:**
        - Mole fractions don't sum to 1.0 (must normalize)
        - K-values don't match components (length mismatch)
        - K-values at wrong P-T conditions (must match flash conditions)
        - Using weight fractions instead of mole fractions
        - Not accounting for non-hydrocarbon components
        - K-values from wrong correlation/EOS
    
        **Example Usage:**
        ```python
        {
            "zis": [0.5, 0.3, 0.2],
            "Kis": [2.5, 1.8, 0.6]
        }
        ```
        Result: β ≈ 0.3-0.5 (two-phase), with light components enriched in vapor,
        heavy components enriched in liquid.
    
        **Note:** Rachford-Rice equation assumes ideal mixing. For real systems,
        K-values must account for non-ideality (activity coefficients, fugacity).
        K-values are typically obtained from EOS (Peng-Robinson, Soave-Redlich-Kwong)
        or correlations (Wilson, Standing). Always ensure K-values match flash conditions.
        """
        # Solve Rachford-Rice
        iteration, xi, yi, beta, err = simtools.rr_solver(
            zi=request.zis,
            ki=request.Kis,
        )
    
        return {
            "vapor_fraction": float(beta),
            "liquid_composition": [float(x) for x in xi],
            "vapor_composition": [float(y) for y in yi],
            "method": "Rachford-Rice (Newton-Raphson)",
            "inputs": request.model_dump(),
            "note": "Vapor fraction (beta) ranges from 0 (all liquid) to 1 (all vapor)",
        }
  • Pydantic model defining the input schema for the rachford_rice_flash tool, including validation for mole fractions zis and K-values Kis.
    class RachfordRiceRequest(BaseModel):
        """Request model for Rachford-Rice flash calculation."""
    
        model_config = ConfigDict(
            json_schema_extra={
                "example": {
                    "zis": [0.5, 0.3, 0.2],
                    "Kis": [1.5, 0.9, 0.3],
                }
            }
        )
    
        zis: List[float] = Field(..., min_length=2, description="Overall mole fractions")
        Kis: List[float] = Field(..., min_length=2, description="K-values (yi/xi)")
    
        @field_validator("zis", "Kis")
        @classmethod
        def validate_composition(cls, v):
            """Validate composition arrays."""
            if not all(val >= 0 for val in v):
                raise ValueError("All values must be non-negative")
            return v
    
        @field_validator("zis")
        @classmethod
        def validate_sum(cls, v):
            """Validate sum of mole fractions."""
            total = sum(v)
            if not (0.99 <= total <= 1.01):
                raise ValueError(f"Mole fractions must sum to 1.0 (got {total})")
            return v
  • The registration of simtools tools, including rachford_rice_flash, by calling register_simtools_tools(mcp) in the main MCP server setup.
    from .tools.simtools_tools import register_simtools_tools
    from .tools.brine_tools import register_brine_tools
    from .tools.layer_tools import register_layer_tools
    from .tools.library_tools import register_library_tools
    
    register_oil_tools(mcp)
    register_gas_tools(mcp)
    register_inflow_tools(mcp)
    register_simtools_tools(mcp)
  • The register_simtools_tools function that defines and registers the rachford_rice_flash tool using the @mcp.tool() decorator.
    def register_simtools_tools(mcp: FastMCP) -> None:
        """Register all simulation tools with the MCP server."""
    
        @mcp.tool()
        def generate_rel_perm_table(request: RelPermTableRequest) -> dict:
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description fully discloses behavioral traits. It explains the solution method (Newton-Raphson with bounds checking), convergence behavior (3-10 iterations), assumptions (ideal mixing), and dependencies (K-values from EOS or correlations). It also details the return structure and includes interpretation guidance for phase behavior (e.g., β=0 means all liquid).

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections (e.g., Parameters, Rachford-Rice Equation, Applications), but it is lengthy with some redundancy (e.g., repeating parameter details in multiple sections). However, every sentence adds value, such as explaining phase behavior or common mistakes, making it efficient despite its length.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of the tool (solving an equation with iterative methods), no annotations, and an output schema present, the description is highly complete. It covers purpose, usage, parameters, equation details, solution method, applications, returns, common mistakes, and example usage, providing all necessary context for an AI agent to use it correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 0%, so the description must compensate. It provides detailed semantics for both parameters: zis as 'Overall mole fractions of components (0-1)' with examples and constraints, and Kis as 'Equilibrium ratios (K-values) for components' with definitions and behavior explanations (e.g., K>1 for light components). This adds significant value beyond the minimal schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Solve Rachford-Rice equation for vapor-liquid equilibrium.' It specifies the verb ('solve') and resource ('Rachford-Rice equation'), and distinguishes it from siblings by focusing on flash calculations for compositional analysis, unlike tools for gas properties or oil rates.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool: 'Essential for compositional analysis, separator design, and phase behavior calculations.' It lists specific applications (e.g., gas-oil separator design, phase envelope calculations) and includes a 'Common Mistakes' section with warnings about when not to use it (e.g., mole fractions not summing to 1.0, K-values at wrong conditions).

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/gabrielserrao/pyrestoolbox-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server