Skip to content

MCP server

The MCP server serves the deterministic workflow of ForecastingAssistant to coding agents (Claude Code, Cursor, Claude Desktop and any other MCP client). It needs the mcp extra:

pip install "skforecast-ai[mcp]"
skforecast-ai mcp --allow-dir /path/to/data

Importing skforecast_ai never imports the server or the mcp package. The options of the command are in the CLI reference; how to connect an agent and give it the skill that ships with the package, in MCP server for coding agents.

Tools

Every tool that creates an object returns a ToolResult with its id; later tools take ids, never objects, so no plan, profile or cross-validation strategy is ever accepted as JSON. The description of each tool says which id it takes, which tool takes the id it returns and which other tool to use instead when the two can be confused; the instructions the server sends when a client connects give the whole workflow and the rules on trust, cost, privacy and licenses.

Tool Takes Returns
profile data_path, target (without it, the error lists the columns of the file), date_column, series_id_column, exog_columns (the exogenous columns to use, [] for none; null for every other column), sep, decimal and thousands (the separator, the decimal mark and the thousands separator of the file; null to detect them), dayfirst (the order of the day and the month of dates that read both ways; null to tell it from the dates) a profile id
plan profile_id, steps, interval, forecaster, estimator, estimator_kwargs, lags, window_features, metric, use_exog, differentiation, calendar_features, target_transformer, dropna_from_series a plan id
refine_plan plan_id, overrides (the keys of refine_plan(); an omitted key keeps the value of the plan, and every key but forecaster, estimator and steps set to null asks for the default; a value the new forecaster or estimator cannot take is left out, with a notice that names it) a new plan id
create_cv plan_id and the arguments of create_cv() a cv id, with its cost: folds, trainings, estimator fits and the inference windows of a foundation model (at most one per series and fold), for its plan and for a compare without candidates
backtest cv_id, plan_id (another plan of the same profile; null for the plan of the strategy), confirm_cost (the number of the cost of an expensive run, once the user chose it) a backtest id; predictions and metrics in CSV files (the predictions carry the fold, the step of the horizon and the observed value y_true, whose values the summary never gives; with an interval, the metrics carry its coverage and interval_width by series, which the summary gives next to the nominal coverage; the metrics end with n_evaluated, the number of points each row is measured on, which is not a metric)
compare cv_id, candidates ([{name, config}], null for those of the profile and the plan of the strategy), interval, metric, baseline, confirm_cost (as in backtest) a comparison id, the plan of the winner in links.best_plan_id; the leaderboard (with an interval, its coverage and interval_width after the metrics, then n_evaluated, the number of points each candidate was measured on; they do not rank) and the predictions and metrics of the winner in CSV files; its cost: the folds of the strategy and the trainings, estimator fits and inference windows of all its candidates together, the baseline included, counted before they run
forecast plan_id, test_size (null to forecast the future), exog_path (one row per date of the horizon, and per series when they are stacked; for data without dates, one row per step, in order) a forecast id; predictions (and metrics in evaluation) in CSV files
get_code object_id, candidate (of a comparison) a CodeResult: the script that ran, or that would run for a plan, and requirements, the packages it needs with the versions installed where the server runs. A forecast with exog_path reads the future exogenous values from that file, by its path, with its separator, decimal mark, encoding and date format
get_failure object_id (details.failure_id of an error, or a comparison), candidate (required with a comparison) a FailureResult: the traceback and the code of a failed run
list_objects kind an ObjectList
describe_object object_id the ToolResult that created the object

compare ranks the candidates by its metric; without one, by the metric chosen for the plan of the strategy (metric of plan or refine_plan), and otherwise by the metric selected from the data (compare() in Python, which takes no plan, uses the metric selected from the data). A candidate whose arguments do not match the schema of the tool (an unknown key, a forecaster that does not exist) or that names a foundation model the server does not run is rejected with the whole call, before anything runs. A candidate that passes those checks and whose configuration is not valid (an unknown estimator, arguments the forecaster cannot use) is ranked last with its error, as in Python, and get_failure returns why it failed. compare sends a progress notification when each candidate starts and ends (2 * completed + started over 2 * total). Every tool that runs the core also sends one every 5 seconds while its worker thread is busy, to a client that asked for progress: k notifications after an event of progress p send p + k / (k + 1) (from 0, with no total, for a call without events), so the values grow without reaching the next event, and the message names what runs and for how long ("ForecasterStats: running (35 s)"). A cancelled compare stops before its next candidate; any other cancelled call waits for its work to end. A cancelled call registers nothing. While a call runs, only get_code, get_failure, list_objects and describe_object answer; the other tools wait their turn.

