Skip to content

MCP reference

The spectro-kernel MCP server, version 0.8.1: 142 tools (13 session / discovery tools and 129 algorithm tools), 3 resources and 2 resource templates. This page is generated from the server at build time, so it is exactly what a client sees after tools/list and resources/list; Using it as an MCP server explains sessions, transports and the hardened HTTP mode. The same inventory, with the full JSON schemas, is available as mcp-tools.json.

How the server introduces itself

The instructions a client receives on initialize:

spectro-kernel exposes a catalogue of astronomical spectroscopy algorithms.

Typical workflow:
  1. create_session()                       -> session_id
  2. load_spectrum(session_id, path)        load a FITS/ASCII spectrum
  3. call analysis tools (normalize_polynomial, snr_der, fit_gaussian_line, ...)
     each one takes session_id and an optional params object
  4. get_session_state(session_id)          inspect accumulated results

Use list_algorithms / describe_algorithm to discover tools and their parameters, or
run_preset to execute a whole pipeline at once. The catalogue is also readable as
resources: spectro://algorithms, spectro://algorithms/{name}, spectro://recipes,
spectro://recipes/{name} and spectro://llms.txt (a short map of this server).

Session and discovery tools

These tools manage the working session (one WorkContext kept alive between calls), load spectra and expose the catalogue.

create_session

Create a new working session and return its id.

Every other tool needs a session_id. Call this first.

This tool takes no arguments.

end_session

Discard a working session and free its memory.

Argument Type Required Default Description
session_id string yes -

load_spectrum

Load a spectrum file (FITS or ASCII, local path or http(s) URL) into a session.

The spectrum becomes the session's working spectrum, ready for the analysis tools.

Argument Type Required Default Description
session_id string yes -
path string yes -

load_spectrum_from_url

Download a spectrum from url and load it as the session's working spectrum.

Use after request_upload_url (with the returned download_url) or with any reachable http(s) URL. The file type is inferred from the URL suffix; pass format_hint ("fits" or "ascii") to override.

Argument Type Required Default Description
session_id string yes -
url string yes -
format_hint string - ""

request_upload_url

Return a presigned URL the client can PUT a file to, plus the GET URL.

Use this when a spectrum is too large to inline in MCP. The client uploads with HTTP PUT, then calls load_spectrum_from_url with the returned download_url. Requires SPECTRO_MCP_S3_BUCKET (+ optional endpoint) configured on the server.

Argument Type Required Default Description
session_id string yes -
filename string yes -
content_type string - "application/octet-stream"

get_session_state

Return a summary of everything currently held in a session's context.

Argument Type Required Default Description
session_id string yes -

get_spectrum_preview

Return a downsampled preview of the session's current spectrum (50 samples).

Argument Type Required Default Description
session_id string yes -

get_spectrum_data

Return the session spectrum as JSON arrays, at most max_points samples.

Heavier than get_spectrum_preview — use this when the caller needs to plot or re-analyse the spectrum client-side and the 50-point preview is too coarse. Returns {wavelength, flux, uncertainty, wavelength_unit, flux_unit, meta, downsampled, npix_total, npix_returned, stride}. Spectra longer than max_points (default 20000) are stride-downsampled (every k-th sample) and flagged downsampled: true; pass max_points=0 to get every pixel.

Argument Type Required Default Description
session_id string yes -
max_points integer | null - 20000

list_algorithms

List the available spectroscopy algorithms, optionally filtered by category.

Argument Type Required Default Description
category string | null - null

describe_algorithm

Return the full details (parameters, inputs, outputs) of one algorithm.

Argument Type Required Default Description
name string yes -

get_algorithm_source

Return the source code of one algorithm's wrapper class.

Useful when the agent (or its user) wants to audit what the wrapper does — especially for algorithms backed by an external library (astropy, easyspec, scipy). The response carries the repository- relative path, a GitHub permalink, the declared backend, and the source as a UTF-8 string. The absolute path on disk (path) is only filled in when the server runs locally (stdio mode).

Argument Type Required Default Description
name string yes -

list_presets

List every preset available on this server (bundled + installed collections).

This tool takes no arguments.

run_preset

Run a complete preset pipeline against a session's context in one call.

variables binds the preset's declared variables (its instrument / observer profile); list_presets says how many a preset declares and describe them via the preset's page or spectro preset show.

Argument Type Required Default Description
session_id string yes -
preset_name string yes -
variables object | null - null

Algorithm tools

