from typing import Annotated, Literal from pydantic import BaseModel, Field from mcp.server import MCPServer from mcp.server.mcpserver.exceptions import ToolError from mcp.types import ToolAnnotations from suspension_tool import ride_tuning as _ride_tuning from gearing_tool import gearing_performance as _gearing_performance from exhaust_tool import exhaust_backpressure as _exhaust_backpressure from handling_tools import cornering_load_transfer as _cornering_load_transfer from handling_tools import braking_performance as _braking_performance mcp = MCPServer( "car-setup-analysis", title="Car Setup Analysis", version="1.0.0", log_level="WARNING", instructions=( "Analytical tools for road and track car setup. All inputs are SI units unless the parameter " "name says otherwise (N/mm, km/h, g). Convert user units before calling. Results are first-order " "engineering estimates: report the warnings list to the user and do not present results as test data." ), ) CALC = ToolAnnotations(read_only_hint=True, idempotent_hint=True, open_world_hint=False) def _run(fn, **kwargs): try: return fn(**kwargs) except ValueError as e: raise ToolError(str(e)) from e class RideTuningResult(BaseModel): mode: Literal["analyze_given_spring", "solve_spring_for_frequency"] = Field(description="'analyze_given_spring' or 'solve_spring_for_frequency'") spring_rate_n_per_mm: float = Field(description="Spring rate used or solved for, N/mm") wheel_rate_n_per_mm: float = Field(description="Spring rate referred to the wheel, N/mm") ride_rate_n_per_mm: float = Field(description="Wheel rate in series with tire rate, N/mm") ride_frequency_hz: float = Field(description="Undamped sprung-mass natural frequency, Hz") damped_ride_frequency_hz: float = Field(description="Damped sprung-mass frequency, Hz") wheel_hop_frequency_hz: float = Field(description="Unsprung-mass natural frequency, Hz") static_deflection_mm: float = Field(description="Corner sag under sprung weight, mm") critical_damping_wheel_n_s_per_m: float = Field(description="Critical damping at the wheel, N*s/m") damping_wheel_n_s_per_m: float = Field(description="Required damping at the wheel, N*s/m") damping_at_damper_n_s_per_m: float = Field(description="Required damper coefficient at the damper, N*s/m") ride_character: str = Field(description="Qualitative band for the ride frequency") warnings: list[str] = Field(description="Notes when the result is near or beyond a model limit") @mcp.tool(title="Ride tuning (quarter car)", annotations=CALC) def ride_tuning( sprung_mass_kg: Annotated[float, Field(ge=50, le=1000, description="Sprung mass carried by this corner, kg")], spring_rate_n_per_mm: Annotated[float | None, Field(ge=5, le=500, description="Coil spring rate at the spring, N/mm. Omit when target_frequency_hz is given.")] = None, motion_ratio: Annotated[float, Field(ge=0.3, le=1.2, description="Spring/damper travel per unit wheel travel, dimensionless")] = 1.0, unsprung_mass_kg: Annotated[float, Field(ge=10, le=100, description="Unsprung mass at this corner, kg")] = 40.0, tire_rate_n_per_mm: Annotated[float, Field(ge=100, le=500, description="Vertical tire stiffness, N/mm")] = 250.0, target_damping_ratio: Annotated[float, Field(ge=0.05, le=1.0, description="Desired damping ratio zeta, dimensionless")] = 0.3, target_frequency_hz: Annotated[float | None, Field(ge=0.5, le=5.0, description="If given, solve for the spring rate that gives this ride frequency, Hz")] = None, ) -> RideTuningResult: """Quarter-car ride tuning for one corner: wheel rate, ride rate (spring in series with tire), ride and wheel-hop frequencies, static sag, and the damper coefficient for a target damping ratio. With target_frequency_hz it solves for the spring rate instead. Assumes a linear spring, tire and damper, constant motion ratio, and no roll/pitch coupling, anti-roll bar, bump stop or aero load.""" return RideTuningResult(**_run( _ride_tuning, sprung_mass_kg=sprung_mass_kg, spring_rate_n_per_mm=spring_rate_n_per_mm, motion_ratio=motion_ratio, unsprung_mass_kg=unsprung_mass_kg, tire_rate_n_per_mm=tire_rate_n_per_mm, target_damping_ratio=target_damping_ratio, target_frequency_hz=target_frequency_hz)) class GearRow(BaseModel): gear: int = Field(description="Gear number, 1 = first") ratio: float = Field(description="Transmission ratio of this gear") overall_ratio: float = Field(description="Gear ratio x final drive") speed_at_redline_kmh: float = Field(description="Road speed at redline in this gear, km/h") peak_wheel_force_n: float = Field(description="Peak tractive force in this gear, capped by traction, N") traction_limited: bool = Field(description="True if the tires, not the engine, limit force in this gear") rpm_at_query_speed: float | None = Field(None, description="Engine rpm at query_speed_kmh; null if not requested or above redline") over_redline_at_query_speed: bool | None = Field(None, description="True if query_speed_kmh is above redline in this gear; null if not requested") class GearingResult(BaseModel): gears: list[GearRow] = Field(description="One row per gear") zero_to_100_kmh_s: float | None = Field(description="0-100 km/h time, s; null if not reached in 60 s") geared_top_speed_kmh: float = Field(description="Highest speed the gearing allows where tractive force >= resistance, km/h") top_speed_gear: int = Field(description="Gear in which the geared top speed occurs") top_speed_limited_by: Literal["drag", "redline"] = Field(description="'drag' (power-limited) or 'redline' (gearing too short)") drag_limited_top_speed_kmh: float = Field(description="Speed where wheel power at peak equals resistance power, km/h") traction_force_limit_n: float = Field(description="Maximum tractive force the driven tires can transmit, N") warnings: list[str] = Field(description="Notes when the result is near or beyond a model limit") @mcp.tool(title="Gearing and longitudinal performance", annotations=CALC) def gearing_performance( peak_power_kw: Annotated[float, Field(ge=20, le=1000, description="Peak crank power, kW (1 hp = 0.7457 kW)")], peak_power_rpm: Annotated[float, Field(ge=2000, le=12000, description="Engine speed at peak power, rpm")], vehicle_mass_kg: Annotated[float, Field(ge=500, le=3000, description="Vehicle mass with driver, kg")], gear_ratios: Annotated[list[Annotated[float, Field(ge=0.4, le=6.0)]], Field(min_length=1, max_length=10, description="Transmission ratios from 1st gear upward, strictly decreasing")], final_drive: Annotated[float, Field(ge=2, le=6, description="Final drive ratio")], redline_rpm: Annotated[float | None, Field(ge=2000, le=14000, description="Shift point, rpm; between peak_power_rpm and 1.4x it. Default 1.1x peak_power_rpm")] = None, tire_radius_m: Annotated[float, Field(ge=0.25, le=0.40, description="Loaded rolling radius, m")] = 0.31, cda_m2: Annotated[float, Field(ge=0.3, le=1.5, description="Drag coefficient x frontal area, m^2")] = 0.65, crr: Annotated[float, Field(ge=0.005, le=0.03, description="Rolling-resistance coefficient")] = 0.012, drivetrain_efficiency: Annotated[float, Field(ge=0.7, le=0.98, description="Crank-to-wheel efficiency")] = 0.85, tire_mu: Annotated[float, Field(ge=0.5, le=1.8, description="Tire-road friction coefficient")] = 1.0, driven_axle_load_fraction: Annotated[float, Field(ge=0.3, le=1.0, description="Share of weight on the driven axle(s); 1.0 = AWD")] = 0.5, query_speed_kmh: Annotated[float | None, Field(ge=5, le=400, description="Optional road speed at which to report engine rpm in every gear, km/h")] = None, ) -> GearingResult: """Longitudinal performance from engine power, gearing and vehicle data: speed in each gear at redline, engine rpm at a chosen road speed, 0-100 km/h time (time-stepped with traction limit and 0.3 s shifts), geared top speed and drag-limited top speed. Engine curve reconstructed from peak power only; level road, no wind, no tire slip or launch control.""" out = _run( _gearing_performance, peak_power_kw=peak_power_kw, peak_power_rpm=peak_power_rpm, vehicle_mass_kg=vehicle_mass_kg, gear_ratios=gear_ratios, final_drive=final_drive, redline_rpm=redline_rpm, tire_radius_m=tire_radius_m, cda_m2=cda_m2, crr=crr, drivetrain_efficiency=drivetrain_efficiency, tire_mu=tire_mu, driven_axle_load_fraction=driven_axle_load_fraction, query_speed_kmh=query_speed_kmh) rows = [] for g in out["gears"]: q = g.pop("rpm_at_query_speed", None) rows.append(GearRow(**g, rpm_at_query_speed=q if isinstance(q, (int, float)) else None, over_redline_at_query_speed=(q == "over redline") if query_speed_kmh is not None else None)) out["gears"] = rows return GearingResult(**out) class ExhaustResult(BaseModel): exhaust_mass_flow_kg_s: float = Field(description="Total exhaust mass flow, kg/s") gas_density_kg_m3: float = Field(description="Exhaust gas density at pipe temperature, kg/m^3") velocity_m_s: float = Field(description="Mean gas velocity in each pipe, m/s") mach: float = Field(description="Gas velocity / local speed of sound, dimensionless") reynolds: float = Field(description="Reynolds number in each pipe, dimensionless") friction_factor: float = Field(description="Darcy friction factor (Colebrook)") back_pressure_kpa: float = Field(description="Pressure drop through pipe, bends and components, kPa") pumping_loss_kw: float = Field(description="Engine power spent against the back pressure, kW") firing_frequency_hz: float = Field(description="Fundamental exhaust pulse (tone) frequency, Hz") warnings: list[str] = Field(description="Notes when the result is near or beyond a model limit") @mcp.tool(title="Exhaust flow and back pressure", annotations=CALC) def exhaust_backpressure( displacement_l: Annotated[float, Field(ge=0.6, le=8.0, description="Engine displacement, litres")], rpm: Annotated[float, Field(ge=800, le=9000, description="Engine speed, rpm")], pipe_diameter_mm: Annotated[float, Field(ge=25, le=130, description="Pipe inner diameter, mm (1 in = 25.4 mm)")], cylinders: Annotated[int, Field(ge=1, le=12, description="Number of cylinders")] = 4, volumetric_efficiency: Annotated[float, Field(ge=0.5, le=1.3, description="Volumetric efficiency; >1 for boosted engines")] = 0.9, air_fuel_ratio: Annotated[float, Field(ge=10, le=18, description="Air-fuel mass ratio")] = 13.0, exhaust_temp_k: Annotated[float, Field(ge=400, le=1300, description="Mean gas temperature in the pipe, K")] = 900.0, pipe_length_m: Annotated[float, Field(ge=0.3, le=8.0, description="Pipe length, m")] = 3.0, n_bends_90: Annotated[int, Field(ge=0, le=12, description="Number of 90-degree mandrel bends")] = 2, component_k: Annotated[float, Field(ge=0, le=20, description="Extra loss coefficient for muffler/cat/resonator")] = 0.0, n_pipes: Annotated[Literal[1, 2], Field(description="1 = single exhaust, 2 = dual with flow split evenly")] = 1, ) -> ExhaustResult: """Steady-flow exhaust sizing for a four-stroke engine at one rpm: mass flow, gas velocity, Mach and Reynolds numbers, Colebrook friction factor, back pressure, pumping loss and firing frequency. Real exhaust flow pulses, so peak losses exceed this mean estimate; defaults describe full load.""" return ExhaustResult(**_run( _exhaust_backpressure, displacement_l=displacement_l, rpm=rpm, pipe_diameter_mm=pipe_diameter_mm, cylinders=cylinders, volumetric_efficiency=volumetric_efficiency, air_fuel_ratio=air_fuel_ratio, exhaust_temp_k=exhaust_temp_k, pipe_length_m=pipe_length_m, n_bends_90=n_bends_90, component_k=component_k, n_pipes=n_pipes)) class WheelLoads(BaseModel): front_outer_n: float = Field(description="Front outside-wheel load, N") front_inner_n: float = Field(description="Front inside-wheel load, N") rear_outer_n: float = Field(description="Rear outside-wheel load, N") rear_inner_n: float = Field(description="Rear inside-wheel load, N") class LoadTransferResult(BaseModel): static_load_front_wheel_n: float = Field(description="Static load on each front wheel, N") static_load_rear_wheel_n: float = Field(description="Static load on each rear wheel, N") front_load_transfer_n: float = Field(description="Lateral load transfer across the front axle, N") rear_load_transfer_n: float = Field(description="Lateral load transfer across the rear axle, N") front_geometric_transfer_n: float = Field(description="Front share through the roll centre (links), N") front_elastic_transfer_n: float = Field(description="Front share through springs and anti-roll bar, N") rear_geometric_transfer_n: float = Field(description="Rear share through the roll centre (links), N") rear_elastic_transfer_n: float = Field(description="Rear share through springs and anti-roll bar, N") wheel_loads_n: WheelLoads = Field(description="Loaded wheel loads at this lateral acceleration, N") front_lltd: float = Field(description="Front lateral load transfer distribution, 0-1") balance_indicator: str = Field(description="Front LLTD compared with front weight fraction (+/-5 % band)") roll_angle_deg: float = Field(description="Body roll angle at this lateral acceleration, deg") roll_gradient_deg_per_g: float = Field(description="Body roll per g of lateral acceleration, deg/g") static_stability_factor: float = Field(description="Average track / (2 x CG height); rigid-body rollover threshold in g") warnings: list[str] = Field(description="Notes when the result is near or beyond a model limit") @mcp.tool(title="Cornering lateral load transfer", annotations=CALC) def cornering_load_transfer( vehicle_mass_kg: Annotated[float, Field(ge=500, le=3000, description="Vehicle mass with driver, kg")], lateral_accel_g: Annotated[float, Field(ge=0, le=2.0, description="Steady-state lateral acceleration, g")], front_weight_fraction: Annotated[float, Field(ge=0.3, le=0.7, description="Static weight on the front axle, fraction")] = 0.55, cg_height_m: Annotated[float, Field(ge=0.2, le=0.9, description="Centre-of-gravity height, m")] = 0.50, track_front_m: Annotated[float, Field(ge=1.0, le=2.0, description="Front track width, m")] = 1.55, track_rear_m: Annotated[float, Field(ge=1.0, le=2.0, description="Rear track width, m")] = 1.55, front_roll_center_height_m: Annotated[float, Field(ge=-0.1, le=0.3, description="Front roll-centre height, m")] = 0.05, rear_roll_center_height_m: Annotated[float, Field(ge=-0.1, le=0.3, description="Rear roll-centre height, m")] = 0.10, front_roll_stiffness_share: Annotated[float, Field(ge=0.2, le=0.8, description="Front share of total roll stiffness (springs + anti-roll bars)")] = 0.60, total_roll_stiffness_nm_per_deg: Annotated[float, Field(ge=200, le=20000, description="Total roll stiffness, N*m/deg")] = 1500.0, ) -> LoadTransferResult: """Steady-state cornering: lateral load transfer per axle split into geometric (roll-centre) and elastic (spring/anti-roll bar) parts, the four wheel loads, front lateral load transfer distribution (LLTD) as an understeer/oversteer indicator, roll angle and roll gradient, and the static stability factor. Rigid body with a straight roll axis; sprung and unsprung mass not separated; no aero, no tire model.""" out = _run( _cornering_load_transfer, vehicle_mass_kg=vehicle_mass_kg, lateral_accel_g=lateral_accel_g, front_weight_fraction=front_weight_fraction, cg_height_m=cg_height_m, track_front_m=track_front_m, track_rear_m=track_rear_m, front_roll_center_height_m=front_roll_center_height_m, rear_roll_center_height_m=rear_roll_center_height_m, front_roll_stiffness_share=front_roll_stiffness_share, total_roll_stiffness_nm_per_deg=total_roll_stiffness_nm_per_deg) return LoadTransferResult(**out) class BrakingResult(BaseModel): max_deceleration_g: float = Field(description="Highest deceleration before the first axle locks, g") braking_efficiency: float = Field(description="max_deceleration_g / tire_mu; 1.0 = both axles at the limit together") first_axle_to_lock: str = Field(description="'front' (stable, steering lost), 'rear' (unstable, spin) or 'both'") ideal_front_bias: float = Field(description="Front brake-force fraction that locks both axles together at tire_mu") installed_front_bias: float = Field(description="Installed front brake-force fraction (echo of input)") decel_at_front_lock_g: float | None = Field(description="Deceleration at which the front axle would lock; null if it never does") decel_at_rear_lock_g: float = Field(description="Deceleration at which the rear axle would lock, g") load_transfer_n: float = Field(description="Longitudinal load transfer at max deceleration, N") front_axle_load_n: float = Field(description="Front axle load at max deceleration, N") rear_axle_load_n: float = Field(description="Rear axle load at max deceleration, N") reaction_distance_m: float = Field(description="Distance travelled during driver reaction, m") braking_distance_m: float = Field(description="Distance from brake application to stop, m") stopping_distance_m: float = Field(description="Reaction distance + braking distance, m") stopping_time_s: float = Field(description="Reaction time + braking time, s") warnings: list[str] = Field(description="Notes when the result is near or beyond a model limit") @mcp.tool(title="Braking performance and brake bias", annotations=CALC) def braking_performance( vehicle_mass_kg: Annotated[float, Field(ge=500, le=3000, description="Vehicle mass with driver, kg")], speed_kmh: Annotated[float, Field(ge=10, le=300, description="Speed at brake application, km/h")], front_brake_bias: Annotated[float, Field(ge=0.4, le=0.9, description="Installed front share of total brake force, fraction")], front_weight_fraction: Annotated[float, Field(ge=0.3, le=0.7, description="Static weight on the front axle, fraction")] = 0.55, cg_height_m: Annotated[float, Field(ge=0.2, le=0.9, description="Centre-of-gravity height, m")] = 0.50, wheelbase_m: Annotated[float, Field(ge=2.0, le=3.5, description="Wheelbase, m")] = 2.65, tire_mu: Annotated[float, Field(ge=0.3, le=1.8, description="Tire-road friction coefficient (0.3 wet/snow to 1.8 slicks)")] = 1.0, reaction_time_s: Annotated[float, Field(ge=0, le=2.5, description="Driver reaction time before braking, s")] = 1.0, ) -> BrakingResult: """Straight-line braking with a fixed front/rear brake bias: dynamic axle loads, the deceleration at which each axle locks, which axle locks first, ideal bias, braking efficiency, and reaction/braking/stopping distance from a given speed. Constant friction, level road, no ABS, no aero or brake fade.""" return BrakingResult(**_run( _braking_performance, vehicle_mass_kg=vehicle_mass_kg, speed_kmh=speed_kmh, front_brake_bias=front_brake_bias, front_weight_fraction=front_weight_fraction, cg_height_m=cg_height_m, wheelbase_m=wheelbase_m, tire_mu=tire_mu, reaction_time_s=reaction_time_s)) if __name__ == "__main__": mcp.run()