Foundation models only take the estimator_kwargs context_length, cross_learning, point_estimate, max_horizon, add_calendar_features and n_fourier_terms through the server: other arguments of the adapters of skforecast can send the data to a remote service or download files. The server decides from the FoundationModelInfo of skforecast: a foundation model whose license restricts commercial use (commercial_use_restricted), whose weights are gated (requires_hf_auth) or whose provider requires its own account (requires_provider_auth), or for which skforecast does not give these facts, only runs when the server was started with --allow-model and a prefix of its model ID; otherwise plan, refine_plan and compare raise model_not_allowed. The weights of a foundation model are downloaded the first time it runs: the first time a plan or a candidate uses a model whose weights are not in the local Hugging Face cache (looked up under weights_repo_id), the response carries a ModelDownloadNotice (source plan) with its license. Every other plan with a foundation model, and every comparison that ran one, carries a ModelLicenseNotice with that license, so the agent never has to state it from memory. A model whose backend keeps its weights outside that cache (weights_in_hf_cache is false, as for TabPFN) gets the notice the first time it is used, saying that the server cannot tell whether they are downloaded. Set HF_HUB_OFFLINE=1 in the environment of the server to forbid downloads from the Hugging Face Hub.

Arguments are checked strictly: an unknown argument, a number written as text or a float for an integer is an error, and so is a key of an entry of window_features other than stats and window_size. The values of estimator_kwargs are checked when the plan is made by building the estimator with them: a value that a scikit-learn estimator or the Arima of ForecasterStats rejects is invalid_argument on estimator_kwargs (LightGBM, XGBoost and CatBoost check theirs only when they fit, so a wrong value of theirs is an execution_failed). Dates are ISO 8601 text; a test_size with a time zone is placed on the dates of the data in their zone, and is invalid_argument when the data has none.

The files of a response are CSV files with the index of the data: predictions and metrics of a backtest or a forecast, leaderboard, best_predictions and best_metrics of a comparison. The metrics of a forecast with test_size have the columns of those of a backtest of the same plan: one per metric, named as the metric (mean_absolute_error, root_mean_squared_error...), and levels with the series when skforecast gives it (several series, and ForecasterDirectMultiVariate). A summary, a script or a failure too long for a response is written to a file as well.