Every algorithm of the catalogue is a tool of the same name. All of them take the same two arguments and return the same response shape; the algorithm's parameters go in params and are documented on its page (the tool description carries the same text).

Argument Type Required Default Description
session_id string yes -
params object | null - null

Response (outputSchema is an open object; the fields are always these):

{
  "algorithm": "<name>",
  "success": true,
  "message": "<human-readable summary or null>",
  "error": "<error message when success is false, else null>",
  "metrics": {
    "<metric>": 0.0
  },
  "artifacts": {
    "<key>": "<JSON-safe value>"
  },
  "context": {
    "has_spectrum": true,
    "metrics": {},
    "line_fits": [],
    "n_history": 0
  }
}

metrics is the session's whole metrics dict after the run (not only this tool's), context is WorkContext.summary(). Non-finite numbers are serialised as null.

Input / output

Tool What it does Algorithm page
read_ascii_spectrum Read a 1D spectrum from a two- or three-column text file. read_ascii_spectrum
read_echelle_fits Read a multi-order échelle FITS file into ctx.spectra. read_echelle_fits
read_fits Read a 1D spectrum from a FITS file (local path or http(s) URL). read_fits
read_sdss_spectrum Read an SDSS-format spectrum (spec-*.fits) into ctx.spectrum. read_sdss_spectrum
read_votable_spectrum Read a 1D spectrum from a VOTable file (the IVOA Virtual Observatory format). read_votable_spectrum

Master frames

Tool What it does Algorithm page
bias_combine Combine a stack of bias frames into one master bias. bias_combine
bias_combine_easyspec Combine bias frames into a master bias via easyspec.cleaning.master. bias_combine_easyspec
dark_combine Combine a stack of dark frames into a master dark. dark_combine
dark_combine_easyspec Combine dark frames into a master dark via easyspec.cleaning.master. dark_combine_easyspec
flat_combine Combine a stack of flat frames into a master flat (raw, not normalised). flat_combine
flat_combine_easyspec Combine flat frames into a master flat via easyspec.cleaning.master. flat_combine_easyspec

Preprocessing (2-D image)

Tool What it does Algorithm page
correct_slant_affine Make monochromatic lines parallel to the rows by a horizontal shear. correct_slant_affine
correct_smile_polynomial Undo smile curvature via the Schroeder even-order expansion. correct_smile_polynomial
correct_tilt_affine Re-align the slit with the detector columns by a vertical shear. correct_tilt_affine
dark_subtract Subtract a master dark from ctx.image. dark_subtract
denoise_gaussian_2d Separable isotropic Gaussian smoothing of ctx.image. denoise_gaussian_2d
denoise_median_2d Square median filter over ctx.image, optionally banded by rows. denoise_median_2d
flat_normalize Divide ctx.image by a master flat normalised to unity. flat_normalize
flat_normalize_easyspec Flat-field correct a science frame via cleaning.flatten. flat_normalize_easyspec
outlier_rejection_mad_adaptive Replace pixels whose deviation from a local median exceeds threshold·MAD. outlier_rejection_mad_adaptive
subtract_bias Subtract the master bias (or a constant bias level) from ctx.image. subtract_bias
subtract_bias_easyspec Subtract a master bias from a single science frame via cleaning.debias. subtract_bias_easyspec
subtract_dark_easyspec Subtract a master dark from a science frame via cleaning.sub_dark. subtract_dark_easyspec
subtract_sky_2d Subtract a per-column sky model fitted from off-trace rows of ctx.image. subtract_sky_2d

Cosmic-ray rejection

Tool What it does Algorithm page
clip_cosmic_rays Detect and replace cosmic-ray hits on ctx.image. clip_cosmic_rays
cosmic_ray_remove_easyspec Cosmic-ray (and optional gain) correction via CR_and_gain_corrections. cosmic_ray_remove_easyspec

Extraction (2-D to 1-D)

Tool What it does Algorithm page
detect_trace Detect the spectral trace on ctx.image and expose it on ctx.extras["trace"]. detect_trace
extract_sky_lateral_bands Median-combine two off-trace sky bands into a 1D pixel-axis reference. extract_sky_lateral_bands
extract_spectrum_boxcar Trace (easyspec) + pure-numpy aperture extraction on ctx.image. extract_spectrum_boxcar
extract_spectrum_easyspec Trace and extract a 1D spectrum from a 2D frame via easyspec. extract_spectrum_easyspec
extract_spectrum_optimal Optimal (Horne 1986) aperture extraction of ctx.image. extract_spectrum_optimal
extract_spectrum_sum Extract a 1D spectrum from ctx.image by summing across the trace. extract_spectrum_sum

Wavelength calibration

Tool What it does Algorithm page
fit_emission_lines_gaussian Measure sub-pixel centroids of several emission lines at once. fit_emission_lines_gaussian
match_lamp_lines Auto-identify arc-lamp lines against the bundled NIST atlas. match_lamp_lines
measure_arc_geometry Measure smile_radius + slant_deg from an arc-lamp 2-D image. measure_arc_geometry
reidentify_arc_features Re-anchor stored (pixel, λ) arc features onto a fresh arc exposure. reidentify_arc_features
wavelength_calibrate_easyspec Fit a wavelength polynomial via extraction.wavelength_calibration and apply it. wavelength_calibrate_easyspec
wavelength_calibrate_polynomial Fit a polynomial to (pixel → wavelength) pairs and apply it to the spectrum. wavelength_calibrate_polynomial
wavelength_calibration_in_situ Refine the wavelength zero-point from simultaneously-acquired sky lines. wavelength_calibration_in_situ
wavelength_calibration_solar Calibrate a solar spectrum from built-in Fraunhofer line wavelengths. wavelength_calibration_solar

Flux calibration

Tool What it does Algorithm page
flux_calibrate_easyspec Flux-calibrate ctx.spectrum via a standard-star observation. flux_calibrate_easyspec
response_from_standard Derive the instrumental response curve from a standard-star observation. response_from_standard

Continuum

Tool What it does Algorithm page
compare_normalisations Run every continuum-normalisation method on ctx.spectrum and collect them. compare_normalisations
normalize_edges Normalise a spectrum using a continuum fitted only on its line-free edges. normalize_edges
normalize_max Normalise a spectrum by dividing the flux by its maximum value. normalize_max
normalize_percentile Normalise a spectrum by dividing the flux by a high percentile of itself. normalize_percentile
normalize_polynomial Normalise the continuum to unity with a sigma-clipped polynomial fit. normalize_polynomial
normalize_spline Normalise the continuum with an IRAF-style iteratively clipped cubic spline. normalize_spline
normalize_to_region Divide the flux by its NaN-safe mean over [wave_lo, wave_hi]. normalize_to_region
subtract_continuum Subtract a sigma-clipped polynomial continuum, leaving the line residual. subtract_continuum

Smoothing

Tool What it does Algorithm page
compare_smoothings Run every smoothing kernel on ctx.spectrum and collect the results. compare_smoothings
smooth_gaussian Smooth a spectrum by convolution with a Gaussian kernel. smooth_gaussian
smooth_savgol Smooth a spectrum with a Savitzky-Golay filter. smooth_savgol

Resampling

Tool What it does Algorithm page
resample_flux_conserving Resample onto a new wavelength grid while preserving integrated flux. resample_flux_conserving
resample_linear Resample a spectrum onto a uniform wavelength grid by linear interpolation. resample_linear

Transforms

Tool What it does Algorithm page
clip_sigma Remove outlier samples (cosmic rays, hot pixels) by iterative sigma clipping. clip_sigma
combine_spectra_arithmetic Add, subtract, multiply or divide ctx.spectrum by a reference. combine_spectra_arithmetic
extract_region Crop a spectrum to the wavelength window [wavelength_min, wavelength_max]. extract_region
mask_range Flag every sample inside a wavelength window as masked. mask_range

Quality / SNR

Tool What it does Algorithm page
compare_snr_methods Run every SNR estimator on ctx.spectrum and collect their numbers. compare_snr_methods
measure_resolving_power Resolving power R = λ/FWHM from Gaussian fits of the strongest isolated lamp / sky lines. measure_resolving_power
snr_der Derivative-based SNR estimator (DER_SNR, Stoehr et al. 2008). snr_der
snr_edge Estimate SNR from the flat, line-free regions at the spectrum's edges. snr_edge
snr_linear_fit Estimate SNR from the scatter around a linear fit of a continuum region. snr_linear_fit
validate_bess_header Check a FITS header against the BeSS keyword contract. validate_bess_header

Line detection

Tool What it does Algorithm page
detect_lines Detect emission/absorption peaks, optionally matched to a named catalogue. detect_lines

Line fitting