The notices of a response are the warnings the call emitted, deduplicated, with their source: data (reading or profiling the data), plan (a warning the plan carries in plan.warnings) or runtime. Deprecation warnings go to the log of the server (stderr) instead. Besides those, a profile carries data_profile.warnings (category DataProfileWarning, source data), a plan carries them too (without those about the exogenous columns when it has use_exog: false, and with the rate of missing values computed on the target alone), with any text of plan.warnings not emitted in the call (category PlanWarning), and create_cv carries a LongTrainingWarning with the cost of a backtest of the strategy when it is an expensive run (above 50 estimator fits, or 2000 inference windows of a foundation model, one per series and fold). The server adds notices of its own, besides the ModelDownloadNotice and the ModelLicenseNotice of a foundation model: create_cv carries a CostNotice (source runtime) when the backtest of the strategy, or a compare without candidates on it, is above those thresholds, next to the warning of the library that states the cost: the notice tells the agent to stop, to tell the user the numbers and the cheaper strategies, and to run the expensive one only if they choose it, passing the number of its cost as confirm_cost (see the errors below). It names only the changes that lower that cost: an integer refit or refit=false only when the strategy trains more than once, and never for ForecasterStats (refitted in every fold) nor for a foundation model (never trained); fewer folds (skip_folds among them, except when ForecasterStats runs, which rejects it); a shorter horizon for a direct forecaster trained once; fewer series for a foundation model. The thresholds of a compare apply to all its candidates together, also with candidates: above them, the error of a call without confirm_cost gives the total and what each candidate adds; create_cv also carries a CompareCostNotice (source runtime) when a compare without candidates on the strategy would cost more than its plan; create_cv also carries a MissingValuesNotice (source data) when the backtest of its plan can fail on missing values of the target or of its exogenous columns, next to the warnings of the library that say when: the notice tells the agent that those values are the user's (ask before filling, dropping or writing any, also in a copy), that backtest checks every test fold of the target and of the exogenous columns before running and names the dates, that an estimator that accepts missing values (the one the rules choose for the data) avoids the error of a test fold predicted from a missing value but not that of a test fold that holds one, and to say it when it switches or when it forecasts without a backtest; a backtest or a forecast of a plan whose estimator was passed to plan, refine_plan or the candidates of compare instead of the one the rules recommend for its forecaster on the data (the one plan chooses, for ForecasterDirectMultiVariate sized by the dates the series share) carries an EstimatorNotRecommendedNotice (source plan) with both estimators and, when it is so, that it is the estimator that accepts missing values that the advice on the missing values names, and tells the agent to say in its answer that the estimator is not the recommended one, which one is and why it was changed; the plan of the winner of a compare without candidates (chosen and measured among candidates of the rules), ForecasterStats, a foundation model and the baseline never carry it, and the Python API does not warn about it (whoever chose the estimator there knows it); a plan (from plan or refine_plan) whose estimator needs a package that is not installed where the server runs (XGBoost, CatBoost) is still made, since its script may run elsewhere, and carries a MissingDependencyNotice (source plan) in place of the MissingBackendWarning of the library: it says that, until the package is installed, backtest and forecast fail on it with missing_dependency and its row of compare fails and is ranked last, with the advice of that error (pip, the --with of uvx, the restart); a backtest or a forecast whose metrics include MASE or RMSSE carries a MetricReferenceNotice (source runtime) saying that they are scaled by the one-step naive forecast over the observations known when each prediction is made, not by a seasonal naive forecast nor by the baseline of compare; a backtest, a forecast or a comparison that computes MAPE, sMAPE, MSE or RMSE carries a MetricUnitNotice with the unit of each one: MAPE is a fraction (1.245 is 124.5 %), sMAPE is already a percentage, from 0 to 200, MSE is in the squared units of the target and RMSE in its units; when the target of a series takes values at or around zero, MAPE gets a MetricUndefinedNotice instead, saying that its value means nothing there and is not to be reported nor converted (the default panel leaves MAPE out on such a target, and a plan that asks for it carries a warning); a backtest or a comparison with an interval whose coverage, measured by skforecast (coverage in the metrics and the leaderboard, next to the mean width interval_width), is clearly below its nominal level in a series (more than two binomial standard errors for the number of predictions, and at least 5 percentage points) carries an IntervalCoverageNotice (source runtime) in place of the IntervalCoverageWarning of the library: it names the series, or the candidates, with their coverage, and tells the agent to give the measured coverage, also in a forecast of the same plan, and never to present the interval at its nominal level; a backtest of several series (ForecasterRecursiveMultiSeries, or a foundation model) that did not forecast a series in some test fold where it has values carries a FoldsLeftOutWarning (source runtime), also in its summary, that names the series and those folds, since its metrics and the average across series use fewer folds, and a comparison carries one that names the candidates; a backtest with an estimator that accepts missing values carries one (category UserWarning) naming the missing exogenous values that a test fold reads, as forecast does with the future values; a forecast run with test_size carries a HoldoutEvaluationNotice (source runtime) with the dates it predicts, which are already in the data, so it is not presented as the forecast of the future; a forecast of the future carries an UnmeasuredPlanNotice (source runtime) when no backtest, compare or forecast with test_size of the server measured its plan, that is, the same decisions on the same profile with any interval or metric (any candidate of a comparison that ran counts, not only the winner), so it is not presented as reliable nor given the accuracy of another plan; a plan that uses exogenous variables carries a FutureExogNotice (source plan) saying that forecast needs their future values from the user, naming only the columns its model reads (ForecasterStats and a foundation model without categorical covariates leave the categorical ones out), and a forecast of a plan that leaves the exogenous columns of the data out carries an ExogLeftOutNotice. An error of the library about the content of a file (a problem of the CSV in profile; missing values that a prediction reads, or final rows without a target, in backtest, compare and forecast; the file of future exogenous values, or its absence, in forecast) has a hint of the server that leaves the values to the user: the agent tells them and asks, and never writes, fills in or drops values on its own.