Tool What it does Algorithm page
compare_line_fits Fit one spectral line with every profile in turn and pick the best one. compare_line_fits
equivalent_width Measure a line's equivalent width without assuming a profile shape. equivalent_width
fit_gaussian_line Fit a single Gaussian (plus a linear continuum) to one spectral line. fit_gaussian_line
fit_lorentzian_line Fit a single Lorentzian (plus a linear continuum) to one spectral line. fit_lorentzian_line
fit_voigt_line Fit a single Voigt profile (plus a linear continuum) to one spectral line. fit_voigt_line
vr_ratio Violet/Red intensity ratio of a double-peaked emission line. vr_ratio

Corrections

Tool What it does Algorithm page
air_to_vacuum Convert the wavelength axis from air to vacuum wavelengths. air_to_vacuum
atmospheric_extinction_correct Remove atmospheric extinction : F_0 = F · 10^(0.4 · k(λ) · X) with a mean site curve. atmospheric_extinction_correct
barycentric_correction Compute the barycentric (or heliocentric) correction and Julian date, and shift the spectrum. barycentric_correction
deredden_interstellar Deredden a spectrum for interstellar dust : F_0 = F / 10^(−0.4 A(λ)), CCM89 / F99 / G23. deredden_interstellar
doppler_shift Doppler-shift the wavelength axis by a radial velocity. doppler_shift
extinction_correct_easyspec Apply atmospheric extinction correction to ctx.spectrum via easyspec. extinction_correct_easyspec
fit_telluric_scaling Fit the airmass that best matches a telluric template to ctx.spectrum. fit_telluric_scaling
remove_telluric_division Remove telluric absorption by dividing the science spectrum by a reference. remove_telluric_division
synth_telluric Generate a synthetic telluric transmission spectrum. synth_telluric
vacuum_to_air Convert the wavelength axis from vacuum to air wavelengths. vacuum_to_air

Radial velocity

Tool What it does Algorithm page
cross_correlate_rv Measure radial velocity by cross-correlation against a template spectrum. cross_correlate_rv
fit_keplerian_orbit Fit a single-companion Keplerian RV curve to a velocity time series. fit_keplerian_orbit
measure_radial_velocity Measure a radial velocity from the Doppler shift of a single line. measure_radial_velocity
redshift_lines Redshift z by per-line Gaussian fits against a list of rest-frame anchors. redshift_lines
rv_precision_bouchy Compute the fundamental photon-noise limit on RV precision (Bouchy 2001). rv_precision_bouchy

Time series

Tool What it does Algorithm page
box_least_squares Box least squares transit search (Kovács, Zucker & Mazeh 2002) via astropy. box_least_squares
lomb_scargle Compute a Lomb-Scargle periodogram and report the dominant period. lomb_scargle
phase_dispersion_minimization Stellingwerf (1978) phase dispersion minimization: Θ = s²/σ² over a period grid. phase_dispersion_minimization
phase_fold Phase-fold a light curve on a known period. phase_fold
temporal_variance_spectrum Temporal variance spectrum (Fullerton, Gies & Bolton 1996) of N ≥ 3 line profiles. temporal_variance_spectrum

Stacking

Tool What it does Algorithm page
merge_echelle_orders Merge every Spectrum1D in ctx.spectra into a single ctx.spectrum. merge_echelle_orders
stack_spectra Combine every spectrum in ctx.spectra into one stacked spectrum. stack_spectra

Embeddings

Tool What it does Algorithm page
embed_band_power Embed a spectrum as the integrated flux in N adjacent wavelength bands. embed_band_power
embed_continuum_subtracted Subtract the polynomial continuum, then embed the line residual. embed_continuum_subtracted
embed_lick_indices Embed a spectrum as the canonical Lick/IDS line-strength indices. embed_lick_indices
embed_log_lambda Resample to a uniform log-λ grid, then embed. embed_log_lambda
embed_pretrained Embed a spectrum with a local pre-trained PyTorch model. embed_pretrained
embed_remote Embed a spectrum via a remote HTTPS inference endpoint. embed_remote
embed_spectrum Compute a fixed-length, L2-normalised embedding of a spectrum. embed_spectrum
embed_wavelets Embed a spectrum via a truncated discrete wavelet transform. embed_wavelets

Nebular diagnostics

Tool What it does Algorithm page
balmer_decrement_extinction Nebular extinction c(Hβ), E(B−V) and A_V from the observed Hα/Hβ Balmer decrement. balmer_decrement_extinction
bpt_line_ratios Measure BPT line ratios + classify a galaxy (HII / Composite / Seyfert / LINER). bpt_line_ratios
oiii_electron_temperature Electron temperature Te (K) from the [O III] (λ4959+λ5007)/λ4363 ratio. oiii_electron_temperature
sii_electron_density Electron density n_e (cm⁻³) from the [S II] λ6716/λ6731 ratio. sii_electron_density