compare without interval computes the interval of the plan the strategy was built for (unlike compare() in Python, whose default is no interval), so the plan of the winner keeps it; to compare without one, build the strategy from a plan without interval. Other decisions of that plan (lags, use_exog...) do not reach the other candidates: each one is planned from the profile with its own config. Without candidates, that plan also runs, with its decisions, as the row Strategy plan when it is none of the candidates of the profile (as compare() in Python does with a CVResult), and the summary names the row of that plan. With candidates, only they run: the summary names the candidate that makes the decisions of that plan, or a notice (category UserWarning, source runtime) and the summary say that it was not compared; Strategy plan is reserved, as are the names of the baseline, and a candidate with that name is invalid_argument in candidates. Each candidate goes through the checks backtest makes before running (a series that no fold forecasts, a missing value that a fold reads, a first training window too short): one that fails them is ranked last with that error, which get_failure gives, runs nothing and is left out of the cost. Candidates with different differentiation orders run on the same strategy, and backtest takes a plan_id of any order on any strategy of its profile: skforecast takes the order from the window of the forecaster, so the strategy does not carry it. The seasonal naive baseline and ForecasterStats only compute symmetric intervals (lower + upper = 1): with an asymmetric one the comparison has no baseline (its summary says why), and a ForecasterStats candidate fails and is ranked last. skforecast does not allow skip_folds for ForecasterStats either: without candidates, a strategy with skip_folds leaves it out, with a notice that says so. backtest and forecast of a ForecasterFoundation plan whose backend package is not installed where the server runs, or of a plan whose estimator needs a package that is not installed there (XGBoost, CatBoost), raise missing_dependency before running anything, on the argument that named the plan (plan_id, or cv_id for backtest without plan_id), with a hint that says how to install it with pip and with the --with of uvx and to restart the server, and details with the package and the model ID or the estimator; a candidate of compare with that model or estimator fails and is ranked last, as in Python. Without candidates, compare leaves such a candidate out (the foundation model, and XGBRegressor, which the rules propose with several series and no extra installs), with a notice (category MissingBackendWarning) and a sentence of the summary that name the package, and it is not counted in the cost; the profile still lists the estimator, since it does not depend on where the server runs.

Limits

  • The server keeps at most 256 objects and about 1 GB of them (--max-objects, --max-memory-mb); beyond that, the least recently used ones are removed and their ids raise unknown_id saying so. Objects built from a removed one keep working.
  • Ids do not survive a restart of the server: an id of a previous run raises unknown_id saying so.
  • A summary, a script or a failure longer than 20,000 characters is cut in the response, and the full text is written to the output directory (files).
  • Calls run one at a time; a call waits for the previous one to end.
  • CSV files larger than --max-file-mb (256 MB by default) are rejected before being read, and plan and refine_plan reject a steps longer than the longest series of the profile (invalid_argument). create_cv rejects skip_folds for a ForecasterStats plan, which skforecast refits in every fold, and fixed_train_size with refit false or null for any other plan, where it has no effect (invalid_argument; the Python API warns instead).
  • The output directory (--output-dir, by default a new temporary directory that is kept when the server stops) is also the working directory of the server.
  • The scripts run in the process of the server, with the permissions of the user who started it. The server trusts the agent as much as that user: it limits what the agent can read (--allow-dir) and pass, not what the scripts it builds can do.
  • The scripts of get_code and the summary of a plan (its script lists the file it reads) name the path of the data file; the other summaries, the failures and the rest of the responses do not.

Errors

A failure of a tool reaches the agent as an error result whose text is Error executing tool <name>: followed by a JSON object with code, message, field, hint and details. code is one of the codes of the core or one of the server:

code When
unknown_id The id does not exist, was removed to stay within the limits of the server (details.removed), or comes from a previous run of the server.
inconsistent_ids The plan and the cross-validation strategy passed to backtest come from different profiles.
invalid_path The path is not absolute, does not end in .csv, .tsv, .csv.gz or .tsv.gz, or holds a control character.
path_not_allowed The path is outside the directory given to --allow-dir, also after resolving symbolic links. It is checked before looking at the file, so the error does not say whether a file outside exists. Its hint names the directory and tells the agent to ask the user to copy the file there or to change --allow-dir, not to copy it itself.
url_not_allowed The path is a URL. Download the file into the allowed directory.
cost_not_confirmed backtest or compare of an expensive run without confirm_cost, or with a number that is not that of its cost (see below). Nothing ran. It is not invalid_argument on purpose: that code asks the agent to correct the argument and call again, and here the user decides.
file_too_large The CSV file (data or future exogenous values) is larger than --max-file-mb (256 MB by default; 0 for no limit). Its size is checked before reading it, and so is the size of the content of a .gz file; details has the size and the limit.
model_not_allowed A foundation model that --allow-model does not allow: its license restricts commercial use, its weights are gated, its provider requires an account, or skforecast gives no license information for it. details has its license and those facts; hint names the option to ask the user for.
data_changed The CSV file changed since it was profiled, or the data or the exogenous file changed while the server was reading it. Nothing is registered; call profile again (or the tool again, for the exogenous file). The Python API profiles such data again and runs; the server asks for a new profile, so that every id keeps describing the file it was built from.

An expensive run is refused before anything runs: a backtest above 50 estimator fits, or 2000 inference windows of a foundation model, or a compare whose candidates are above them together (the baseline included, without a candidate whose plan cannot be built or that fails the checks of backtest, which runs nothing), is a cost_not_confirmed error (field confirm_cost) unless confirm_cost is the number of its cost: its estimator fits, or its inference windows when only those are above. Its message states the cost and what each candidate adds, its hint the cheaper strategies and that the agent does not call again until the user answers, and then only if they choose that run, and details has the number (confirm_cost), the cost and, for a comparison, the cost of each candidate (candidates). In the core the error is CostNotConfirmedError, with the code invalid_argument, and it accepts confirm_cost=True (the Python API and the CLI, where a person decides); the server gives the error its own code and only takes the number, so the agent has read the cost, and a number given for another strategy, plan or candidates is refused with the new one. Below the thresholds confirm_cost is ignored. create_cv gives the number for its plan and for a compare without candidates in cost and in its CostNotice.

When a script fails (execution_failed) or every candidate of a comparison fails (all_candidates_failed), details.failure_id names the full failure, which get_failure returns: it never goes in the error itself. The error names only the type of what failed when skforecast-ai did not raise it (an error of pandas or of the estimator can quote a value of the data), as an internal_error does; an error of skforecast-ai keeps its class (InvalidInputError) and its message, also for a failed candidate. With the id of a comparison, get_failure needs the candidate; without it, the error lists the failed candidates. The id of an object that did not fail (a comparison whose candidates all ran, or any other object) is invalid_argument on object_id. The failure that get_failure returns holds the whole message, so it can quote values of the data; its traceback names the files by module, without the directory they are installed in, and the code it holds reads the data in memory and does not name the path of the data file.

An error of profile about the content of the file (repeated dates with different values, series of different frequencies) gets a hint that leaves the fix to the user: the agent must tell them and ask before writing a corrected copy. The messages of the core are forwarded as they are: they can name columns, series ids and values of the data, such as categories or dates (at most 5 values each). An error that skforecast-ai did not raise itself is an internal_error with only its type and an id (details.error_type, details.error_id): its message and traceback, which can quote a value, are written to the log of the server (stderr) with that id. The server cuts a message to 4,000 characters, a hint to 1,000 and each text of details to 500, and a response carries at most 20 notices of 1,000 characters each (notices_omitted counts the rest).

skforecast_ai.mcp.create_server

create_server(
    allow_dir,
    output_dir=None,
    max_objects=DEFAULT_MAX_OBJECTS,
    max_memory_mb=DEFAULT_MAX_MEMORY_MB,
    allow_models=(),
    max_file_mb=DEFAULT_MAX_FILE_MB,
)

Create the MCP server of skforecast-ai, without running it.

Useful to test the server in memory (mcp.Client(server)) or to run it with another transport. run_server() creates it and serves it over stdio, as the skforecast-ai mcp command does.

Parameters:

Name Type Description Default
allow_dir (str, Path)

Directory the server may read data from. Only absolute paths of CSV files inside it are accepted, also after resolving symbolic links.

required
output_dir (str, Path)

Directory of the files the server writes: predictions, metrics and leaderboards as CSV, and summaries, scripts and failures too long for a response. It is created if it does not exist. When None, a new temporary directory, kept when the server stops.

None
max_objects int

Most objects the server keeps; the least recently used ones are removed beyond it.

256
max_memory_mb int

Memory, in MB, the objects may take (an estimate); the least recently used ones are removed beyond it.

1024
allow_models iterable of str

Model ID prefixes of foundation models that the server may run although their license restricts commercial use, their weights are gated, their provider requires an account or skforecast gives no license information ('google/timesfm-3.0'). Each must start with the prefix of an adapter of skforecast. Other models run without it.

()
max_file_mb int

Largest CSV file (data or future exogenous values) the server reads, in MB, checked on the size of the file before reading it. 0 for no limit.

256

Returns:

Name Type Description
server MCPServer

Server of the mcp package with the tools of skforecast-ai.