Kinematics

Tool What it does Algorithm page
rotation_curve Projected long-slit rotation curve v_los(r) from Hα per slit offset. rotation_curve
vsini_fourier v sin i from the first zero of the Fourier transform of one line profile. vsini_fourier

Spectral classification

Tool What it does Algorithm page
classify_template_chi2 Spectral classification by χ² against a Pickles-style template atlas. classify_template_chi2

Stellar activity

Tool What it does Algorithm page
activity_index_caii_hk Mount Wilson S index from the Ca II H & K cores, plus R'_HK when B−V is given. activity_index_caii_hk
activity_index_halpha Hα activity index : mean core flux over the sum of two reference-band fluxes. activity_index_halpha
ccf_bisector Bisector of a CCF (or one line) and the Queloz et al. 2001 Bisector Inverse Slope. ccf_bisector

External catalogues

Tool What it does Algorithm page
gaia_query Cone-search the Gaia archive around ICRS coordinates. gaia_query
simbad_query Resolve an object name against SIMBAD and store the record in the context. simbad_query
standard_star_reference Load a spectrophotometric standard (CALSPEC or Pickles template) as the catalogue spectrum. standard_star_reference
vizier_query Look up an object in VizieR — the CDS table service. vizier_query

Visualisation

Tool What it does Algorithm page
plot_3d_surface_plotly Render every spectrum in ctx.spectra as one row of a 3D surface. plot_3d_surface_plotly
plot_animation_plotly Render an animated Plotly figure that plays through ctx.spectra. plot_animation_plotly
plot_dynamic_spectrum Render every spectrum in ctx.spectra as one row of a 2D heatmap. plot_dynamic_spectrum
plot_overlay_plotly Render every spectrum in ctx.spectra overlaid on one Plotly figure. plot_overlay_plotly
plot_spectrum_plotly Render ctx.spectrum as a Plotly line figure. plot_spectrum_plotly

Export

Tool What it does Algorithm page
export_csv Export ctx.spectrum to a CSV file. export_csv
export_fits Export ctx.spectrum to a FITS file. export_fits
export_fits_bess Export ctx.spectrum as a BeSS / ARAS-compliant FITS image. export_fits_bess
export_hdf5 Export ctx.spectrum to an HDF5 file. export_hdf5
export_votable Export ctx.spectrum to a VOTable file (IVOA exchange format). export_votable

Advanced

Tool What it does Algorithm page
aperture_photometry Differential aperture photometry on ctx.image (photutils). aperture_photometry
disentangle_sb2 Separate the spectra of the two components of an SB2 spectroscopic binary. disentangle_sb2
doppler_tomogram Doppler tomogram of a binary from N phase-resolved spectra. doppler_tomogram

Resources

Read-only views of the catalogue, backed by the same builders as the published JSON (algorithms.json, presets.json). Read them with resources/read; no session is needed.

URI Content type What it returns
spectro://algorithms application/json The whole algorithm catalogue as JSON (same shape as docs/ai/algorithms.json): every algorithm with its parameters, defaults, inputs, outputs, references and call shapes.
spectro://recipes application/json Every recipe (preset) discoverable on this server as JSON (same shape as docs/ai/presets.json): variables, steps, status, references.
spectro://llms.txt text/plain Plain-text map of this server for language models: what it is, the tool families, the resources, links to the documentation.
spectro://algorithms/{name} application/json One algorithm's catalogue entry, by name (see spectro://algorithms).
spectro://recipes/{name} application/json One recipe's catalogue entry, by name (see spectro://recipes).

An unknown {name} returns an MCP error whose message names the catalogue resource to read; in shared (HTTP) mode a recipe found on SPECTRO_PRESET_PATH reports its source as path rather than the directory.

Error behaviour

  • A missing or expired session_id, a refused path or URL and an unknown algorithm or recipe raise a tool error whose message reaches the client even when the server masks unexpected exceptions (--http).
  • A load that fails (unreadable file, empty spectrum, refused URL) returns {"error": "..."} instead of raising, so the agent can recover.
  • An algorithm that fails returns success: false with error set; the session context is unchanged.
  • In --http mode unexpected exceptions are masked (mask_error_details), local filesystem paths are refused and URLs go through the SSRF guard.

The same catalogue, every door

The tools are generated from the registry, so the Python API and the CLI expose the same algorithms with the same parameters.