Source code in skforecast_ai/mcp/server.py
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
def create_server(
    allow_dir: str | Path,
    output_dir: str | Path | None = None,
    max_objects: int = DEFAULT_MAX_OBJECTS,
    max_memory_mb: int = DEFAULT_MAX_MEMORY_MB,
    allow_models: Iterable[str] = (),
    max_file_mb: int = DEFAULT_MAX_FILE_MB,
) -> MCPServer:
    """
    Create the MCP server of skforecast-ai, without running it.

    Useful to test the server in memory (`mcp.Client(server)`) or to run it
    with another transport. `run_server()` creates it and serves it over
    stdio, as the `skforecast-ai mcp` command does.

    Parameters
    ----------
    allow_dir : str, Path
        Directory the server may read data from. Only absolute paths of CSV
        files inside it are accepted, also after resolving symbolic links.
    output_dir : str, Path, default None
        Directory of the files the server writes: predictions, metrics and
        leaderboards as CSV, and summaries, scripts and failures too long for
        a response. It is created if it does not exist. When None, a new
        temporary directory, kept when the server stops.
    max_objects : int, default 256
        Most objects the server keeps; the least recently used ones are
        removed beyond it.
    max_memory_mb : int, default 1024
        Memory, in MB, the objects may take (an estimate); the least
        recently used ones are removed beyond it.
    allow_models : iterable of str, default ()
        Model ID prefixes of foundation models that the server may run
        although their license restricts commercial use, their weights are
        gated, their provider requires an account or skforecast gives no
        license information (`'google/timesfm-3.0'`).
        Each must start with the prefix of an adapter of skforecast. Other
        models run without it.
    max_file_mb : int, default 256
        Largest CSV file (data or future exogenous values) the server reads,
        in MB, checked on the size of the file before reading it. 0 for no
        limit.

    Returns
    -------
    server : MCPServer
        Server of the `mcp` package with the tools of skforecast-ai.
    """

    state = _build_state(
        allow_dir, output_dir, max_objects, max_memory_mb, allow_models, max_file_mb
    )

    return _build_server(state)

skforecast_ai.mcp.run_server

run_server(
    allow_dir,
    output_dir=None,
    max_objects=DEFAULT_MAX_OBJECTS,
    max_memory_mb=DEFAULT_MAX_MEMORY_MB,
    allow_models=(),
    max_file_mb=DEFAULT_MAX_FILE_MB,
)

Run the MCP server of skforecast-ai over stdio until the client closes.

The working directory of the process becomes output_dir, so a library that writes files next to it (CatBoost writes catboost_info/) does not write them into the project of the user. As it starts serving, it starts importing pandas, scikit-learn, scipy and skforecast in a background thread, which the handshake does not need and every tool waits for. While it serves, the logger skforecast_ai.mcp writes one plain line per record to the standard error and does not pass its records to the root logger; both are restored when it returns. When the client disconnects, also during a call, it logs one line and returns instead of raising, and the standard output (the closed pipe of the client) is pointed to the null device so flushing it at exit does not fail again.

Parameters:

Name Type Description Default
allow_dir (str, Path)

Directory the server may read data from. Only absolute paths of CSV files inside it are accepted, also after resolving symbolic links.

required
output_dir (str, Path)

Directory of the files the server writes: predictions, metrics and leaderboards as CSV, and summaries, scripts and failures too long for a response. It is created if it does not exist. When None, a new temporary directory, kept when the server stops.

None
max_objects int

Most objects the server keeps.

256
max_memory_mb int

Memory, in MB, the objects may take (an estimate).

1024
allow_models iterable of str

Model ID prefixes of foundation models that the server may run although their license restricts commercial use, their weights are gated, their provider requires an account or skforecast gives no license information.

()
max_file_mb int

Largest CSV file the server reads, in MB; 0 for no limit.

256

Returns:

Type Description
None
Source code in skforecast_ai/mcp/server.py
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
def run_server(
    allow_dir: str | Path,
    output_dir: str | Path | None = None,
    max_objects: int = DEFAULT_MAX_OBJECTS,
    max_memory_mb: int = DEFAULT_MAX_MEMORY_MB,
    allow_models: Iterable[str] = (),
    max_file_mb: int = DEFAULT_MAX_FILE_MB,
) -> None:
    """
    Run the MCP server of skforecast-ai over stdio until the client closes.

    The working directory of the process becomes `output_dir`, so a library
    that writes files next to it (CatBoost writes `catboost_info/`) does not
    write them into the project of the user. As it starts serving, it starts
    importing pandas, scikit-learn, scipy and skforecast in a background
    thread, which the handshake does not need and every tool waits for.
    While it serves, the logger
    `skforecast_ai.mcp` writes one plain line per record to the standard
    error and does not pass its records to the root logger; both are
    restored when it returns. When the client disconnects, also during a
    call, it logs one line and returns instead of raising, and the standard
    output (the closed pipe of the client) is pointed to the null device so
    flushing it at exit does not fail again.

    Parameters
    ----------
    allow_dir : str, Path
        Directory the server may read data from. Only absolute paths of CSV
        files inside it are accepted, also after resolving symbolic links.
    output_dir : str, Path, default None
        Directory of the files the server writes: predictions, metrics and
        leaderboards as CSV, and summaries, scripts and failures too long for
        a response. It is created if it does not exist. When None, a new
        temporary directory, kept when the server stops.
    max_objects : int, default 256
        Most objects the server keeps.
    max_memory_mb : int, default 1024
        Memory, in MB, the objects may take (an estimate).
    allow_models : iterable of str, default ()
        Model ID prefixes of foundation models that the server may run
        although their license restricts commercial use, their weights are
        gated, their provider requires an account or skforecast gives no
        license information.
    max_file_mb : int, default 256
        Largest CSV file the server reads, in MB; 0 for no limit.

    Returns
    -------
    None
    """

    state = _build_state(
        allow_dir, output_dir, max_objects, max_memory_mb, allow_models, max_file_mb
    )
    server = _build_server(state)
    os.chdir(state.output_dir)
    # The log of the server goes to stderr in plain lines; the SDK of MCP
    # configures a handler that wraps them to the width of a terminal.
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(_OneLineFormatter())
    previous = (logger.level, logger.propagate)
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)
    logger.propagate = False
    wire = _stdout_stat()
    wire_fd = _stdout_duplicate() if sys.platform == "win32" else None
    try:
        logger.info(
            "skforecast-ai MCP server: reads CSV files in %s, writes files to %s.",
            state.allowed.path,
            state.output_dir,
        )
        # The core is imported in the background while the server answers
        # its client: the handshake and `tools/list` do not need it, and
        # starting it here instead of after the first answer costs the
        # handshake nothing measurable.
        _preload.PRELOAD.start()
        try:
            server.run("stdio")
        except BaseException as exc:
            if not _client_disconnected(exc):
                raise
            # The client went away while a call ran: nothing is left to
            # answer, so the server stops as if the client had closed it.
            logger.info("The client disconnected; the server stops.")
            _discard_stdout(wire, wire_fd)
    finally:
        if wire_fd is not None:
            try:
                os.close(wire_fd)
            except OSError:
                pass
        logger.removeHandler(handler)
        logger.setLevel(previous[0])
        logger.propagate = previous[1]

skforecast_ai.mcp.models

Classes:

Name Description
ToolResult

Envelope returned by the tools that create an object, and by

ToolNotice

A warning emitted while a tool call ran.

CodeResult

Script of an object, returned by the get_code tool.

FailureResult

Full description of a failure, returned by the get_failure tool.

ObjectInfo

An object registered in the server, as listed by list_objects.

ObjectList

Objects registered in the server, returned by list_objects.

Classes

ToolResult

Bases: BaseModel

Envelope returned by the tools that create an object, and by describe_object.

Attributes:

Name Type Description
id str

Id of the object, to pass to the tools that take it.

kind str

Kind of the object: 'profile', 'plan', 'cv', 'backtest', 'comparison' or 'forecast'.

links dict

Ids of related objects: those it was built from (profile_id, plan_id, cv_id, and parent_plan_id for a refined plan), the plan of the winner of a comparison (best_plan_id), and the comparison a winning plan comes from (comparison_id).

summary str

Plain-text description of the object (describe() of the core), cut to 20,000 characters.

summary_truncated bool

Whether summary was cut; the full text is then in files['summary'].

notices list of ToolNotice

Warnings the call emitted, the first 20 distinct ones. Deprecation warnings go to the log of the server instead, and the failures of the candidates of a comparison are in its result.

notices_omitted int

Number of distinct warnings left out of notices.

files dict

Absolute paths of the files written for the object, by role: predictions and metrics (CSV with the index) of a backtest or a forecast, leaderboard, best_predictions and best_metrics of a comparison, and summary when the summary was cut.

values_included bool

Always False: the response holds no rows of the data or of the predictions. The summary carries statistics of the predictions, the metrics and the leaderboard of a comparison; the rows are in files.

cost (dict, None)

Cost of a cross-validation strategy, a backtest or a comparison: n_folds, n_fits (trainings of the forecaster), estimator_fits (fits of an estimator, which a direct forecaster multiplies by steps) and inference_windows (the cost of a foundation model, never trained: one forecast per series and fold; 0 for the other forecasters). For a comparison, n_folds is that of the shared strategy and the other three are totals over all its candidates, the baseline included, counted before they run (a candidate that fails while it runs counts too; one whose plan cannot be built, or that fails the checks of backtest, runs nothing and does not). A cross-validation strategy also has compare_estimator_fits and compare_inference_windows, those of a comparison without candidates with it. Above 50 estimator fits, or 2000 inference windows, backtest and compare run only with confirm_cost set to the estimator fits (the inference windows, when only those are above). None for the other kinds.

changeable list of str

Arguments of refine_plan (for a plan) or of create_cv (for a cross-validation strategy) that build a variant of the object. Empty for the other kinds.

Attributes
model_config class-attribute instance-attribute
model_config = ConfigDict(frozen=True, extra='forbid')
id instance-attribute
id
kind instance-attribute
kind
links = Field(default_factory=dict)
summary instance-attribute
summary
summary_truncated class-attribute instance-attribute
summary_truncated = False
notices class-attribute instance-attribute
notices = Field(default_factory=list)
notices_omitted class-attribute instance-attribute
notices_omitted = 0
files class-attribute instance-attribute
files = Field(default_factory=dict)
values_included class-attribute instance-attribute
values_included = False
cost class-attribute instance-attribute
cost = None
changeable class-attribute instance-attribute
changeable = Field(default_factory=list)

ToolNotice

Bases: BaseModel

A warning emitted while a tool call ran.

Attributes:

Name Type Description
source str

Where the warning comes from: 'data' (reading or profiling the data), 'plan' (a warning the plan carries in plan.warnings, or the model a plan uses) or 'runtime' (any other warning of the call).

category str

Class name of the warning (e.g. 'LongTrainingWarning'), or the name of a notice of the server (e.g. 'ModelDownloadNotice', 'MetricReferenceNotice'): the reference of the MCP server lists them.

message str

Text of the warning, without the suggestion of skforecast on how to silence it, cut to 1,000 characters.

count int

Number of times the call emitted it.

Attributes
model_config class-attribute instance-attribute
model_config = ConfigDict(frozen=True, extra='forbid')
source instance-attribute
source
category instance-attribute
category
message instance-attribute
message
count class-attribute instance-attribute
count = Field(ge=1)

CodeResult

Bases: BaseModel

Script of an object, returned by the get_code tool.

Attributes:

Name Type Description
id str

Id of the object.

kind str

Kind of the object.

candidate (str, None)

Candidate of a comparison whose script it is.

code str

Python code, cut to 20,000 characters.

code_truncated bool

Whether code was cut; the full code is then in files['code'].

requirements list of str

Packages to install to run the script outside the server: those of the modules it imports and the backend of its foundation model, each with the version installed where the server runs ('skforecast==0.27.0').

files dict

Absolute path of the file with the full code, when it was cut.

Attributes
model_config class-attribute instance-attribute
model_config = ConfigDict(frozen=True, extra='forbid')
id instance-attribute
id
kind instance-attribute
kind
candidate class-attribute instance-attribute
candidate = None
code instance-attribute
code
code_truncated class-attribute instance-attribute
code_truncated = False
requirements class-attribute instance-attribute
requirements = Field(default_factory=list)
files class-attribute instance-attribute
files = Field(default_factory=dict)

FailureResult

Bases: BaseModel

Full description of a failure, returned by the get_failure tool.

Attributes:

Name Type Description
id str

Id of the failure, or of the comparison whose candidate failed.

candidate (str, None)

Candidate of the comparison that failed.

text str

Error, line and statement that failed, traceback and code that ran, cut to 20,000 characters. Like the messages of the errors, it can quote values of the data. The code that ran reads the data in memory, so it does not name the path of the data file.

text_truncated bool

Whether text was cut; the full text is then in files['failure'].

files dict

Absolute path of the file with the full text, when it was cut.

Attributes
model_config class-attribute instance-attribute
model_config = ConfigDict(frozen=True, extra='forbid')
id instance-attribute
id
candidate class-attribute instance-attribute
candidate = None
text instance-attribute
text
text_truncated class-attribute instance-attribute
text_truncated = False
files class-attribute instance-attribute
files = Field(default_factory=dict)

ObjectInfo

Bases: BaseModel

An object registered in the server, as listed by list_objects.

Attributes:

Name Type Description
id str

Id of the object.

kind str

Kind of the object.

links dict

Ids of the objects it was built from.

Attributes
model_config class-attribute instance-attribute
model_config = ConfigDict(frozen=True, extra='forbid')
id instance-attribute
id
kind instance-attribute
kind
links = Field(default_factory=dict)

ObjectList

Bases: BaseModel

Objects registered in the server, returned by list_objects.

Attributes:

Name Type Description
objects list of ObjectInfo

Registered objects, most recently used first.

max_objects int

Most objects the server keeps; the least recently used ones are removed beyond it.

max_memory_mb int

Memory, in MB, the objects may take; the least recently used ones are removed beyond it.

removed int

Number of objects removed so far to stay within those limits. A tool that receives the id of a removed object says so.

Attributes
model_config class-attribute instance-attribute
model_config = ConfigDict(frozen=True, extra='forbid')
objects instance-attribute
objects
max_objects instance-attribute
max_objects
max_memory_mb instance-attribute
max_memory_mb
removed class-attribute instance-attribute
removed = 0