
wolfram-alpha
Wolfram|Alpha queries and context retrieval.
- GitHub stars
- 103
Install
/plugin install wolfram-alpha@wolfram-agent-skillsRun it inside Claude Code after adding the marketplace with /plugin marketplace add WolframResearch/AgentTools.
Contents
Discovered from sourceSkills 5
Wolfram|Alpha
Query Wolfram|Alpha for computational answers and retrieve contextual information using semantic search.
Prerequisites
These scripts require wolframscript. If it is not installed or not on your PATH, read references/GetWolframEngine.md (relative to this skill directory) for installation instructions.
Usage
With MCP Server (preferred)
If you have Wolfram|Alpha MCP tools available in your tool list (e.g., mcp__Wolfram__WolframAlpha), use those directly. They provide richer integration and better performance than the bundled scripts.
For a richer experience, consider setting up the Wolfram MCP server. See references/SetUpWolframMCPServer.md (relative to this skill directory) for instructions.
With Bundled Scripts
If no MCP tools are available, use the bundled scripts in the scripts/ directory (relative to this skill directory). Run them with:
wolframscript -f scripts/<ScriptName>.wls <arguments>
Pass --usage to any script to see its argument documentation:
wolframscript -f scripts/<ScriptName>.wls --usage
For detailed usage, arguments, and invocation syntax for each script, see references/Scripts.md (relative to this skill directory).
Reminder: These scripts are only relevant when you do not have the equivalent MCP tool available.
Available Tools
| Script | When to use |
|---|---|
WolframAlphaContext | Retrieve contextual information about a topic via semantic search |
WolframAlpha | Query Wolfram|Alpha for computational answers and real-world data |
WolframAlphaContext
Always use WolframAlphaContext as a first step before querying WolframAlpha. It uses semantic search to retrieve relevant background information and helps ensure you have up-to-date context. The context argument should be written in natural language (not as a search query) and be as detailed as possible (up to 250 words).
If your MCP server provides a WolframContext tool, you can use that instead of WolframAlphaContext. It's effectively equivalent, except it may include additional context from Wolfram Language documentation.
WolframAlpha
Use WolframAlpha for natural language queries that need computational answers or real-world data. This is especially useful for questions about:
- Mathematics (equations, calculus, algebra, statistics)
- Science (physics, chemistry, biology, astronomy)
- Geography and demographics
- History and culture
- Finance and economics
- Unit conversions and comparisons
- Weather, dates, and time zones
Queries should be phrased in natural language, similar to how you would ask a question. For example: "population of France", "integrate sin(x) from 0 to pi", "distance from Earth to Mars".
Other Tips
- Always call
WolframAlphaContextbeforeWolframAlphato ensure you have the most up-to-date context for your query. - If a query returns unexpected results, try rephrasing it or being more specific.
- For complex mathematical expressions, use standard notation that Wolfram|Alpha understands (e.g.,
sin(x),x^2,sqrt(x)).
Wolfram Language Debugging
Verified techniques for finding out why Wolfram Language code misbehaves, checked with Wolfram 15.0 in the MCP
evaluator (both methods), wolframscript, wolfram -script and the cloud. Many standard techniques silently do nothing
in some of these environments, so read the ground rules first. Paths are relative to this skill directory.
Prerequisites
You need a Wolfram kernel. If you have neither of the following, read references/GetWolframEngine.md; to set up the
MCP server, read references/SetUpWolframMCPServer.md.
- MCP evaluator (preferred, for example
mcp__Wolfram__WolframLanguageEvaluator): a persistent kernel, so definitions made in one call can be inspected in the next. - wolframscript: a fresh kernel per run, needed for first-time effects (autoloading, package loading) and for Trace
where the MCP evaluator cannot run it.
-f file.wlprints onlyPrintoutput;-code '...'drops string quotes (printToString[expr, InputForm]). Always bound runs:timeout -s KILL 300 wolframscript -f file.wl < /dev/null.
Start here: where does the code run?
Module[{cl = StringRiffle[ToString /@ $CommandLine, " "]},
<|"Env" -> Which[
$EvaluationEnvironment === "Script", "wolframscript",
$EvaluationEnvironment === "WebEvaluation", "CloudEvaluate",
$EvaluationEnvironment === "WebAPI", "deployed API or remote MCP server",
StringContainsQ[cl, "ChatbookSandbox"], "MCP Local",
StringContainsQ[cl, "StartMCPServer"] || StringStartsQ[$Context, "Sessions`"], "MCP Session",
MemberQ[$CommandLine, "-script"], "wolfram -script",
True, $EvaluationEnvironment],
"TraceWorks" -> Trace[1 + 1] =!= {}, "Context" -> $Context, "TimeRemaining" -> Internal`TimeRemaining[]|>]
| MCP Local | MCP Session | wolframscript | cloud | |
|---|---|---|---|---|
Trace, TraceScan, On[sym] | work | record nothing | work | record nothing |
| context of typed symbols | Sessions`<id>` | Sessions`<id>` | Global` | Global` |
| state between calls | persists in a subkernel shared by all sessions | persists in the MCP server's own kernel | none | none |
$MessageList | reset per input | never reset | per script | per call |
Print, Echo | shown | shown | stdout | dropped (the remote MCP server shows Print only) |
RunProcess, LaunchKernels | blocked (protected mode) | allowed | allowed | blocked |
| file writes | only below $TemporaryDirectory | anywhere | anywhere | cloud files (remote MCP server: a throwaway directory) |
MCP Local and MCP Session are the two evaluation methods of the MCP evaluator; installed local servers use Session by
default. "Cloud" is CloudEvaluate, deployed APIs and the remote MCP server. wolfram -script, used by the TestReport
MCP tool, also records no Trace. Everything else that differs: references/Environments.md.
Ground rules
- Check
Trace[1 + 1] =!= {}before using Trace. Where it records nothing, use message handlers withStack,Internal`InheritedBlockspies or stack sampling, or run the Trace in wolframscript (more workarounds:references/TracingAndPerformance.md). - Stack frames, trace items and arguments of kernel messages are wrapped in
HoldCompleteForm(HoldFormbefore version 15). Match them with_[e_]and format withToString[Unevaluated[e], InputForm, TotalWidth -> 150]. Never extract them withFirst,[[1]]orReleaseHold: that evaluates the frame again. - Filter user frames with both user contexts:
MemberQ[{"Global`", $Context}, Context[s]]. - Each input is parsed just before it runs, so a name in the same input as the
Get/Needsthat defines it is created in your own context. An input is one line in-fscripts and in the MCP evaluator with Chatbook 2.7.28+, but the whole call with older Chatbook. PutGet/Needsin its own call and call package functions by their full names. - Evaluate code under test as
StackBegin[StackComplete[expr]].StackBegindrops the environment's wrapper frames (about 15 in wolframscript, 65 in CloudEvaluate);StackCompletekeeps your calls, which are otherwise replaced on the stack by their right-hand sides. - Return small data as the value. Raw stacks, traces and
TestReportObjects can be hundreds of KB (Shorthas no effect in the MCP evaluator or wolframscript), andPrintoutput can be lost: collect diagnostics withInternal`Bag/Internal`StuffBagand return them. - Scope every change: MCP kernels are shared. Use
Internal`HandlerBlock(notInternal`AddHandler),Internal`InheritedBlock,BlockandWithCleanup. In an MCP evaluator, never callQuit,Exit,Input,InputString,Dialog,ChoiceDialogorRun, write to"stdout", or change$RecursionLimit,$Pre,$Post,OfforSetOptionsglobally; in MCP Session this can silence or kill the server. In MCP Local, lower$RecursionLimit(even in aBlock) only after the subkernel has printed an ordinary message (1/0;in an earlier call): a first printed message under a low limit breaks$Contextfor every session. - Reproduce autoloading and package-loading problems in wolframscript: MCP kernels have many packages loaded.
- A
Throw-based probe can be swallowed byCatch[..., _]orEvaluationDatain the code under test. If the probe returns the normal result instead of your data, record without throwing. - The remote MCP server evaluates every input inside
Quiet, so handlers see every message as quieted: wrap the code under test inQuiet[expr, None, All].
Symptom → first move → reference
| symptom | first move | read in references/ |
|---|---|---|
messages (which, from where?), unexplained $Failed or Failure | WolframDebugging`CollectMessages[expr], WolframDebugging`CaptureEvaluation[expr], the recipe below | MessagesAndStacks.md |
unevaluated f[...] in the result, or the wrong rule fires | WolframDebugging`StuckCalls[result], WolframDebugging`WhyNoMatch[f[args]] | UnevaluatedCalls.md |
slow, hangs, times out; Trace options | WolframDebugging`SampleStacks[expr], WolframDebugging`TimeCalls[expr, {f, g}] (no Trace needed) | TracingAndPerformance.md |
| calls and arguments inside an evaluation; mocks (HTTP, time, randomness); a variable changes unexpectedly | WolframDebugging`LogCalls[{f, g}, expr], WolframDebugging`WithOverrides[{lhs :> rhs}, expr], WolframDebugging`WatchChanges[{x}, expr] | OverridesAndWatchpoints.md |
| definition or source file of a symbol | SymbolDefinition MCP tool, WolframDebugging`FindSymbolSource["Ctx`name"] | DefinitionsAndSource.md |
| edits have no effect, symbol undefined after loading, what got loaded? | WolframDebugging`ContextSourceInfo["Ctx`"], WolframDebugging`LoadTrace[expr] | PackageLoading.md |
| a test fails, or a test file reports 0 tests | WolframDebugging`TestFailureSummary[report], WolframDebugging`CheckTestFile[file] | Testing.md |
| parallel or asynchronous code misbehaves | WolframDebugging`ParallelCapture[f, list] | ParallelAndAsync.md |
| deployed API or HTTP request fails | URLRead[req, {"StatusCode", "Headers", "Body"}], WolframDebugging`DebugHTTPResponse[api, params] | CloudAndHTTP.md |
| works in one environment but not another, notebook-only code, crashes | WolframDebugging`EnvironmentInfo[], WolframDebugging`EnvironmentFingerprint[] | Environments.md, HeadlessAndCrashes.md |
The helper package
scripts/WolframDebugging.wl packages the recipes of this skill as tested functions with small, bounded results. Load
it in its own call (see rule 4), then call its functions by their full names:
Get["/absolute/path/to/wolfram-debugging/scripts/WolframDebugging.wl"]
WolframDebugging`CollectMessages[myFn[-1, 1]] (* in a later call *)
The helpers work in MCP Local, MCP Session, wolframscript and (most of them) CloudEvaluate; Trace-based ones return
Failure["TraceUnavailable", ...] where Trace records nothing. The remote MCP server cannot load local files: use the
recipes below there. Every function, option and result shape is in references/HelperFunctions.md.
Core recipes (no helper package needed)
The examples use these definitions:
otherFn[x_] := 1/x; myFn[a_, b_] := Table[otherFn[i], {i, a, b}]; suspectCode[] := Module[{k = 0}, While[True, k++]]
The stack at the first message
A "Message" handler receives Hold[Message[name, args...], willPrint], where willPrint is False for quieted
messages. Throwing the stack from the handler gives the call chain that led to the message:
Module[{tag, st},
st = Catch[Internal`HandlerBlock[{"Message", Replace[#, Hold[Message[_, ___], True] :> Throw[Stack[_], tag]] &},
StackBegin[StackComplete[myFn[-1, 1]]]], tag];
If[ListQ[st],
Block[{$ContextPath = Join[{"Global`", $Context}, $ContextPath]},
StringRiffle[Replace[Take[st, Position[st, _[_Message], {1}][[-1, 1]]],
_[e_] :> ToString[Unevaluated[e], InputForm, TotalWidth -> 150], {1}], "\n"]],
st]] (* st is the normal result when no message was issued *)
StackComplete[myFn[-1, 1]]
myFn[-1, 1]
Table[otherFn[i], {i, -1, 1}]
otherFn[i]
1/0
0^(-1)
Message[Power::infy, HoldCompleteForm[0^(-1)]]
Frames show expressions as they were pushed (otherFn[i], not otherFn[0]). For function names only, throw Stack[]
instead of Stack[_] and return st unformatted. Match Hold[Message[Power::infy, ___], True] for one message, and
Hold[Message[_, ___], _] on the remote MCP server. To collect all messages without stopping, use
EvaluationData[expr]["MessagesExpressions"].
Spy on, mock or override a function
Internal`InheritedBlock keeps the existing definitions and attributes and restores them when the block exits, even
on abort:
Module[{calls = Internal`Bag[], inF = False, res},
otherFn; (* evaluate the symbol first: loads an autoload stub *)
res = Internal`InheritedBlock[{otherFn},
Unprotect[otherFn];
PrependTo[DownValues[otherFn], HoldPattern[otherFn[args___] /; !inF] :>
Block[{inF = True}, Internal`StuffBag[calls, HoldComplete[args]]; otherFn[args]]];
Quiet @ myFn[-1, 1]];
{res, Internal`BagPart[calls, All]}]
(* {{-1, ComplexInfinity, 1}, {HoldComplete[-1], HoldComplete[0], HoldComplete[1]}} *)
- To mock, prepend
HoldPattern[lhs] :> fakeValueinstead. Always useHoldPatternand:>; guard recursion as shown. - For the stack when a function gets particular arguments, prepend a rule whose condition records the stack and fails,
HoldPattern[otherFn[0]] /; (Internal`StuffBag[bag, Stack[]]; False) :> Null, and run the code asStackBegin[StackComplete[...]](helper:WolframDebugging`StackAtCall[expr, otherFn[0]]). - Some changes leak out of the block:
ClearAll/Removeof the symbol wipes the outer definitions (useClearorDownValues[f] = {}), andTemporaryorLockedset inside stay set (never setLockedin a shared kernel). - Calls made from kernel C code (
Total,Sum, auto-compiledTable) and literal rules such asf[0] = 1are not seen. HTTP requests fromURLRead,URLExecuteandCloudGetall go throughURLFetch.
Why does f[args] stay unevaluated?
Keys @ DownValues[f] (* the rules, in the order they are tried *)
Flatten @ Position[Keys @ DownValues[f], lhs_ /; MatchQ[Unevaluated @ f[20.], lhs], {1}, Heads -> False]
(* which left-hand sides match (right-hand-side conditions are not checked) *)
{Context[f], Attributes[f]} (* wrong context? Hold attributes? *)
Select[Names["*`f"], ToExpression[#, InputForm, System`Private`HasAnyEvaluationsQ] &] (* shadowing contexts *)
Common causes: _Integer given a Real, a condition or PatternTest that does not return exactly True, the wrong
number of arguments, _List given an Association, HoldAll with a typed pattern, a private package symbol called
unqualified, and memoized values from an old definition.
Where is slow or hanging code spending its time?
Stack sampling works in every environment, including those where Trace records nothing:
Module[{bag = Internal`Bag[], task, res},
task = SessionSubmit[ScheduledTask[Internal`StuffBag[bag, Stack[_]], {0.25, 20}]]; (* always bound the count *)
res = TimeConstrained[StackBegin[suspectCode[]], 4, $TimedOut]; (* stay below Internal`TimeRemaining[] *)
Quiet[TaskRemove[task]];
{res, Block[{$ContextPath = Join[{"Global`", $Context}, $ContextPath]},
Replace[TakeWhile[Internal`BagPart[bag, -1], FreeQ[#, HoldPattern[bag]] &],
_[e_] :> ToString[Unevaluated[e], InputForm, TotalWidth -> 120], {1}]]}]
(* {$TimedOut, {"Module[{k = 0}, While[True, k++]]", "While[True, k$389372++]", ...}} *)
The last sample shows where the code was when time ran out; WolframDebugging`SampleStacks turns many samples into a
profile.
Read a ReadProtected definition
Prefer the SymbolDefinition MCP tool. Otherwise:
CloudPut; (* evaluate the symbol first, or a fresh kernel shows only its autoload stub *)
Internal`InheritedBlock[{CloudPut}, ClearAttributes[CloudPut, ReadProtected];
StringTake[ToString[Definition[CloudPut], InputForm], UpTo[2000]]] (* ToString inside the block *)
Some symbols are kernel code without Wolfram Language definitions. For the source files and line ranges, use
WolframDebugging`FindSymbolSource["CloudPut"] (System symbols are often defined in paclets, here CloudObject` ).
To see what an evaluation loads, compare $LoadedFiles before and after it in a fresh kernel; nesting and autoloads are
in references/PackageLoading.md.
Wolfram Language
A full Wolfram Language development environment with code evaluation, documentation search, symbol inspection, static analysis, and test execution.
Prerequisites
These scripts require wolframscript. If it is not installed or not on your PATH, read references/GetWolframEngine.md (relative to this skill directory) for installation instructions.
Usage
With MCP Server (preferred)
If you have Wolfram Language MCP tools available in your tool list (e.g., mcp__Wolfram__WolframLanguageEvaluator), use those directly. They provide richer integration, stateful evaluation, and better performance than the bundled scripts.
For a richer experience, consider setting up the Wolfram MCP server. See references/SetUpWolframMCPServer.md (relative to this skill directory) for instructions.
With Bundled Scripts
If no MCP tools are available, use the bundled scripts in the scripts/ directory (relative to this skill directory). Run them with:
wolframscript -f scripts/<ScriptName>.wls <arguments>
Pass --usage to any script to see its argument documentation:
wolframscript -f scripts/<ScriptName>.wls --usage
For detailed usage, arguments, and invocation syntax for each script, see references/Scripts.md (relative to this skill directory).
Reminder: These scripts are only relevant when you do not have the equivalent MCP tool available.
Available Tools
| Script | When to use |
|---|---|
WolframLanguageContext | Agentic search for documentation and other Wolfram Language resources |
WolframLanguageEvaluator | Evaluate Wolfram Language code and return results |
SymbolDefinition | Inspect how symbols are defined |
TestReport | Run .wlt test files and directories to verify correctness |
CodeInspector | Check Wolfram Language code or files for issues and style problems |
WolframLanguageContext
If your MCP server provides a WolframContext tool instead of WolframLanguageContext, you can use that instead. It's effectively equivalent, except it may include additional context from Wolfram Alpha.
You should almost always search with WolframLanguageContext as a first step. It searches a variety of sources, including documentation, the Wolfram Function Repository, Data Repository, Neural Net Repository, Paclet Repository, and more. Even if you're very familiar with Wolfram Language, it's a good idea to search first because there may be a new ResourceFunction, paclet, etc. that does what you need.
The context argument should be as specific as possible, but avoid mentioning specific code that's only defined in the codebase you're working on, since it only knows about publicly available resources.
WolframLanguageEvaluator
If you have access to this tool via a local MCP server, evaluations are done in a persistent kernel session. This means that you can evaluate code that modifies global state, such as defining functions, loading packages, and the changes will persist between evaluations. If it's a remote MCP server, or you're using the bundled scripts, the kernel is disposed after each evaluation. This means that you need to redefine functions, load packages, etc. for each evaluation that needs them.
Working with Natural Language Input
The \[FreeformPrompt] syntax is analogous to ctrl+= input in notebooks. It parses natural language input into Wolfram Language expressions. You should ALWAYS use this natural language input to obtain things like Quantity, Entity, EntityClass, etc.
Important: Natural language input is parsed before evaluation, so it works like macro expansion. For example:
In[1]:= Hold[\[FreeformPrompt]["picture of a cat"]]
Out[1]= Hold[Entity["TaxonomicSpecies", "FelisCatus::ddvt3"][EntityProperty["TaxonomicSpecies", "Image"]]]
This means that programmatic uses like the following will NOT work:
Table[\[FreeformPrompt]["picture of a "<>name], {name, {"cat", "dog"}}]
You can use a symbol as the second argument to specify the expected head of the parsed expression:
| Input | Parsed Expression |
|---|---|
\[FreeformPrompt]["Pennsylvania", Entity] | Entity["AdministrativeDivision", {"Pennsylvania", "UnitedStates"}] |
\[FreeformPrompt]["lanthanide elements", EntityClass] | EntityClass["Element", "Lanthanide"] |
\[FreeformPrompt]["123 terawatt hours", Quantity] | Quantity[123, "Hours"*"Terawatts"] |
A string as the second argument represents an expected entity type, which can be an Entity or EntityClass:
| Input | Parsed Expression |
|---|---|
\[FreeformPrompt]["Mercury", "Planet"] | Entity["Planet", "Mercury"] |
\[FreeformPrompt]["Mercury", "MannedSpaceMission"] | EntityClass["MannedSpaceMission", "ProjectMercuryMannedMission"] |
When in doubt, use the single argument form. You'll get feedback about other valid interpretations, which you can then choose from. For example:
In[2]:= \[FreeformPrompt]["12:00"]
During evaluation of In[2]:= [WARNING] Interpreted "12:00" as TimeObject[{12, 0}] with other possible interpretations:
ResourceFunction["RatioSimplify"][{12, 0}]
Quantity[MixedMagnitude[{12, 0}], MixedUnit[{"Minutes", "Seconds"}]]
TimeObject[{0, 0}]
Out[2]= TimeObject[{12, 0}, "Minute"]
SymbolDefinition
Use SymbolDefinition instead of evaluating Definition or DownValues via the WolframLanguageEvaluator tool to inspect symbol definitions. This tool is optimized for producing LLM readable output for definitions. If you have a persistent local kernel for the MCP server, this tool has access to the same kernel session as the WolframLanguageEvaluator tool.
TestReport
If the user has test files for their project (.wlt files), you can run them with the TestReport tool to get a Markdown formatted report of the test results.
CodeInspector
If you've edited Wolfram Language files, you should check your work with CodeInspector.
Other Tips
- When using Markdown formatting, you should ALWAYS use double backticks for inline code containing fully qualified symbol names:
MyContext`MySymbol[x]
Wolfram Notebooks
Read and write Wolfram notebook (.nb) files, including conversion between markdown and notebook format.
Prerequisites
These scripts require wolframscript. If it is not installed or not on your PATH, read references/GetWolframEngine.md (relative to this skill directory) for installation instructions.
Usage
With MCP Server (preferred)
If you have Wolfram notebook MCP tools available in your tool list (e.g., mcp__Wolfram__ReadNotebook), use those directly. They provide richer integration and better performance than the bundled scripts.
For a richer experience, consider setting up the Wolfram MCP server. See references/SetUpWolframMCPServer.md (relative to this skill directory) for instructions.
With Bundled Scripts
If no MCP tools are available, use the bundled scripts in the scripts/ directory (relative to this skill directory). Run them with:
wolframscript -f scripts/<ScriptName>.wls <arguments>
Pass --usage to any script to see its argument documentation:
wolframscript -f scripts/<ScriptName>.wls --usage
For detailed usage, arguments, and invocation syntax for each script, see references/Scripts.md (relative to this skill directory).
Reminder: These scripts are only relevant when you do not have the equivalent MCP tool available.
Available Tools
| Script | When to use |
|---|---|
ReadNotebook | Read a Wolfram notebook (.nb) file and return its contents as markdown |
WriteNotebook | Convert markdown text to a Wolfram notebook and save it to a .nb file |
ReadNotebook
Use ReadNotebook to inspect the contents of an existing Wolfram notebook. The tool returns the notebook's content as markdown text, including code cells, text cells, and their outputs. This is useful for:
- Understanding what a notebook contains without opening it in a Wolfram notebook interface
- Reviewing notebook code and results in a text-based workflow
- Extracting code or documentation from notebooks
The notebook argument should be a file path to a .nb file.
WriteNotebook
Use WriteNotebook to create a new Wolfram notebook from markdown text. The markdown is converted to notebook cell structure with appropriate cell types (code cells, text cells, section headers, etc.). This is useful for:
- Creating notebooks programmatically from documentation or code
- Converting markdown-based content into interactive Wolfram notebooks
- Generating starter notebooks for users
The file argument must end in .nb. The markdown argument is the content to convert. Use the --overwrite flag if you need to replace an existing file.
Other Tips
- Use
ReadNotebookbefore modifying a notebook to understand its current structure and content. - When writing notebooks, use standard markdown formatting:
#headers become Section/Subsection cells, fenced code blocks become Code cells, and plain text becomes Text cells. - If you also have the
wolfram-languageskill available, you can evaluate code from a notebook usingWolframLanguageEvaluatorafter reading it withReadNotebook.
Wolfram Paclets
Paclet development and release workflow tools for checking, building, and submitting Wolfram Language paclets.
Prerequisites
These scripts require wolframscript. If it is not installed or not on your PATH, read references/GetWolframEngine.md (relative to this skill directory) for installation instructions.
Usage
With MCP Server (preferred)
If you have Wolfram paclet tools available in your tool list (e.g., mcp__Wolfram__CheckPaclet), use those directly. They provide richer integration and better performance than the bundled scripts.
The CheckPaclet, BuildPaclet, and SubmitPaclet MCP tools are only provided by the WolframPacletDevelopment MCP server. If the Wolfram MCP server in your tool list does not have them, use the bundled scripts instead.
For a richer experience, consider setting up the Wolfram MCP server. See references/SetUpWolframMCPServer.md (relative to this skill directory) for instructions.
With Bundled Scripts
If no MCP tools are available, use the bundled scripts in the scripts/ directory (relative to this skill directory). Run them with:
wolframscript -f scripts/<ScriptName>.wls <arguments>
Pass --usage to any script to see its argument documentation:
wolframscript -f scripts/<ScriptName>.wls --usage
For detailed usage, arguments, and invocation syntax for each script, see references/Scripts.md (relative to this skill directory).
Reminder: These scripts are only relevant when you do not have the equivalent MCP tool available.
Available Tools
| Script | When to use |
|---|---|
CheckPaclet | Check a paclet for issues before building or submitting |
BuildPaclet | Build a .paclet archive from a paclet directory |
SubmitPaclet | Submit a paclet to the Wolfram Language Paclet Repository |
CheckPaclet
Use CheckPaclet before building or submitting a paclet. It reports errors, warnings, and suggestions organized by severity. The path should be an absolute path to the paclet root directory or the definition notebook (.nb) file.
BuildPaclet
Use BuildPaclet to produce a .paclet archive. Optionally pass --check true to run CheckPaclet before building. The build is aborted if errors are found.
SubmitPaclet
Use SubmitPaclet to submit a paclet to the Wolfram Language Paclet Repository. This builds the paclet internally before submitting. Requires prior authentication via $PublisherID or an active Wolfram Cloud connection. Use CheckPaclet first to verify readiness.
Other Tips
- Run
CheckPacletfirst, thenBuildPaclet, and only thenSubmitPacletfor a reliable release flow.
Agents 26
Getting the Wolfram Engine
The bundled scripts in this skill require wolframscript, the command-line interface to the Wolfram Language. This guide covers installation on each platform.
Check If Already Installed
Run the following in your terminal:
wolframscript -code '1+1'
If it prints 2, you're ready to go — no further setup needed.
macOS
Via Homebrew (recommended)
brew install --cask wolfram-engine
After installation, wolframscript should be available on your PATH automatically.
Manual Download
- Download the Wolfram Engine from https://www.wolfram.com/engine/.
- Open the
.dmgand drag Wolfram Engine to Applications. - Run the app once to complete activation.
wolframscriptis installed at/usr/local/bin/wolframscript.
Linux
- Download the
.shinstaller from https://www.wolfram.com/engine/. - Run:
sudo bash WolframEngine_*_Linux.sh - Follow the prompts and activate when complete.
After installation, wolframscript is typically at /usr/bin/wolframscript.
Windows
- Download the installer from https://www.wolfram.com/engine/.
- Run the
.exeinstaller and follow the prompts. - Activate when prompted.
wolframscript.exeis added to your PATH automatically. If not, the default location is:C:\Program Files\Wolfram Research\WolframScript\wolframscript.exe
Activation
The Wolfram Engine is free for development use but requires activation with a Wolfram Account. If you don't have one, create an account at https://account.wolfram.com.
When you first run wolframscript, it will prompt for activation. You can also activate manually:
wolframscript -activate
Troubleshooting
wolframscriptnot found — Ensure the install directory is on your PATH. You can check the location withwhich wolframscript(macOS/Linux) orwhere wolframscript(Windows).- Activation fails — Check your internet connection and verify your Wolfram Account credentials at https://account.wolfram.com.
- License issues — The free Wolfram Engine license covers non-production development use. For production or commercial use, see https://www.wolfram.com/engine/commercial-options/.
More Information
- Wolfram Engine: https://www.wolfram.com/engine/
- Wolfram Account: https://account.wolfram.com
Script Reference
Auto-generated reference for bundled scripts. Pass --usage to any
script for the latest argument documentation.
WolframAlphaContext.wls
Uses semantic search to retrieve any relevant information from Wolfram Alpha. Always use this tool at the start of new conversations or if the topic changes to ensure you have up-to-date relevant information. This uses semantic search, so the context argument should be written in natural language (not a search query) and contain as much detail as possible (up to 250 words).
Usage:
wolframscript -f scripts/WolframAlphaContext.wls <context>
Arguments:
| Argument | Required | Description |
|---|---|---|
context | Yes | A detailed summary of what the user is trying to achieve or learn about. |
WolframAlpha.wls
Use natural language queries with Wolfram|Alpha to get up-to-date computational results about entities in chemistry, physics, geography, history, art, astronomy, and more. Always use the Wolfram context tool before using this tool to make sure you have the most up-to-date information.
Usage:
wolframscript -f scripts/WolframAlpha.wls <query>
Arguments:
| Argument | Required | Description |
|---|---|---|
query | Yes | The query to send to Wolfram|Alpha. |
Setting Up the Wolfram MCP Server
This guide explains how to connect your client to a Wolfram MCP server. With an MCP server you call the Wolfram tools directly instead of running the bundled scripts. A local server also keeps one Wolfram Language session alive between calls (definitions persist, and no kernel has to start for each call) and provides more tools.
There are two options:
| Wolfram Local MCP | Wolfram Cloud MCP | |
|---|---|---|
| Requires | A local Wolfram installation (Wolfram Engine, Wolfram, or Mathematica) | Nothing: free, no subscription or API key |
| Tools | Depends on the toolset (Step 3) | WolframContext, WolframLanguageEvaluator, WolframAlpha |
| Evaluation | Persistent session | Stateless, 60-second default time limit |
| Agent skills | DeployAgentTools installs them with the server | Not included |
Use the local server for coding agents and for anything that needs heavy computation, notebooks, tests, or paclet tools. Use Wolfram Cloud MCP when there is no local Wolfram installation and the user does not want to install one.
Both options change the user's client configuration, so ask the user before setting either one up. Also ask which toolset they want if the context does not make it clear. New MCP servers appear only after the client is restarted or reloaded, so the tools will not show up in your current session.
Option 1: Wolfram Local MCP
Step 1: Check for wolframscript
wolframscript -code '$VersionNumber'
If wolframscript is not found, read GetWolframEngine.md (in this references/ directory) or use Option 2. Current versions of AgentTools require Wolfram 15.0 or later.
The commands below are written for a POSIX shell. On Windows, shell quoting can mangle the double quotes in the code. To avoid that, put the code in a .wls file, wrap each result in Print[...], and run wolframscript -f file.wls.
Step 2: Install or update the AgentTools paclet
wolframscript -code 'PacletInstall["Wolfram/AgentTools", UpdatePacletSites -> True]["Version"]'
wolframscript -code 'Wolfram`AgentTools`AgentToolsObject["WolframLanguage"]["AgentSkillNames"]'
Wolfram 15 includes an older built-in copy of AgentTools. The first command installs the latest version, and Wolfram uses that version from then on. The second command should print {wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging}. If it prints {}, or the expression comes back unevaluated, the installed AgentTools cannot install agent skills. In that case use InstallMCPServer (Step 5).
Step 3: Choose a toolset
| Toolset | MCP tools | Agent skills installed by DeployAgentTools |
|---|---|---|
Wolfram | WolframContext, WolframLanguageEvaluator, WolframAlpha | wolfram-language, wolfram-alpha, wolfram-debugging |
WolframAlpha | WolframAlphaContext, WolframAlpha | wolfram-alpha |
WolframLanguage | WolframLanguageContext, WolframLanguageEvaluator, ReadNotebook, WriteNotebook, SymbolDefinition, CodeInspector, TestReport | wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging |
WolframPacletDevelopment | The WolframLanguage tools plus CreateSymbolDoc, EditSymbolDoc, EditSymbolDocExamples, CheckPaclet, BuildPaclet, SubmitPaclet | wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging |
- Use cases:
Wolframis for general computation and knowledge,WolframAlphafor Wolfram|Alpha queries only, andWolframLanguagefor Wolfram Language development.WolframPacletDevelopmentadds tools for writing documentation pages and for checking, building, and submitting paclets. - Tools: the
*Contexttools are semantic search (WolframAlphaContextover Wolfram|Alpha,WolframLanguageContextover Wolfram Language documentation and resources,WolframContextover both).ReadNotebook/WriteNotebookconvert notebooks (.nb) to and from markdown,SymbolDefinitionretrieves symbol definitions,CodeInspectorreports code issues, andTestReportruns.wlttest files. - Default toolset: without a toolset argument, the client's default is used:
Wolframfor Claude Desktop, Goose, and LM Studio, andWolframLanguagefor every other client. - One toolset per client: all four toolsets use the MCP configuration key
Wolfram, so a client (at a given user or project level) has only one of them. Switch withOverwriteTarget -> True, or use"MCPServerName"(Step 5) to install two side by side. - LLMKit: the context tools work best with an LLMKit subscription.
WolframAlphaContextrequires one, so installing theWolframAlphatoolset fails withLLMKitRequiredunless the kernel is connected to the Wolfram Cloud with an account that has LLMKit (useWolframinstead). For the other toolsets, anLLMKitSuggestedwarning is informational only.
Step 4: Choose DeployAgentTools or InstallMCPServer
DeployAgentTools is the recommended way. It installs the toolset's MCP server and its agent skills as one tracked deployment, which DeleteObject can remove again. InstallMCPServer writes only the MCP server configuration. Use it only when the MCP server is all that should be installed.
You are reading this from a Wolfram skill that is already installed, so check two things first:
- Existing deployments: run
wolframscript -code 'DeployedAgentTools[]'. If your client and location already have a deployment, the server is already configured. Ask the user to restart the client, or redeploy withOverwriteTarget -> Trueto switch toolsets or to add the skills that an older AgentTools did not install. - Where this skill is installed: this is the directory that contains this
references/folder. Compare its parent directory with the skills directory thatDeployAgentToolswill use (Supported Clients).
Use DeployAgentTools when this skill is already in that directory (same client, same user or project scope), or when no Wolfram skills are installed yet. It handles existing skills safely:
- An identical copy is adopted as is, and
DeleteObjectnever deletes a skill directory that existed before the deployment. - A copy with different content (installed by hand or by another tool, or a deployed copy that the user modified) is left untouched. The MCP server and the other skills are still installed, and the warning
DeployAgentTools::AgentSkillNotInstallednames the skipped skill. - Copies installed by an earlier deployment are updated to the current AgentTools version automatically; a newer copy that another deployment still uses is never downgraded. (Replacing a deployment for the same client and location still needs
OverwriteTarget -> True.)
Use InstallMCPServer, or DeployAgentTools with "SkillsDirectory" -> None (only the MCP server, still tracked as a deployment), when:
- The user only wants the MCP server, or Step 2 showed that the installed AgentTools has no agent skills.
- The Wolfram skills are installed somewhere that
DeployAgentToolsdoes not manage, but that your client also reads.DeployAgentToolswould add a second copy, and the client would see each skill twice. Examples: a Claude Code plugin (a path under~/.claude/plugins/); another skills directory that your client loads, such as~/.agents/skillsor~/.claude/skillsfor a client that also reads those; or the project's skills directory while you deploy at user level (a project-level deployment also works there if the client supports project MCP configuration).
Never use OverwriteTarget -> All without asking the user. It replaces skill directories that the deployment does not own and discards any changes in them.
Step 5: Install the server
DeployAgentTools, DeployedAgentTools, and AgentToolsDeployment are built-in symbols, so they need no context prefix:
# The client's default toolset, at user level
wolframscript -code 'DeployAgentTools["ClaudeCode"]'
# A specific toolset, at project level (the project's MCP configuration and skills directory)
wolframscript -code 'DeployAgentTools[{"ClaudeCode", "/path/to/project"}, "WolframLanguage"]'
# Only the MCP server, as a tracked deployment
wolframscript -code 'DeployAgentTools["ClaudeCode", "WolframLanguage", "SkillsDirectory" -> None]'
# Replace the Wolfram toolset already deployed for this client and location
wolframscript -code 'DeployAgentTools["ClaudeCode", "Wolfram", OverwriteTarget -> True]'
- Result: an
AgentToolsDeployment[...]. The first run can take a few minutes while the context tools download their search indexes, so use a generous command timeout. - Clients without agent skills support (Claude Desktop, LM Studio, Amazon Q Developer) get only the MCP server.
- Project level without project MCP support: the client gets only the project skills, with an
MCPServersNotDeployedwarning. Add the server at user level withInstallMCPServer. DeploymentExists: a Wolfram toolset is already deployed for that client and location. UseOverwriteTarget -> Trueto replace it.DeployAgentTools[All]deploys to every supported client, installed or not. Do not use it unless the user asks.- Removing:
DeleteObject /@ Select[DeployedAgentTools["ClaudeCode"], #["Scope"] === "Global" && #["Toolset"] === "WolframLanguage" &]removes the user-level deployment. For a project deployment, match#["Scope"] === File["/path/to/project"](the absolute project path) instead; without a scope test, every project's deployment of that toolset is removed too. Skills that another deployment still uses, that were modified, or that existed before the deployment are kept.
InstallMCPServer needs the full context name:
wolframscript -code 'Wolfram`AgentTools`InstallMCPServer["ClaudeCode", "WolframLanguage"]'
wolframscript -code 'Wolfram`AgentTools`InstallMCPServer[{"ClaudeCode", "/path/to/project"}, "WolframLanguage"]'
wolframscript -code 'Wolfram`AgentTools`UninstallMCPServer["ClaudeCode", "WolframLanguage"]'
InstallMCPServer is not tracked by DeployedAgentTools. It replaces whatever Wolfram server is already configured under the key Wolfram.
Both functions accept these options:
"ToolOptions" -> <|"WolframLanguageEvaluator" -> <|"TimeConstraint" -> 120|>|>: per-tool settings."SubmitUsageData" -> False: opts out of usage data collection, which the built-in servers do by default."MCPServerName" -> "WolframDev": uses a different configuration key, so that two Wolfram toolsets can be installed side by side.
Step 6: Restart the client
Ask the user to restart or reload the client. The tools then appear under the server name Wolfram, for example mcp__Wolfram__WolframLanguageEvaluator in Claude Code. When they are available, use them instead of the bundled scripts.
Supported Clients
| Client | Name | Project MCP | User skills directory | Project skills directory |
|---|---|---|---|---|
| Amazon Q Developer | "AmazonQ" | yes | — | — |
| Antigravity | "Antigravity" | yes | ~/.gemini/config/skills (before migration: ~/.gemini/antigravity/skills) | .agents/skills |
| Augment Code | "AugmentCode" | no | ~/.augment/skills | .augment/skills |
| Augment Code IDE | "AugmentCodeIDE" | no | ~/.augment/skills | .augment/skills |
| Claude Code | "ClaudeCode" | yes | ~/.claude/skills | .claude/skills |
| Claude Desktop (macOS, Windows) | "ClaudeDesktop" | no | — | — |
| Cline | "Cline" | no | ~/.cline/skills | .cline/skills |
| Codex CLI | "Codex" | yes | ~/.agents/skills | .agents/skills |
| Continue | "Continue" | yes | ~/.continue/skills | .continue/skills |
| Copilot CLI | "CopilotCLI" | no | ~/.copilot/skills | .github/skills |
| Cursor | "Cursor" | no | ~/.cursor/skills | .cursor/skills |
| Gemini CLI | "GeminiCLI" | no | ~/.gemini/skills | .gemini/skills |
| Goose | "Goose" | no | ~/.agents/skills | .agents/skills |
| Junie | "Junie" | yes | ~/.junie/skills | .junie/skills |
| Kimi Code | "KimiCode" | no | ~/.kimi/skills | .kimi/skills |
| Kiro | "Kiro" | yes | ~/.kiro/skills | .kiro/skills |
| LM Studio | "LMStudio" | no | — | — |
| OpenCode | "OpenCode" | yes | ~/.config/opencode/skills | .opencode/skills |
| Qwen Code | "QwenCode" | yes | ~/.qwen/skills | .qwen/skills |
| Visual Studio Code | "VisualStudioCode" | yes | ~/.copilot/skills | .github/skills |
| Windsurf | "Windsurf" | no | ~/.codeium/windsurf/skills | .windsurf/skills |
| Zed | "Zed" | yes | ~/.agents/skills | .agents/skills |
- Paths:
~is the user's home directory on every operating system. Project skills directories are relative to the project directory. - Aliases are accepted, such as
"Claude"(Claude Desktop),"VSCode","Copilot"(Copilot CLI), and"Gemini"(Gemini CLI). - Shared skills directories: several clients share one. AgentTools tracks which deployments use each skill, so removing one deployment never deletes skills that another deployment still uses.
- Non-standard configuration file: pass
File["/path/to/config.json"]as the target. Add"ApplicationName" -> "<Name>"if the path does not identify the client. WithDeployAgentTools, also pass"SkillsDirectory" -> File["/path/to/skills"], unless the file is the client's standard global or project configuration file.
Local Server in Other Clients: Manual Configuration
Any MCP client that can launch local (stdio) servers can run the local Wolfram server, even if it is not in the Supported Clients table. To print the exact configuration for this machine, run this command with the toolset you want:
wolframscript -code 'Wolfram`AgentTools`MCPServerObject["WolframLanguage"]["JSONConfiguration"]'
Example output on Linux, shown with / instead of the \/ escapes that the real output contains (both are valid JSON):
{
"mcpServers": {
"WolframLanguage": {
"type": "stdio",
"command": "/usr/local/Wolfram/Wolfram/15.0/Executables/wolfram",
"args": [
"-run",
"PacletSymbol[\"Wolfram/AgentTools\",\"Wolfram`AgentTools`StartMCPServer\"][]",
"-noinit",
"-noprompt"
],
"env": {
"MCP_SERVER_NAME": "WolframLanguage",
"WOLFRAM_BASE": "/usr/share/Wolfram",
"WOLFRAM_LOCALBASE": "/home/user/.Wolfram/Objects",
"WOLFRAM_USERBASE": "/home/user/.Wolfram"
}
}
}
}
If the client uses this common mcpServers JSON format, AgentTools can write the entry (under the key Wolfram) for you: Wolfram`AgentTools`InstallMCPServer[File["/path/to/config.json"], "WolframLanguage"] writes only the server, and DeployAgentTools[File["/path/to/config.json"], "WolframLanguage", "SkillsDirectory" -> File["/path/to/skills"]] also installs the skills. Otherwise, copy the values into the client's own format; any server name works.
Command: the Wolfram kernel executable wolfram, not wolframscript.
| OS | Command |
|---|---|
| Windows | $InstallationDirectory\wolfram.exe |
| macOS | $InstallationDirectory/MacOS/wolfram |
| Linux | $InstallationDirectory/Executables/wolfram |
Arguments: four separate arguments, given to the client exactly as in the printed "args":
-run, followed byPacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"][]. This loads the newest installed AgentTools and starts the stdio server.-noinit: skips the user's init files.-noprompt: keeps kernel prompts off standard output, which must carry only MCP messages.
As a single shell command line:
/path/to/wolfram -run 'PacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"][]' -noinit -noprompt
If the client cannot set environment variables, name the toolset in the argument instead: PacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"]["WolframLanguage"].
Environment variables:
| Variable | Needed | Purpose |
|---|---|---|
MCP_SERVER_NAME | Recommended | The toolset to run: Wolfram (the default when unset), WolframAlpha, WolframLanguage, WolframPacletDevelopment, or the name of another server known to AgentTools |
WOLFRAM_USERBASE | Recommended | $UserBaseDirectory. It must be the directory where AgentTools was installed; otherwise the kernel may load the older built-in copy |
WOLFRAM_BASE | Recommended | $BaseDirectory |
WOLFRAM_LOCALBASE | Recommended | $LocalBase (storage for LocalObject) |
APPDATA | Windows | The user's application data directory, from which Windows derives the default $UserBaseDirectory |
MCP_TOOL_OPTIONS | Optional | Per-tool options as compact JSON, e.g. {"WolframLanguageEvaluator":{"TimeConstraint":120}} |
SUBMIT_USAGE_DATA | Optional | false opts out of usage data collection |
MCP_APPS_ENABLED | Optional | false disables MCP Apps (interactive UI resources) |
LLMKIT_ENABLED | Optional | false makes the context tools behave as if there were no LLMKit subscription, without warnings |
The printed configuration already holds this machine's values for the directory variables. Keep them, because the client may start servers with a reduced environment.
Option 2: Wolfram Cloud MCP
Wolfram Cloud MCP is a hosted Wolfram MCP server. It is free and needs no subscription, API key, or local installation.
- URL:
https://agenttools.wolfram.com/mcp - Transport: Streamable HTTP, with no authentication
| Tool | Description |
|---|---|
WolframContext | Semantic search over Wolfram|Alpha and Wolfram Language resources |
WolframLanguageEvaluator | Evaluates Wolfram Language code |
WolframAlpha | Sends natural language queries to Wolfram|Alpha |
Differences from the local server:
- Stateless evaluation:
WolframLanguageEvaluatordoes not carry definitions over between calls. Its default time constraint is 60 seconds per call, which itstimeConstraintargument can change. - No other tools: there are no notebook, symbol definition, code inspection, test, or paclet tools. The
wolfram-notebooksandwolfram-pacletsskills still needwolframscriptfor their scripts. - Manual setup only:
DeployAgentToolsandInstallMCPServerconfigure only the local server.
Configure your client
Clients that support remote servers (some spell it differently: Cline adds "type": "streamableHttp", Antigravity uses "serverUrl"; the support article below has steps for many clients):
{ "mcpServers": { "wolfram": { "url": "https://agenttools.wolfram.com/mcp" } } }
Claude Code (add --scope user to make it available in all projects):
claude mcp add --transport http wolfram https://agenttools.wolfram.com/mcp
Visual Studio Code (the user mcp.json or the workspace's .vscode/mcp.json):
{ "servers": { "wolfram": { "type": "http", "url": "https://agenttools.wolfram.com/mcp" } } }
Claude Desktop: in Customize → Connectors, search for Wolfram and click +.
Clients that only support local (stdio) servers can use the mcp-remote bridge, which requires Node.js:
{ "mcpServers": { "wolfram": { "command": "npx", "args": ["-y", "mcp-remote@latest", "https://agenttools.wolfram.com/mcp"] } } }
The local Wolfram toolset already provides all three of these tools, so don't add the cloud server next to it. Next to another local toolset (for example WolframLanguage, which has no WolframAlpha tool), the cloud server can supply the missing tools under its own key, such as wolfram. Then ask the user to restart or reload the client.
Troubleshooting
LLMKitRequired: the localWolframAlphatoolset needs LLMKit. Use theWolframtoolset or Wolfram Cloud MCP instead.DeploymentExists: a Wolfram toolset is already deployed for that client and location. UseOverwriteTarget -> Trueto replace it.AgentSkillNotInstalled(warning): a different skill with the same name already exists. Everything else was installed. Keep the existing skill, or ask the user before usingOverwriteTarget -> All.UnknownInstallLocation: the client has no known configuration file on this operating system (for example, Claude Desktop on Linux). Use aFile[...]target.- The tools do not appear after a restart: check the configuration file that was written (
dep["ConfigFile"]for a deployment, or the"Location"of theInstallMCPServerresult), then the server log at$UserBaseDirectory/ApplicationData/Wolfram/AgentTools/Servers/<Toolset>/Log.wl. Also make sure the kernel is activated (wolframscript -code '1+1'prints2).
More Information
- Wolfram Local MCP: https://www.wolfram.com/artificial-intelligence/mcp/local/wolfram-mcp-local/
- Wolfram Cloud MCP: https://www.wolfram.com/artificial-intelligence/mcp/cloud/wolfram-mcp-cloud
- Connecting Wolfram Cloud MCP to an AI application: https://support.wolfram.com/75237
- AgentTools paclet: https://resources.wolframcloud.com/PacletRepository/resources/Wolfram/AgentTools/
Cloud deployments and HTTP requests
Debugging code deployed with CloudDeploy (APIFunction, Delayed, FormFunction, scheduled tasks), code run with
CloudEvaluate or CloudSubmit, and HTTP requests made with URLRead, URLExecute and friends: what a caller sees for
each kind of failure, how to reproduce a request locally where messages and stacks work, how to get diagnostics out
of a deployment, and how to see the raw HTTP traffic. Behavior was checked with Wolfram 15.0 (local and cloud kernels).
The examples deploy to a scratch directory (/debug-scratch/...); delete what you deploy (DeleteObject).
What the caller of a deployed API sees
A demo API with one failure mode per mode value:
demoBody[mode_, x_] := Switch[mode,
"ok", x^2, "msg", {1/0, x}, "throw", Throw[x, "demo"], "abort", Abort[], "print", Print["printed"]; x,
"failure", Failure["DemoFailure", <|"MessageTemplate" -> "Bad value `1`.", "MessageParameters" -> {x}|>],
"slow", Pause[x]; "done"];
api = CloudDeploy[APIFunction[{"mode" -> "String", "x" -> "Integer" -> 1}, demoBody[#mode, #x] &,
AllowedCloudExtraParameters -> {"_responseform", "_timeout"}], "/debug-scratch/dbg-demo-api", Permissions -> "Public"];
Call it like an anonymous client (First[api] is the URL string) and reduce HTML pages to their visible text:
pageText[s_String] := StringTrim @ StringReplace[StringDelete[s, {Shortest["<script" ~~ ___ ~~ "</script>"],
Shortest["<style" ~~ ___ ~~ "</style>"], "<" ~~ Except[">"] ... ~~ ">"}], Whitespace .. -> " "];
Table[With[{r = URLRead[HTTPRequest[First[api], <|"Query" -> {"mode" -> m, "x" -> "3"}|>], {"StatusCode", "Headers", "Body"}]},
{m, r["StatusCode"], Lookup[Association[r["Headers"]], "content-type"], StringTake[pageText[r["Body"]], UpTo[50]]}],
{m, {"ok", "msg", "print", "failure", "throw", "abort"}}]
(* {{"ok", 200, "text/plain;charset=utf-8", "9"},
{"msg", 200, "text/plain;charset=utf-8", "{ComplexInfinity, 3}"},
{"print", 200, "text/plain;charset=utf-8", "3"},
{"failure", 400, "application/json", "{ \"Success\":false, \"Failure\":\"Bad value 3.\" }"},
{"throw", 500, "text/html;charset=UTF-8", "Wolfram 500 Internal Server Error"},
{"abort", 500, "text/html", ""}} (same from wolframscript and MCP Local) *)
| in the deployed code | the caller gets |
|---|---|
| messages | nothing: 200 and the normal result |
Print, Echo | nothing (output is lost) |
uncaught Throw | 500 generic HTML page, the same page as HTTPErrorResponse[500] (only a request id differs) |
Abort[] | 500 with an empty body |
| running past the 300 s limit | 502 "Server Error" page after 300 s |
returned Failure (APIFunction) | 400 JSON with the failure's message text |
| parameter that fails to interpret or is missing | 400 JSON naming the field |
Only a returned Failure and parameter failures carry a reason, so return Failure objects from API code instead of
throwing. Delayed renders a returned Failure as a 200 HTML page with its text; a FormFunction answers 400 with an
"API Web Report" page that does not contain the failure text, and a GET with query parameters only shows the form
(test it with a POST). Wrap the body to get more out of a failing deployment ("Diagnostics inside the deployment" below).
Use URLRead, never URLExecute, to debug
URLExecute hides every HTTP error: no Failure, no message, just whatever the error body imports as:
StringTake[ToString[URLExecute[First[api], {"mode" -> #, "x" -> "3"}], InputForm], UpTo[60]] & /@ {"throw", "failure", "abort"}
(* {"\"{t.onerror=t.onload=null,clearTimeout(u);var f=c[e];if(dele", "{\"Success\" -> False, \"Failure\" -> \"Bad value 3.\"}", "\"\""} *)
A 500 page becomes JavaScript text, the 400 JSON a rule list, the empty 500 an empty string. Use
URLRead[req, {"StatusCode", "Headers", "Body"}] and look at the status first. Helper:
WolframDebugging`HTTPSummary[response] (status, content type, visible text); see HelperFunctions.md.
- A URL string calls anonymously;
URLRead[CloudObject[...]],HTTPRequest[CloudObject[...], ...]andURLExecute[CloudObject[...]]are authenticated as the kernel's cloud user (the owner). - In wolframscript, requests that take longer than 1 s print
Connecting… | Elapsed time 1sprogress lines to stdout;ProgressReporting -> Falseturns them off.
Authentication failures look like missing objects
privApi = CloudDeploy[APIFunction[{"x" -> "Integer"}, #x + 1 &], "/debug-scratch/dbg-demo-private"]; (* default: private *)
missing = First[CloudObject["/debug-scratch/dbg-does-not-exist"]];
{URLRead[First[privApi] <> "?x=1", "StatusCode"], URLRead[missing, "StatusCode"],
URLRead[HTTPRequest[privApi, <|"Query" -> {"x" -> "1"}|>], {"StatusCode", "Body"}], FileExistsQ[CloudObject[missing]]}
(* {401, 401, <|"StatusCode" -> 200, "Body" -> "2"|>, False} (wolframscript) *)
- An anonymous request to a private or non-existent object is redirected to the sign-in page and ends as 401 (with
FollowRedirects -> False: 302 to.../j_spring_oauth_security_check?statusCode=401). Check existence and permissions as the owner:FileExistsQ[CloudObject[...]],Options[CloudObject[...], Permissions]. - With a
PermissionsKey, a missing or wrong_keyparameter gives 401 "Object Unavailable". SetPermissionsadds to the existing permissions; give the complete list (or redeploy withPermissions -> ...) to replace them.CloudGetof a missing object:CloudObject::cloudnfand$Failed.
Built-in debug view: _responseform and _timeout
An APIFunction deployed with AllowedCloudExtraParameters -> {"_responseform", "_timeout"} (as above) accepts two
extra parameters. _responseform=JSON (or WL, the same as Wolfram Language text) returns the evaluation data of the
request instead of the result:
KeyTake[URLExecute[api, {"mode" -> #, "x" -> "3", "_responseform" -> "JSON"}, "RawJSON"],
{"StatusCode", "FailureType", "MessagesExpressions", "OutputLog", "Result"}] & /@ {"msg", "print"}
(* {<|"StatusCode" -> 200, "FailureType" -> "MessageFailure", "MessagesExpressions" -> {"Hold[Message[Power::infy, HoldCompleteForm[0^(-1)]]]"},
"OutputLog" -> {}, "Result" -> "{ComplexInfinity, 3}"|>,
<|"StatusCode" -> 200, "FailureType" -> Null, "MessagesExpressions" -> {}, "OutputLog" -> {"printed"}, "Result" -> "3"|>}
(wolframscript, MCP Local) *)
Other keys: "Success", "Messages", "MessagesText", "Timing", "AbsoluteTiming", "InputString" (the full
request, with headers and the client's address), "ResultMeta". Echo output is not in "OutputLog" ($Notebooks is
True in the cloud). For an uncaught Throw the answer is a 500 text/plain "Failed to export to JSON" body that still
contains the Throw::nocatch text. _timeout makes a slow request return early:
AbsoluteTiming[URLRead[HTTPRequest[First[api], <|"Query" -> {"mode" -> "slow", "x" -> "60", "_timeout" -> "1"}|>],
{"StatusCode", "Body"}]]
(* {1.56, <|"StatusCode" -> 200, "Body" -> "$Aborted"|>} *)
Both parameters are ignored unless listed in AllowedCloudExtraParameters, and they exist only for APIFunction
(a Delayed deployment ignores them). Remove them before production: _responseform exposes message texts and
request details.
Reproduce a request locally
GenerateHTTPResponse runs a deployable locally and returns the HTTPResponse the cloud would send, while messages
print, handlers fire and stacks can be captured (works in MCP Local, MCP Session and wolframscript):
otherFn[x_] := 1/x; myFn[a_, b_] := Table[otherFn[i], {i, a, b}];
api = APIFunction[{"a" -> "Integer", "b" -> "Integer"}, myFn[#a, #b] &];
resp = GenerateHTTPResponse[api, HTTPRequest["http://localhost/api", <|"Query" -> {"a" -> "-1", "b" -> "1"}|>]];
{resp["StatusCode"], resp["Body"]}
(* Power::infy is printed, then: {200, "{-1, ComplexInfinity, 1}"} (wolframscript, MCP Local, MCP Session) *)
Status and body match the cloud for APIFunction (FormFunction: the status). Differences: Delayed + Failure
gives a local 500 text/plain instead of the cloud's 200 HTML page, and an Abort[] escapes GenerateHTTPResponse
locally (in wolframscript it ends the script): wrap it in CheckAbort[..., $Aborted].
The request must have the right shape:
Quiet @ {HTTPRequest["http://localhost/api?a=1", <|"Query" -> {"b" -> "2"}|>]["URL"],
GenerateHTTPResponse[api, <|"Query" -> {"a" -> "1", "b" -> "2"}|>]["Body"],
StringTake[GenerateHTTPResponse[api, <|"Query" -> <|"a" -> "1", "b" -> "2"|>|>]["Body"], UpTo[40]],
GenerateHTTPResponse[api, {"a" -> "1", "b" -> "2"}]["StatusCode"],
GenerateHTTPResponse[api, HTTPRequest["http://localhost/api", <|Method -> "POST", "Body" -> {"a" -> "1", "b" -> "2"}|>]]["Body"]}
(* {"http://localhost/api?b=2", "{1, 1/2}", "APIFunction[{\"a\" -> \"Integer\", \"b\" -> \"I", 400, "{1, 1/2}"} *)
The "Query" key replaces the query of the URL; "Query" must be a list of rules (an association gives a 200 whose
body is the unevaluated APIFunction); bare rules are not parameters (400 "no input for fields"); POST parameters go in
"Body". Inside CloudEvaluate, GenerateHTTPResponse ignores the request (always 400); apply the function directly:
{CloudEvaluate[GenerateHTTPResponse[api, <|"Query" -> {"a" -> "1", "b" -> "2"}|>]["StatusCode"]],
CloudEvaluate[api[<|"a" -> "1", "b" -> "2"|>]]}
(* {400, {1, 1/2}} *)
Stack at the first message of a request
GenerateHTTPResponse evaluates the body under EvaluationData, which catches every Throw: a probe that throws
the stack out of a message handler misfires (huge Throw::nocatch output, wrong stack). Record and continue instead:
Module[{msgs = Internal`Bag[], st = None, resp},
resp = Internal`HandlerBlock[{"Message", Function[h, If[Last[h],
Internal`StuffBag[msgs, Replace[h, Hold[Message[mn_, ___], _] :> ToString[Unevaluated[mn], InputForm]]];
If[st === None, st = Stack[_]]]]}, (* record only: never Throw here *)
Block[{$Messages = {}}, StackBegin @ StackComplete @
GenerateHTTPResponse[api, HTTPRequest["http://localhost/api", <|"Query" -> {"a" -> "-1", "b" -> "1"}|>]]]];
<|"Status" -> resp["StatusCode"], "Messages" -> Internal`BagPart[msgs, All], "StackLength" -> Length[st],
"UserFrames" -> Block[{$ContextPath = Join[{"Global`", $Context}, $ContextPath]},
Cases[st, _[e : (_myFn | _otherFn | _Table)] :> ToString[Unevaluated[e], InputForm]]]|>]
(* <|"Status" -> 200, "Messages" -> {"Power::infy"}, "StackLength" -> 52,
"UserFrames" -> {"myFn[-1, 1]", "Table[otherFn[i], {i, -1, 1}]", "otherFn[i]"}|>
(wolframscript, MCP Local; MCP Session: 53 frames, the message is printed despite $Messages = {}, and once the
session has issued Power::infy three times, General::stop is printed and recorded too) *)
About 40 framework frames sit between GenerateHTTPResponse and the user code, hence the filter. For an uncaught
Throw, the frames of the thrower are gone by the time Throw::nocatch is issued: find the thrower with Trace on the
direct application (below). Helper: WolframDebugging`DebugHTTPResponse[api, <|"a" -> "-1", "b" -> "1"|>] (status,
text, messages, stack from the first user frame on).
Trace the deployed code
Trace sees none of the user code inside GenerateHTTPResponse; apply the APIFunction to the parameters directly
(MCP Local and wolframscript; Trace is disabled in MCP Session and in the cloud):
{Trace[GenerateHTTPResponse[api, HTTPRequest["http://localhost/api", <|"Query" -> {"a" -> "-1", "b" -> "1"}|>]], _otherFn],
Trace[api[<|"a" -> "-1", "b" -> "1"|>], _otherFn]} // Quiet
(* {{}, {{{{HoldCompleteForm[otherFn[-1]]}, {HoldCompleteForm[otherFn[0]]}, {HoldCompleteForm[otherFn[1]]}}}}}
(MCP Local shows Sessions`<id>`otherFn)
MCP Session: {{}, {}} *)
Who throws: Trace[Catch[api[<|...|>], _, List], _Throw] (it also lists the internal Throw calls of the parameter
interpreters).
Diagnostics inside the deployment
Message handlers, Stack, StackBegin, TimeConstrained and ScheduledTask stack sampling all work in deployed
kernels; Trace does not. What deployed code runs with:
owner = If[$CloudConnected, $CloudUserID]; (* $CloudUserID stays None until the kernel has connected *)
envApi = With[{owner = owner}, CloudDeploy[APIFunction[{}, <|
"EvaluationEnvironment" -> $EvaluationEnvironment, "RequesterWolframID" -> $RequesterWolframID,
"RunsAsOwner" -> ($CloudUserID === owner), "Notebooks" -> $Notebooks, "TraceWorks" -> (Trace[1 + 1] =!= {}),
"ProtectedMode" -> Developer`$ProtectedMode, "UserFilesDirectory" -> StringStartsQ[Directory[], "/wolframcloud/userfiles"],
"TimeRemaining" -> Internal`TimeRemaining[], "PID" -> $ProcessID|> &], "/debug-scratch/dbg-demo-env", Permissions -> "Public"]];
URLRead[First[envApi], "Body"] & /@ {1, 2}
(* {"<|\"EvaluationEnvironment\" -> \"WebAPI\", \"RequesterWolframID\" -> None, \"RunsAsOwner\" -> True, \"Notebooks\" -> True,
\"TraceWorks\" -> False, \"ProtectedMode\" -> True, \"UserFilesDirectory\" -> True, \"TimeRemaining\" -> 299.99, \"PID\" -> <pid1>|>",
"<|... \"PID\" -> <pid2>|>"} -- a fresh process for every request *)
- Deployed code runs as the owner even for anonymous callers (
$CloudUserIDis the owner,$RequesterWolframIDisNone), in protected mode, with a 300 s time limit, a fresh kernel per request,$NotebooksTrue (soEchooutput goes nowhere) and the owner's persistent user-files directory as the working directory (relative file writes persist). CloudDeploybundles the definitions of the non-System symbols the deployed expression uses (demoBodyabove, or the helper package if it was loaded before deploying).$CloudUserIDisNonein a fresh kernel until the first cloud operation; force the connection with$CloudConnectedbefore capturing it.
A wrapper that returns the normal result, or a JSON report (messages, stack at the first message, uncaught throw) with status 500:
diagApi = APIFunction[{"mode" -> "String", "x" -> "Integer" -> 1}, Module[{msgs = Internal`Bag[], st = {}, res},
res = Internal`HandlerBlock[{"Message", If[Last[#],
Internal`StuffBag[msgs, Replace[#, Hold[Message[mn_, ___], _] :> ToString[Unevaluated[mn], InputForm]]];
If[st === {}, st = Stack[_]]] &},
Catch[StackBegin[StackComplete[demoBody[#mode, #x]]], _, {"UncaughtThrow", ##} &]];
If[Internal`BagLength[msgs] == 0 && FreeQ[res, _Failure | "UncaughtThrow"], res,
HTTPResponse[ExportString[<|"Result" -> ToString[res, InputForm, TotalWidth -> 300],
"Messages" -> Internal`BagPart[msgs, All],
"Stack" -> With[{fr = Take[st, FirstPosition[st, _[_Message], {Length[st] + 1}, {1}][[1]] - 1]},
Replace[Take[fr, -Min[8, Length[fr]]], _[e_] :> ToString[Unevaluated[e], InputForm, TotalWidth -> 150], {1}]]|>,
"RawJSON", "Compact" -> True],
<|"StatusCode" -> 500, "ContentType" -> "application/json"|>]]] &];
diag = CloudDeploy[diagApi, "/debug-scratch/dbg-demo-diag", Permissions -> "Public"];
URLRead[HTTPRequest[First[diag], <|"Query" -> {"mode" -> #, "x" -> "3"}|>], {"StatusCode", "Body"}] & /@ {"ok", "msg", "throw"}
(* {<|"StatusCode" -> 200, "Body" -> "9"|>,
<|"StatusCode" -> 500, "Body" -> "{\"Result\":\"{ComplexInfinity, 3}\",\"Messages\":[\"Power::infy\"],\"Stack\":[
\"StackComplete[demoBody[\\\"msg\\\", 3]]\",\"demoBody[\\\"msg\\\", 3]\",\"Switch[\\\"msg\\\", \\\"ok\\\", 3^2, ...]\",
\"{1\\/0, 3}\",\"1\\/0\",\"0^(-1)\"]}"|>,
<|"StatusCode" -> 500, "Body" -> "{\"Result\":\"{\\\"UncaughtThrow\\\", 3, \\\"demo\\\"}\",\"Messages\":[],\"Stack\":[]}"|>}
GenerateHTTPResponse[diagApi, ...] gives the same responses locally *)
It does not catch an untagged Throw[v], Abort[] or time-outs. The helper does all of these, captures Print output,
can stop at a time limit below 300 s with the sampled stack, answers debug=1 requests with the report if you pass
"Debug" -> Automatic, and can log each report: APIFunction[{...}, WolframDebugging`HTTPDiagnostics[myBody[#x]] &];
load the package before CloudDeploy (options in HelperFunctions.md). Reports go to whoever calls the API and can
show parameters, intermediate values and code: debug a private deployment as its owner, and remove the wrapper when
done.
Logging from deployed code
The cloud keeps no messages, Print output or errors of deployed code (CloudLoggingData[obj] has call counts and
credits only). Log to a cloud object yourself; PutAppend takes 20 to 35 ms there:
log = CloudObject["/debug-scratch/dbg-demo-log"];
logApi = CloudDeploy[APIFunction[{"x" -> "Integer"},
(PutAppend[<|"x" -> #x, "time" -> DateString["ISODateTime", TimeZone -> 0]|>, log]; #x^2) &],
"/debug-scratch/dbg-demo-logapi", Permissions -> "Public"];
URLRead[HTTPRequest[First[logApi], <|"Query" -> {"x" -> ToString[#]}|>], "Body"] & /@ {1, 2}
{CloudGet[log], ReadList[log]}
(* {"1", "4"}
{<|"x" -> 2, "time" -> "2026-10-07T23:57:18"|>, {<|"x" -> 1, "time" -> "2026-10-07T23:57:17"|>, <|"x" -> 2, "time" -> "2026-10-07T23:57:18"|>}} *)
CloudGet returns only the last entry; read the log with ReadList. Pass TimeZone -> 0: cloud kernels do not run
in UTC. Log the same way from inside a deployed ScheduledTask (it runs with $EvaluationEnvironment "Scheduled").
CloudEvaluate
ceF[x_] := (Print["printed in the cloud"]; 1/x);
{CloudEvaluate[ceF[0]], CloudEvaluate[Trace[1 + 1]],
CloudEvaluate[Lookup[EvaluationData[ceF[0]], {"OutputLog", "MessagesExpressions"}]],
CloudEvaluate[{Length[Stack[_]], StackBegin[Length[Stack[_]]]}]}
(* Power::infy relayed and printed locally (twice: the first and the third call)
{ComplexInfinity, {}, {{"printed in the cloud"}, {Hold[Message[Power::infy, HoldCompleteForm[0^(-1)]]]}}, {66, 1}}
(wolframscript, MCP Local) *)
- Local definitions (
ceF) are sent along automatically; messages are relayed and printed locally;Printoutput is dropped (capture it withEvaluationDatainside theCloudEvaluate); Trace returns{}; about 65 wrapper frames sit on the stack (useStackBegin).Abort[]givesCloudEvaluate::srverrand$Failed. More inEnvironments.md.
Inspecting HTTP traffic
URLRead, URLExecute, CloudGet and CloudPut send their requests through URLFetch; Import of a URL and
URLDownload through URLSave. A guarded spy on URLFetch shows every request with its status, including errors that
URLExecute hides (works in MCP Local, MCP Session and wolframscript; see OverridesAndWatchpoints.md for the pattern):
Module[{log = Internal`Bag[], in = False, res},
URLFetch; (* load the autoload stub before the block *)
res = Internal`InheritedBlock[{URLFetch},
Unprotect[URLFetch];
PrependTo[DownValues[URLFetch], HoldPattern[URLFetch[url_, el_ : "Content", rest___] /; !in] :>
Block[{in = True}, With[{r = URLFetch[url, el, rest]},
Internal`StuffBag[log, {url, If[ListQ[el] && ListQ[r] && MemberQ[el, "StatusCode"],
r[[First[FirstPosition[el, "StatusCode"]]]], Head[r]]}]; r]]];
URLExecute["http://127.0.0.1:18765/missing.txt"]];
{StringTake[res, UpTo[50]], Internal`BagPart[log, All]}]
(* {"<!DOCTYPE HTML>\n<html lang=\"en\">\n <head>\n ", {{"http://127.0.0.1:18765/missing.txt", 404}}} *)
Helper: WolframDebugging`WithHTTPLog[expr] (function, method, URL, status and time of every request).
Where Trace works (MCP Local, wolframscript), TraceInternal -> True also lists the requests, with the final URL:
DeleteDuplicates @ Cases[Flatten[Trace[Quiet[URLExecute["http://127.0.0.1:1/x", {"a" -> "1"}]], _URLFetch, TraceInternal -> True]],
_[HoldPattern[URLFetch[u_String, ___]]] :> u]
(* {"http://127.0.0.1:1/x?a=1"} *)
Without HoldPattern the rule's left side URLFetch[u_String, ___] is evaluated and calls URLFetch
(URLFetch::invurl: u_String is not a valid URL).
The raw exchange of one request, in any local environment including MCP Local:
{status, debug} = URLFetch["http://127.0.0.1:18765/missing.txt", {"StatusCode", "DebugContent"}, "Debug" -> True];
{status, StringTake[debug, UpTo[400]]}
(* {404, " Trying 127.0.0.1:18765...\nEstablished connection to 127.0.0.1 (127.0.0.1 port 18765) from 127.0.0.1 port 54720 \n
using HTTP/1.x\nGET /missing.txt HTTP/1.1\r\nHost: 127.0.0.1:18765\r\nUser-Agent: Wolfram HTTPClient in Wolfram Language 15.\r\n
Accept: */*\r\nAccept-Encoding: deflate, gzip\r\nConnection: keep-alive\r\n\r\nRequest completely sent off\n
HTTP 1.0, assume close after body\nHTTP/1.0 404 File not found\r\nSer"} *)
Every request of a piece of code, with headers and bodies (libcurl trace to a file; global until stopped):
logFile = FileNameJoin[{$TemporaryDirectory, "curl-debug.log"}];
WithCleanup[CURLLink`StartDebugLog[logFile],
URLRead[HTTPRequest["http://127.0.0.1:18765/hello.txt", <|Method -> "POST", "Body" -> "a=1"|>]]["StatusCode"],
CURLLink`StopDebugLog[]];
{FileExistsQ[logFile], StringTake[Quiet[ReadString[logFile]], UpTo[300]]}
(* wolframscript, MCP Session:
{True, "23:54:47.000000 => Send header, 215 bytes (0xd7)\n0000: POST /hello.txt HTTP/1.1\n001a: Host: 127.0.0.1:18765\n
0031: Accept: */*\n003e: Accept-Encoding: deflate, gzip\n005e: Content-Type: text/plain;charset=utf-8\n..."}
MCP Local: {False, StringTake[$Failed, UpTo[300]]} *)
Do not use CURLLink`StartDebugLog in MCP Local; use the "Debug" option of URLFetch (above) there. logFile
is never written. Usually no trace is written at all, but in one run the trace went to a file with a garbled binary
name in the kernel's working directory (the project directory), so check ls -lt | head afterwards and delete it.
The == Info: lines (connecting, connection reuse) go to the kernel's stderr, not to the file (in MCP Session: the
server's stderr). The log contains Authorization headers and cookies of cloud requests: do not share it.
Request and response objects: req["URL"], req["Headers"], req["FormRules"] (for a rule-list body req["Body"]
stays unevaluated with HTTPResponse::encfailed), resp["StatusCode"], resp["Headers"], resp["ContentType"]. An
HTTPResponse carries no timing: wrap the call in AbsoluteTiming.
Network failures: the reason is only in the message
With[{ed = EvaluationData[URLRead[#, TimeConstraint -> 5]]},
{ed["Result"][[1]], ed["MessagesText"]}] & /@ {"http://127.0.0.1:1/x", "http://nonexistent-host.invalid/x"}
(* {{"ConnectionFailure", {"URLRead::invhttp : Failed to connect to 127.0.0.1 port 1 after 0 ms: Could not connect to server."}},
{"ConnectionFailure", {"URLRead::invhttp : Could not resolve host: nonexistent-host.invalid."}}}
(wolframscript, MCP Local) *)
- The
Failure["ConnectionFailure", ...]names only the URL; the cause (refused, DNS, time-out, TLS) is only in the::invhttpor::sslmessage, whichGeneral::stopsuppresses after three per evaluation. Capture messages (as here, or with a message handler) when debugging network code. URLReadandURLFetchhave no default time-out: useURLRead[url, TimeConstraint -> 10](connect plus transfer;URLRead::invhttp: Operation timed out after 1000 milliseconds with 0 bytes received.) orURLFetch[url, ..., "ConnectTimeout" -> 5, "ReadTimeout" -> 10]. SeeTracingAndPerformance.mdforTimeConstrained.- TLS problems:
URLRead::ssl: ... libcurl error (60): ...;VerifySecurityCertificates -> Falseconfirms the cause. - Proxy settings:
PacletManager`$InternetProxyRules(typing$InternetProxyRulesunqualified creates a new symbol).
CloudSubmit and cloud tasks
csLog = Internal`Bag[]; csDone = False;
csTask = CloudSubmit[Print["cs-print"]; 1/0; 42,
HandlerFunctions -> <|"MessageGenerated" -> (Internal`StuffBag[csLog, First[#MessageOutput]["MessageTag"]] &),
"PrintOutputGenerated" -> (Internal`StuffBag[csLog, #PrintOutput] &),
"TaskFinished" -> ((csDone = True; Internal`StuffBag[csLog, #EvaluationResult]) &)|>,
HandlerFunctionsKeys -> {"MessageOutput", "PrintOutput", "EvaluationResult"}];
TimeConstrained[While[!csDone, Pause[0.5]], 60]; Quiet[TaskRemove[csTask]];
{csDone, Internal`BagPart[csLog, All]}
(* {True, {"infy", HoldComplete["cs-print"], 42}} (wolframscript, about 10 s) *)
For CloudSubmit, "MessageGenerated" does fire (#MessageOutput is a MessageObject). An uncaught Throw never
finishes the task:
csDone = False;
csTask = CloudSubmit[Throw[7, "cstag"], HandlerFunctions -> <|"TaskFinished" -> ((csDone = True) &)|>];
TimeConstrained[While[!csDone, Pause[0.5]], 30]; {csDone, csTask["TaskStatus"], Quiet[TaskRemove[csTask]]; csTask["TaskStatus"]}
(* {False, "Running", "Removed"} *)
- Always time-limit the wait and
TaskRemovethe task: the local kernel cleans up the task's cloud objects when it sees the task finish, so a stuck task, or a submitting kernel that is killed, leaves two unnamed cloud objects behind. Tasks["Cloud"]andTasks[All]query the account's task objects and hung for more than 40 s on an account with many cloud objects: useTasks[](local tasks) or keep theTaskObject.
Definitions and source code
How to see what a symbol really does at run time (ReadProtected, Locked, kernel code, autoload stubs) and how to find the
source file and lines that define it (System functions implemented in paclets, package functions, your own files).
Read it when you need the definition of a function you did not write, want to read its source, or need to know which
copy of a package is in use. Behavior was checked with Wolfram 15.0 in MCP Local and wolframscript (see
Environments.md for these names).
Which tool for which question
| question | first choice | section |
|---|---|---|
what are the rules of f right now? | SymbolDefinition MCP tool; WolframDebugging`ShowDefinition[f] | Read the runtime definition |
Definition[f] shows nothing useful | ReadProtected, autoload stub, kernel code or Locked: check Attributes, OwnValues; WolframDebugging`SymbolKind[f] | same |
| a compact overview of a big function | Keys[DownValues[f]], usage text, dependency list | Compact views |
where is f defined (file and lines)? | contexts → FindFile/PacletFind → grep or CodeParser; WolframDebugging`FindSymbolSource["f"] | Find the source file |
| which installed copy is in use? | PacletFind[<|"Context" -> ctx|>] + $LoadedFiles | Which copy is loaded |
| full name of a symbol, which paclet declares it | Names["*`name"], Kernel extension scan | Names, paclets, message texts |
| text of a message | sym::tag with General::tag fallback; grep the message files | same |
| documentation of a paclet symbol | Documentation`ResolveLink + the ReadNotebook MCP tool | same |
| which option values does a call use? | OptionValue[f, {opts}, {names}], Trace[call, _OptionValue] | Effective options |
Helpers are in scripts/WolframDebugging.wl (load it with Get in its own call, call them fully qualified; options and
outputs: HelperFunctions.md). Everything below works without them.
The source is better for reading (comments, formatting, macros as written); the runtime definition is better for predicting behavior (it is what actually runs, after load-time macro expansion and with later redefinitions). Use both.
Read the runtime definition
The SymbolDefinition MCP tool
- Runs in the same kernel as the evaluator, so it sees your session's definitions and whatever packages that kernel has loaded. It bypasses ReadProtected and formats the result readably.
- Symbols you defined need their full name,
Sessions`<id>`f. A bare name givesError: Symbol "f" does not existplus a "Did you mean" list with the right full name (in MCP Local a bare name does find the symbols of the session that made the latest evaluator call, whichever session that was). - The
Attributesline omits ReadProtected (it is cleared before formatting):CloudPut // Attributes = { Protected }althoughAttributes[CloudPut]is{Protected, ReadProtected}. - Kernel functions show pseudo-rules:
+___ := "<kernel function>"forPlus. - Autoload stubs are shown as stubs (
GroupOrder := AutoLoad[Hold @ GroupOrder, ...]); the tool does not load them. Evaluate the bare symbol (GroupOrder;) in the evaluator first, then ask again. - Locked symbols: "No definitions found" for
$CommandLine(Locked, with a value: useDefinitiondirectly, see below);Error: ... is Locked and ReadProtectedwhen nothing can show them. - Use
maxLengthto keep the output small (default 10000 characters;CloudPutalone is 2555). - The wolfram-language skill's
SymbolDefinition.wlsscript starts a fresh kernel with the installed AgentTools: it shows stubs for every autoloaded System function (CloudPut = ActivateLoad[CloudPut, {URLDispatcher, ...) and never sees your evaluator definitions. Use the MCP tool, or a wolframscript that loads the symbol first. - The remote MCP server has no SymbolDefinition tool; use the recipes below in its evaluator.
ReadProtected: DownValues still works, Definition does not
ReadProtected hides rules only from Definition, FullDefinition, ?? and Language`ExtendedDefinition;
DownValues, UpValues, SubValues, OwnValues, Options, Messages and Attributes work as usual:
CloudPut; (* evaluating the bare symbol loads an autoload stub; nothing else happens *)
{Attributes[CloudPut], Length[DownValues[CloudPut]], Length[Options[CloudPut]],
StringTake[ToString[Definition[CloudPut], InputForm], UpTo[70]]}
(* {{Protected, ReadProtected}, 7, 13, "Attributes[CloudPut] = {Protected, ReadProtected}\n \nOptions[CloudPut] "} *)
Full Definition text: clear ReadProtected inside Internal`InheritedBlock (restored when the block exits) and convert
to a string inside the block:
CloudPut;
Internal`InheritedBlock[{CloudPut},
ClearAttributes[CloudPut, ReadProtected];
StringTake[ToString[Definition[CloudPut], InputForm], UpTo[250]]]
(* "Attributes[CloudPut] = {Protected}\n \nCloudPut[CloudObject`Private`expr_, CloudObject`Private`opts:OptionsPattern[]] :=
CloudObject`Private`WithProgressReporting[CloudObject`Private`cloudPut[Unevaluated[CloudObject`Private`expr], ..." *)
- The
ToStringmust be inside the block: aDefinition[...]returned from the block is formatted after ReadProtected is back and shows no rules (460 characters of attributes and options instead of 2664 forCloudPut). - Never
ClearAttributes[s, ReadProtected]outside the block in an MCP kernel: it is permanent and shared. - Without the leading
CloudPut;a fresh kernel (wolframscript) shows the autoload stub instead of the rules (CloudPut = Package`ActivateLoad[CloudPut, {URLDispatcher, ...). - The same applies to your own or package symbols. Some packages set ReadProtected on their symbols when built as
.mxfiles (AgentTools does for its public symbols; seeTesting.mdfor the CI consequence).Language`ExtendedDefinitionsilently returns an empty list then:
ClearAll[rpDemo]; rpDemo[x_] := x + 1; SetAttributes[rpDemo, ReadProtected];
{DownValues[rpDemo], ToString[Definition[rpDemo], InputForm], Language`ExtendedDefinition[rpDemo],
Internal`InheritedBlock[{rpDemo}, ClearAttributes[rpDemo, ReadProtected]; ToString[Definition[rpDemo], InputForm]]}
(* wolframscript: {{HoldPattern[rpDemo[x_]] :> x + 1}, "Attributes[rpDemo] = {ReadProtected}", Language`DefinitionList[], "rpDemo[x_] := x + 1"} *)
Helper: WolframDebugging`ShowDefinition[sym, n] (the InheritedBlock recipe with short contexts, at most n characters).
Kernel functions: no rules to show
Many System functions are implemented in C. They have no DownValues; System`Private`HasDownCodeQ tells (it holds
its argument, so a stub is not loaded):
{DownValues[Plus], ToString[Definition[Plus], InputForm],
System`Private`HasDownCodeQ /@ Unevaluated[{Plus, Table, CloudPut}]}
(* {{}, "Attributes[Plus] = {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected}\n \nDefault[Plus] := 0", {True, True, False}} *)
For kernel functions, read the documentation (WolframLanguageContext tool), SyntaxInformation[f] and the messages they
issue. Some System functions (e.g. Integrate) have both kernel code and WL rules loaded from the kernel's own .mx
files (no source ships for those).
Autoload stubs
Many System functions are stubs until first use. The stub is an OwnValue; looking at it does not load anything:
stubQ = Function[s, ! FreeQ[Quiet[OwnValues[s]], Package`ActivateLoad | System`Dump`AutoLoad], HoldAllComplete];
{stubQ[ResourceData], stubQ[GroupOrder], stubQ[Plus],
StringTake[ToString[OwnValues[ResourceData], InputForm], UpTo[150]],
StringTake[ToString[OwnValues[GroupOrder], InputForm], UpTo[75]]}
(* wolframscript: {True, True, False,
"{HoldPattern[ResourceData] :> Package`ActivateLoad[ResourceData, {ResourceData}, \"DataResourceLoader`\", {Package`HiddenImport -> True, Path -> Automat",
"{HoldPattern[GroupOrder] :> System`Dump`AutoLoad[Hold[GroupOrder], Hold[Gro"}
MCP Local: {False, False, False, "{}", "{}"} -- both already loaded by earlier calls in that long-running kernel *)
Package`ActivateLoad[sym, {syms}, "LoaderContext`", opts]= a paclet's Kernel extension (loadsLoaderContext`, the whole package);System`Dump`AutoLoad[Hold[sym], Hold[group], "Ctx`"] /; System`Dump`TestLoad= kernelSystemResources.mxfiles. The context in the stub tells you where the code lives.- Inspecting (
DownValues,Definition,Attributes, the SymbolDefinition tool) does not load a stub; evaluating the bare symbol (sym;) orOptions[sym]does. Load before you inspect or override (details:PackageLoading.md). - Helpers:
WolframDebugging`SymbolKind[sym](attributes, stub, kernel code, value counts, usage),WolframDebugging`AutoloadStubQ[sym],WolframDebugging`EnsureLoaded[sym].
Locked symbols
Block and Internal`InheritedBlock cannot localize a Locked symbol (::lockv, or Block::lockt with an initial
value; the InheritedBlock message has no text: "-- Message text not found --"), so every InheritedBlock-based tool
fails on them. A Locked symbol without ReadProtected can be read directly:
{Attributes[$CommandLine], Length[OwnValues[$CommandLine]],
StringTake[ToString[Definition[$CommandLine], InputForm], UpTo[48]],
Quiet[Internal`InheritedBlock[{$CommandLine}, 1]]}
(* {{Locked, Protected}, 1, "Attributes[$CommandLine] = {Locked, Protected}\n ", Internal`InheritedBlock[{$CommandLine}, 1]} *)
Locked and ReadProtected together (System` : I, $InputStreamMethods, $OutputStreamMethods, plus some package
internals): nothing shows them. OwnValues/DownValues give General::readp and $Failed, ClearAttributes fails
(Attributes::locked):
{Attributes[$InputStreamMethods], Quiet[OwnValues[$InputStreamMethods]],
Quiet[Internal`InheritedBlock[{$InputStreamMethods}, ClearAttributes[$InputStreamMethods, ReadProtected]]]}
(* {{Locked, Protected, ReadProtected}, $Failed, Internal`InheritedBlock[{$InputStreamMethods}, ClearAttributes[...]]} *)
Never set Locked on anything in a shared kernel: it cannot be undone for the rest of the kernel session.
Compact views of a big function
Signatures only (the left-hand sides, in the order the evaluator tries them):
CloudPut;
Block[{$ContextPath = Join[{"CloudObject`Private`"}, $ContextPath]},
ToString[#, InputForm] & /@ Keys[DownValues[CloudPut]]]
(* {"HoldPattern[CloudPut[expr_, opts:OptionsPattern[]]]", "HoldPattern[CloudPut[expr_, obj_CloudObject, opts:OptionsPattern[]]]",
"HoldPattern[CloudPut[expr_, uri_String, opts:OptionsPattern[]]]", "HoldPattern[CloudPut[expr_, uriwrapper:_URL | _Hyperlink, opts:OptionsPattern[]]]",
"HoldPattern[CloudPut[expr_, failureObj_Failure, opts:OptionsPattern[]]]", "HoldPattern[CloudPut[expr_, obj_, opts:OptionsPattern[]]]",
"HoldPattern[e:CloudPut[args___]]"} *)
Putting the definition's private context on $ContextPath while formatting shortens the names. The order of
DownValues is the kernel's try order (more specific first, literal arguments before patterns), not source order; here
the _Failure rule is 5th at run time but last in the source, and _URL | _Hyperlink was written $LinkWrappers (a
macro expanded at load time).
Usage as plain text (usage strings contain box syntax):
StringRiffle[ToString[#, OutputForm] & /@ StringSplit[CloudPut::usage, "\n"], "\n"]
(* "CloudPut[expr] writes expr to a new anonymous cloud object.\nCloudPut[expr, \"uri\"] writes expr to a cloud object at a given URI.\n..." *)
Package usage messages exist only after the package is loaded. Definition does not include ::usage.
Helper functions a definition uses (the symbols it references, with their own definitions). The default
"ExcludedContexts" -> Automatic also drops package contexts, and ReadProtected symbols are skipped silently:
CloudPut;
With[{d = Language`ExtendedFullDefinition[CloudObject`Private`cloudPut, "ExcludedContexts" -> {"System`"}]},
{Length[d], Take[Cases[List @@ d, (_[s_] -> defs_) :> {ToString[Unevaluated[s], InputForm], Length[Lookup[defs, DownValues]]}], UpTo[3]]}]
(* {11, {{"CloudObject`Private`cloudPut", 2}, {"CloudObject`Private`opts", 0}, {"CloudObject`Private`handleCBase", 4}}} *)
DownValues, Attributes, Options and friends hold their argument: inside Module they inspect the local variable.
Use With to insert the symbol:
ClearAll[hdDemo]; hdDemo[x_] := x;
{Module[{h = hdDemo}, DownValues[h]], With[{h = hdDemo}, DownValues[h]]}
(* {{}, {HoldPattern[hdDemo[x_]] :> x}} *)
Find the source file
Works when the package ships .wl/.m source (most paclets in $InstallationDirectory/SystemFiles/Components,
SystemFiles/Links, AddOns/Applications and the user paclet repository do). The steps: context → entry file → paclet
root → search.
1. Which context holds the code?
For a System function implemented in a paclet, Context["CloudPut"] is just System` . Look at the contexts of the
symbols inside its definition (or at the loader context in its stub), then give FindFile the package context without
trailing Private` parts:
CloudPut;
{DeleteDuplicates @ Cases[DownValues[CloudPut], s_Symbol :> Context[Unevaluated[s]], Infinity, Heads -> True],
FindFile["CloudObject`"], FindFile["CloudObject`Private`"]}
(* {{"System`", "CloudObject`Private`", "System`Private`"}, "~/.Wolfram/Paclets/Repository/CloudObject-15.0.9/Kernel/CloudObject.m", $Failed} *)
2. The paclet root
For a context, ask the paclet manager (all candidates, the one in use first):
{#["Name"], #["Version"], #["Location"]} & /@ PacletFind[<|"Context" -> "CloudObject`"|>]
(* {{"CloudObject", "15.0.9", "~/.Wolfram/Paclets/Repository/CloudObject-15.0.9"},
{"CloudObject", "15.0.0", "/usr/local/Wolfram/Wolfram/15.0/SystemFiles/Links/CloudObject"}} *)
For a file, walk up to the directory with PacletInfo.wl/PacletInfo.m. The often-quoted
NestWhile[DirectoryName, file, Not @* PacletObjectQ @* PacletObject @* File] works for files inside a paclet (with a
PacletManager`CreatePaclet::badarg message for every level below the root) but never terminates for a file outside
one: DirectoryName["/"] is "", DirectoryName[""] is "" again, and PacletObject[File[""]] is a Failure. Capped
at 6 steps, the loop sits on "":
{TimeConstrained[Quiet @ NestWhile[DirectoryName, "/tmp/foo/bar.m", Not @* PacletObjectQ @* PacletObject @* File], 2],
Quiet @ NestWhileList[DirectoryName, "/tmp/foo/bar.m", Not @* PacletObjectQ @* PacletObject @* File, 1, 6]}
(* {$Aborted, {"/tmp/foo/bar.m", "/tmp/foo/", "/tmp/", "/", "", "", ""}} *)
A version that always stops (at most 64 levels, without the final ""):
pacletRootOf[file_String] := SelectFirst[
DeleteCases[Rest @ NestWhileList[DirectoryName, file, StringLength[#] > 0 &, 1, 64], ""],
FileExistsQ[FileNameJoin[{#, "PacletInfo.wl"}]] || FileExistsQ[FileNameJoin[{#, "PacletInfo.m"}]] &,
Missing["NotInPaclet", file]];
{pacletRootOf[FindFile["CloudObject`"]], pacletRootOf[FindFile["CodeParser`"]], pacletRootOf["/tmp/foo/bar.m"]}
(* {"~/.Wolfram/Paclets/Repository/CloudObject-15.0.9/", "/usr/local/Wolfram/Wolfram/15.0/SystemFiles/Components/CodeParser/",
Missing["NotInPaclet", "/tmp/foo/bar.m"]} *)
(The result ends in /, as DirectoryName returns it.) Helper: WolframDebugging`PacletRoot[file] (no trailing /,
Missing["NotFound", file] outside paclets).
The source files of the paclet, relative to its root:
With[{root = First[PacletFind[<|"Context" -> "CloudObject`"|>]]["Location"]},
{Length[#], Take[#, 4]} &[StringDelete[FileNames[{"*.wl", "*.m"}, root, Infinity], StartOfString ~~ root ~~ "/"]]]
(* {62, {"Kernel/AccountData.m", "Kernel/BackupUtilities.wl", "Kernel/CharacterEncoding.m", "Kernel/CloudBase.m"}} *)
3. Search the files
grep with your own file tools (fast; finds top-level definitions written at column 0, including e : f[...] :=,
Options[f] = and Attributes[f] =; misses definitions indented or nested in With/Module):
grep -rnE --include='*.m' --include='*.wl' '^([A-Za-z$][A-Za-z0-9$]* *: *)?(HoldPattern\[)?(Options\[|Attributes\[)?CloudPut\b' <paclet root>
# Kernel/GetPutSave.m:254:Options[CloudPut] = $defaultOptions[CloudPut] = sortOptions @ objectFunctionOptionsJoin[
# Kernel/GetPutSave.m:518:CloudPut[expr_, opts : OptionsPattern[]] :=
# Kernel/GetPutSave.m:521:CloudPut[expr_, obj_CloudObject, opts:OptionsPattern[]] :=
# ... 540, 546, 549
# Kernel/GetPutSave.m:555:e : CloudPut[args___] := Null /; (System`Private`Arguments[e, {1, 2}]; False)
# Kernel/GetPutSave.m:557:CloudPut[expr_, failureObj_Failure, opts:OptionsPattern[]] := failureObj
A plain '^CloudPut\[' misses the e : CloudPut[...] and Options[CloudPut] lines. Then read the lines around each hit.
GeneralUtilities`FindDefinition (preloaded; a first guess): FileLine[file, line] of the first match of a line
regex; $Failed for the .wl-based paclets tried (CodeParser, AgentTools), .mx-only code and kernel functions. It can
also land on a message line (ResourceData → DataResource/Kernel/Messages.m:24, a ResourceData::elemstring text).
{GeneralUtilities`FindDefinition[CloudPut], GeneralUtilities`FindDefinition[CodeParser`CodeParse],
GeneralUtilities`FindDefinition[Plus]}
(* {GeneralUtilities`FileLine["~/.Wolfram/Paclets/Repository/CloudObject-15.0.9/Kernel/GetPutSave.m", 518], $Failed, $Failed} *)
CodeParser (exact source text of each top-level definition). The parser annotates top-level Set/SetDelayed/
TagSet/UpSet nodes with a "Definitions" list; with "SourceCharacterIndex" the Source is a character range for
StringTake. Use fully qualified CodeParser names: typed in the same input as the Needs, short names are created in your
own context and the pattern silently matches nothing:
Needs["CodeParser`"]; (* full names below, so this works in the same input *)
Module[{file, ast, pos},
file = FileNameJoin[{First[PacletFind[<|"Context" -> "CloudObject`"|>]]["Location"], "Kernel", "GetPutSave.m"}];
ast = CodeParser`CodeParse[File[file], "SourceConvention" -> "SourceCharacterIndex"]; (* never print an AST *)
pos = Cases[ast, _[_, _, KeyValuePattern[{"Definitions" -> {CodeParser`LeafNode[Symbol, "CloudPut" | "System`CloudPut", _]},
CodeParser`Source -> p_}]] :> p, Infinity];
{Length[pos], StringTake[ReadString[file], pos[[{1, -1}]]]}]
(* {7, {"CloudPut[expr_, opts : OptionsPattern[]] :=\n WithProgressReporting[cloudPut[Unevaluated[expr], saveDefToIncludeDef[{opts}]]]",
"CloudPut[expr_, failureObj_Failure, opts:OptionsPattern[]] := failureObj"}} *)
- The name in
"Definitions"is the literal source text: match both"f"and"Ctx`f". - Only top-level assignments are annotated (
f[a_] := 1;alone on its line is): definitions insideWith/Module/Ifand both definitions off[a_] := 1; f[b_] := 2on one line are not.f::usage,Options[f] =,Attributes[f] =andFormat[f] :=carry"AdditionalDefinitions"instead. - Without
"SourceConvention",Sourceis{{line1, col1}, {line2, col2}}(line numbers for your Read tool). - Parse only the files that mention the name (prefilter with
StringContainsQ[ReadString[f], name]): a whole large paclet takes seconds.
Helper: WolframDebugging`FindSymbolSource["Ctx`name"] does all three steps (contexts from the definition or stub,
paclet roots, CodeParser including nested definitions, fallback to $LoadedFiles for loose files) and returns file, line
range, kind and a text preview per definition.
Which copy is loaded
FindFile and PacletFind name the copy the next Get would load: the highest version, so updated system paclets in
the user paclet repository (~/.Wolfram/Paclets/Repository) shadow the installation's copy, and a newer installed
paclet beats a development checkout added with PacletDirectoryLoad. $LoadedFiles is what this kernel actually read:
CloudPut;
{FindFile["CloudObject`"], Take[Select[$LoadedFiles, StringContainsQ["CloudObject"]], UpTo[2]]}
(* {"~/.Wolfram/Paclets/Repository/CloudObject-15.0.9/Kernel/CloudObject.m",
{"~/.Wolfram/Paclets/Repository/CloudObject-15.0.9/Kernel/CloudObjectLoader.m", "~/.Wolfram/Paclets/Repository/CloudObject-15.0.9/Kernel/CloudObject.m"}} *)
Read the source of the copy that $LoadedFiles lists. After a .mx build or an edit made after the kernel started, the
source and the running code differ (PackageLoading.md).
No source: .mx-only components and kernel code
Some components ship only a loader and a compiled .mx file (in 15.0 among others GeneralUtilities, Dataset, Forms,
Templating, URLUtilities, TypeSystem, NeuralNetworks, Authentication, Streaming). Kernel functions and the kernel's own
SystemFiles/Kernel/SystemResources/*.mx code never ship source. Check before you search:
With[{root = First[PacletFind[<|"Context" -> "GeneralUtilities`"|>]]["Location"]},
{root, FileNameTake /@ FileNames["*.mx", root, Infinity], FileNameTake /@ FileNames[{"*.m", "*.wl"}, root, Infinity]}]
(* {"/usr/local/Wolfram/Wolfram/15.0/SystemFiles/Components/GeneralUtilities", {"GeneralUtilities.mx"},
{"GeneralUtilitiesLoader.m", "GeneralUtilities.m", "PacletInfo.m"}} *)
.mx files present and no grep hits: only the runtime definition is available (SymbolDefinition tool, DownValues).
Names, paclets and message texts
Names
CloudPut;
{Names["*InheritedBlock*"], Names["*`*InheritedBlock*"], Names["*`*CloudPut*"], Names["CloudObject`Private`cloudPut*"],
Names["CloudPu", SpellingCorrection -> True], Context["CloudPut"]}
(* {{}, {"Internal`InheritedBlock"}, {"CloudPut", "CloudObject`Private`iCloudPut"}, {"CloudObject`Private`cloudPut"}, {"CloudPut"}, "System`"} *)
- Without a backtick in the pattern,
Namessearches only$Contextand$ContextPath: use"*`*name*"to search all contexts. Symbols on the context path come back short ("CloudPut"). Names["*`name"]lists every context that has a symbol calledname(shadowing check, seePackageLoading.md).Names["*`*"]has about 63,000 entries in a fresh kernel and over 200,000 in MCP Local: always wrap searches inLengthorTake.- Typing an unknown name creates the symbol in your context, where it can shadow a package symbol. Pass names as strings:
{Quiet[Context["dsNoSuchName"]], Names["*`dsNoSuchName"], Context[dsNoSuchName2], Names["*`dsNoSuchName2"]}
(* wolframscript: {Context["dsNoSuchName"], {}, "Global`", {"dsNoSuchName2"}}
MCP evaluator: {Context["dsNoSuchName"], {}, "Sessions`<id>`", {"dsNoSuchName2"}} *)
PacletFind pitfalls
Only "Context" filters an association query; any other key ("Symbol", "Symbols", a typo) is ignored silently and
returns every paclet:
{Length[PacletFind[All]], Length[PacletFind[All, <|"Symbol" -> "System`CloudPut"|>]],
#["Name"] & /@ PacletFind[All, <|"Context" -> "CodeParser`"|>]}
(* {355, 355, {"CodeParser"}} (the count depends on the installation) *)
Which paclet declares an autoloaded System symbol (scan the Kernel extensions; well under 0.1 s):
{#["Name"], #["Version"]} & /@ Select[PacletFind[All],
MemberQ[Flatten @ Cases[#["Extensions"], {"Kernel", ___, "Symbols" -> s_, ___} :> s], "System`CloudPut"] &]
(* {{"CloudObject", "15.0.9"}, {"CloudObject", "15.0.0"}} *)
Never return a PacletObject or PacletFind[All] itself: each object prints its whole PacletInfo. Take properties
(#["Name"], #["Version"], #["Location"]).
Message texts
Message looks for sym::tag first and falls back to General::tag; Messages[sym] lists only the specific texts, and
system texts are loaded lazily (in a fresh kernel Messages[General] has only about 75 entries), so neither list is
complete. A lookup that mirrors Message:
msgText = Function[{s, tag}, Replace[MessageName[s, tag],
_MessageName :> Replace[MessageName[General, tag], _MessageName :> Missing["NoText", tag]]], HoldFirst];
CloudPut;
{msgText[CloudPut, "invcloudobj"], msgText[Power, "infy"], msgText[Block, "lockv"], msgText[Internal`InheritedBlock, "lockv"]}
(* {"`1` is not a valid cloud object.", "Infinite expression `1` encountered.",
"Cannot localize locked symbol `1` in local variable specification `2`.", Missing["NoText", "lockv"]} *)
Missing["NoText", ...] is what prints as "-- Message text not found --". To find a message by its text, grep the files:
system texts are in $InstallationDirectory/SystemFiles/Kernel/TextResources/English/Messages.m (e.g. line 1537
General::infy = "Infinite expression `1` encountered."); package texts are in the package source
(grep -rn 'invcloudobj *=' <paclet root> → Kernel/Messages.m:127:General::invcloudobj = ...).
Documentation
{Documentation`ResolveLink["paclet:ref/CloudPut"], Information[CloudPut, "Documentation"],
Documentation`ResolveLink["paclet:Wolfram/AgentTools/ref/CreateMCPServer"]}
(* {URL["https://reference.wolfram.com/language/ref/CloudPut.html?v=15.0"], <|"Web" -> "http://reference.wolfram.com/language/ref/CloudPut.html"|>,
".../Documentation/English/ReferencePages/Symbols/CreateMCPServer.nb"}
wolframscript: the installed paclet's notebook (~/.Wolfram/Paclets/Repository/Wolfram__AgentTools-2.2.0/...);
MCP Local: the development checkout loaded by that server -- the same version shadowing as for code *)
- Paclet symbols:
ResolveLink["paclet:Publisher/Paclet/ref/Name"]gives the local reference notebook; read it with the ReadNotebook MCP tool (as Markdown; reference pages are long). The pattern is<paclet root>/Documentation/English/ReferencePages/Symbols/<Name>.nb. - System symbols: installations without local reference pages (the Linux installation checked here has none) get the
web URL from
ResolveLink. Use the WolframLanguageContext MCP tool.
Effective options
ClearAll[optDemo]; Options[optDemo] = {"A" -> 1, "B" -> 2};
optDemo[x_, opts : OptionsPattern[]] := {x, OptionValue["A"], OptionValue["B"]};
{OptionValue[optDemo, {"A" -> 7}, {"A", "B"}], Options[optDemo, "B"], OptionValue[CloudPut, {}, {CloudBase, Permissions}],
Internal`InheritedBlock[{optDemo}, SetOptions[optDemo, "A" -> 99]; optDemo[0]], optDemo[0]}
(* {{7, 2}, {"B" -> 2}, {Automatic, Automatic}, {0, 99, 2}, {0, 1, 2}} *)
OptionValue[f, {opts}, {names}]: the values a call withoptsgets (explicit options, thenOptions[f]).- Try a different default without leaking it:
SetOptionsinsideInternal`InheritedBlock[{f}, ...]. A plainSetOptionsin an MCP kernel changes the option for every session. Options[stub]loads an autoload stub (it evaluates its argument).
Where Trace works (MCP Local, wolframscript; not in MCP Session or the cloud), see the options a call really received:
ClearAll[optDemo]; Options[optDemo] = {"A" -> 1, "B" -> 2};
optDemo[x_, opts : OptionsPattern[]] := {x, OptionValue["A"], OptionValue["B"]};
Trace[optDemo[0, "A" -> 10], _OptionValue]
(* {{HoldCompleteForm[OptionValue[optDemo, {"A" -> 10}, "A"]]}, {HoldCompleteForm[OptionValue[optDemo, {"A" -> 10}, "B"]]}}
(MCP Local shows Sessions`<id>`optDemo; MCP Session gives {}) *)
Environment notes
- MCP Local and MCP Session: long-running kernels with many packages already loaded; which System functions are still stubs depends on what earlier calls used. wolframscript: a fresh kernel, so most System packages are stubs until used.
- CloudEvaluate:
Definitionis broken there (CloudEvaluate[ToString[Definition[Plus], InputForm]]gives"$Failed"withSetDelayed::writeandAttributes::attnfmessages; the InheritedBlock recipe fails the same way) whileDownValuesworks; useDownValues/OwnValues. Source files exist in cloud kernels too, andGeneralUtilities`FindDefinitionworks there. - Remote MCP server: no SymbolDefinition tool;
ToString[Definition[...], InputForm]and the InheritedBlock recipe work in its evaluator. - Output size: never return an AST, a
PacletObject,Names["*`*"]or a wholeDefinitionof a big function; take aStringTake/Length/Keysview first.
Gotchas
- ReadProtected blocks only
Definition-style views;DownValuesworks (not on Locked+ReadProtected symbols). Convert to a string insideInternal`InheritedBlock; never clear ReadProtected or set attributes permanently in a shared kernel. - Load autoload stubs first (
sym;): every inspection, the SymbolDefinition tool included, shows the stub. The tool needs full names for your own symbols and omits ReadProtected from its Attributes line. FindFilewants the package context ("CloudObject`"), not aPrivate`subcontext;PacletFindwith any key but"Context"returns everything.- The
NestWhile[DirectoryName, ...]paclet-root loop never ends outside a paclet; use the bounded version or the helper. DownValuesorder is try order, not source order, and rules can differ from the source text (macros expanded at load time).FindDefinitiongives the first regex hit only and$Failedfor.wlpaclets.Nameswithout a backtick misses most contexts; typing an unknown name creates it.
Evaluation environments
How the places where Wolfram Language code can run differ when you debug: the MCP evaluator (Local and Session
methods), wolframscript, wolfram -script, CloudEvaluate, deployed APIs and the remote MCP server. Covers how to tell
where you are, the full behavior matrix, how to run code and load the helper package in each environment, what never to
do in a shared kernel, and how to keep output small. Read it first when something works in one place but not in another.
Behavior was checked with Wolfram 15.0 on Linux.
The environments
| name | what runs your code | state between calls |
|---|---|---|
| MCP Local | WolframLanguageEvaluator with Method "Local": a protected-mode sandbox subkernel (-noinit -pacletreadonly) started by the MCP server and shared by every session and agent of that server | persists until the subkernel restarts (time-out of a non-abortable call, crash, Quit[]) |
| MCP Session | Method "Session", the default for installed local servers: the MCP server's own kernel | persists; definitions are restored from a session file after a server restart (loaded packages, handlers and Off settings are not) |
| wolframscript | wolframscript -f file.wls or wolframscript -code '...': a fresh kernel per run, init files loaded | none |
wolfram -script | a plain kernel running a file; the TestReport MCP tool runs tests this way (-script .../TestReport.wls -noinit) | none |
| CloudEvaluate | CloudEvaluate[expr] from any local kernel (also from MCP Local): a cloud kernel | none |
| deployed API | APIFunction/Delayed/FormFunction deployed with CloudDeploy: a fresh cloud kernel per request | none (see CloudAndHTTP.md) |
| remote MCP server | Method "Cloud" server such as https://agenttools.wolfram.com/mcp: a fresh cloud kernel per call, no session parameter | none |
| notebook | the desktop front end | persists (not covered by the checks in this skill) |
The wolfram-language skill's bundled scripts/WolframLanguageEvaluator.wls runs the evaluator tool inside a fresh
wolframscript kernel: Trace works, $Context is Sessions`<id>` , the time limit is 60 s, and passing
--session <id> from the previous run restores that run's definitions (not its loaded packages).
You cannot change the evaluator method from inside a call; it is part of the server configuration.
Where am I? (run this first)
Module[{cl = StringRiffle[ToString /@ $CommandLine, " "]},
<|"Env" -> Which[
$EvaluationEnvironment === "Script", "wolframscript",
$EvaluationEnvironment === "WebEvaluation", "CloudEvaluate",
$EvaluationEnvironment === "WebAPI", "deployed API or remote MCP server",
StringContainsQ[cl, "ChatbookSandbox"], "MCP Local",
StringContainsQ[cl, "StartMCPServer"] || StringStartsQ[$Context, "Sessions`"], "MCP Session",
MemberQ[$CommandLine, "-script"], "wolfram -script",
True, $EvaluationEnvironment],
"TraceWorks" -> (Trace[1 + 1] =!= {}),
"ProtectedMode" -> TrueQ[Developer`$ProtectedMode],
"Context" -> $Context,
"PID" -> $ProcessID,
"TimeRemaining" -> Round[Internal`TimeRemaining[], 0.1]|>]
MCP Local: <|"Env" -> "MCP Local", "TraceWorks" -> True, "ProtectedMode" -> True, "Context" -> "Sessions`<id>`", "PID" -> ..., "TimeRemaining" -> 60.|>
MCP Session: <|"Env" -> "MCP Session", "TraceWorks" -> False, "ProtectedMode" -> False, "Context" -> "Sessions`<id>`", "PID" -> ..., "TimeRemaining" -> 60.|>
wolframscript: <|"Env" -> "wolframscript", "TraceWorks" -> True, "ProtectedMode" -> False, "Context" -> "Global`", "PID" -> ..., "TimeRemaining" -> Infinity|>
wolfram -script: <|"Env" -> "wolfram -script", "TraceWorks" -> False, "ProtectedMode" -> False, "Context" -> "Global`", "PID" -> ..., "TimeRemaining" -> Infinity|>
CloudEvaluate: <|"Env" -> "CloudEvaluate", "TraceWorks" -> False, "ProtectedMode" -> True, "Context" -> "Global`", "PID" -> ..., "TimeRemaining" -> 300.|>
remote MCP server: <|"Env" -> "deployed API or remote MCP server", "TraceWorks" -> False, "ProtectedMode" -> True, "Context" -> "Global`", "PID" -> ..., "TimeRemaining" -> 60.|>
The bundled skill script reports "wolframscript" with "Context" -> "Sessions`<id>`" and "TimeRemaining" -> 60.; the
TestReport MCP tool's kernel reports "wolfram -script". A notebook falls through to "Session" (untested). Helper:
WolframDebugging`EnvironmentInfo[] (adds the user contexts, whether the input runs under Quiet, and notes on what
that means); see HelperFunctions.md.
Gotchas:
$Notebooksand$FrontEnddo not tell you whether a notebook exists: they areTrue/aFrontEndObjectin the cloud andFalse/Nullin MCP Local although a headless front end is attached there (seeHeadlessAndCrashes.md).- Detecting MCP Session by
$Contextalone fails insideBegin[...]or package code; check$CommandLineas above. Wolfram`AgentTools`$MCPEvaluationEnvironmentis not a detector: it describes the server, isNonein the Local subkernel, and mentioning it elsewhere creates the context.- The first access of
$CloudConnectedtakes about 3 s; keep it out of quick probes. - On the remote MCP server every input runs inside
Quiet:Lookup[Internal`QuietStatus[], "Global"]gives"Quiet"there. Do not wrap that call inQuiet(it then always says"Quiet").
The environment matrix
| behavior | MCP Local | MCP Session | wolframscript | wolfram -script | CloudEvaluate | deployed API | remote MCP server |
|---|---|---|---|---|---|---|---|
Trace, TraceScan, TracePrint, On[sym] | work | {} | work | {} | {} | {} | {} |
$Context | Sessions`<id>` | Sessions`<id>` | Global` | Global` | Global` | Global` | Global` |
| context of symbols typed in the code | Sessions`<id>` | Sessions`<id>` | Global` | Global` | Global` | Global` | Global` |
symbols created at run time (ToExpression, Get of a plain file) | Sessions`<id>` | Sessions`<id>` | Global` | Global` | Global` | Global` | Global` |
unqualified package symbol after Get/Needs | resolves from the next input (next line) | resolves from the next input (next line) | resolves from the next line of -f | next line | n/a | n/a | n/a |
Symbol::undefined warning before evaluation | undefined upper-case names (not ones defined or localized in the same input) | same as MCP Local | no | no | no | no | upper-case Global` symbols |
| definitions persist across calls | yes (until a restart) | yes (restored after a restart) | no | no | no | no | no |
%, Out[n] | work (one line number per input) | work (one line number per input) | no history | no history | no history | no history | no history |
Length[Stack[]] as the whole input (1 = no wrapper frames) | 1 | 1 | 16 (about 90 KB of frames) | 2 | 65 | about 50 | 1 |
willPrint flag of message handlers | normal | normal | normal | normal | normal | normal | always False |
$MessageList reset | every input | never (server lifetime, all sessions; General::stop counts across calls) | once per script | once per script | every call | every request | every call |
| message after more than 10 prints + messages in one call | shown | dropped | shown | shown | relayed | lost | dropped |
Print / Echo | shown with a During evaluation of In[n]:= prefix | same as MCP Local | stdout | stdout | dropped | lost | Print shown, Echo dropped |
Abort[] in user code | $Aborted, Print kept, later inputs of the call skipped | same as MCP Local | ends the whole script (exit code 0) | ends the whole script (exit code 0) | $Failed + CloudEvaluate::srverr | HTTP 500, empty body | $Aborted, Print kept |
| tool time limit reached (it covers the whole call) | Failure["EvaluationTimeExceeded", ...] with Out[n]=, Print kept, later inputs skipped, state kept | same as MCP Local | no limit unless you add one | no limit | 300 s | 300 s (then HTTP 502) | only the Failure (Print lost) |
time limit hit by a non-abortable call (Run, AbortProtect, long primitives) | subkernel killed about 20 s after the limit and restarted (22 s for a 3 s limit, 28 s for a 10 s limit); the Failure comes without Out[n]= and the Print output of the input that timed out without its label (earlier inputs of the call keep theirs); all state lost | the response arrives only when the call finishes: the Failure (AbortProtect), or for a blocking Run its normal result with the later inputs run; state kept | n/a | n/a | n/a | n/a | n/a |
$RecursionLimit overflow | enclosing expression becomes TerminatedEvaluation["RecursionLimit"] | same | ends the whole script | a statement ending in ; is dropped, otherwise like MCP Local; later lines run | uncaught Throw | not checked | like MCP Local |
Quit[], Exit[] | kills the shared subkernel: only a General::quit message comes back, new PID, everyone's state lost | intercepted (General::quit), later inputs skipped, state kept | exits | exits | no-op | not checked | General::quit, rest of the input skipped |
Input, InputString, Dialog, ChoiceDialog | InputString: no response at all, whatever the time limit (none within 240 s with a 10 s limit) | InputString: server hangs (no response, limit ignored) | InputString: EndOfFile with stdin /dev/null, blocks forever on an open silent stdin; ChoiceDialog prints its prompt in a loop | EOF | not checked | not checked | not checked |
WriteString["stdout", ...], Run[...] | shown / $Failed | corrupt the JSON-RPC stream | stdout | stdout | n/a | n/a | n/a |
protected mode: Run, RunProcess, StartProcess, LaunchKernels, LocalSubmit blocked | yes | no | no | no | yes | yes | yes |
| file writes | only below $TemporaryDirectory, others give a silent $Failed | anywhere | anywhere | anywhere | persistent cloud user files | persistent cloud user files | a throwaway directory |
global settings, handlers, Off[...] | leak to every session and agent | leak to every session and the server itself; can kill it | this run | this run | this call | this request | this call |
| first-time effects (autoloads, first package load) | rarely (many packages preloaded) | rarely | yes | yes | rarely | rarely | rarely |
init.m, InitializationValue | not loaded (-noinit) | not loaded (-noinit) | loaded ("Script" values) | loaded ("Session" values) | not loaded | not loaded | not loaded |
front end for Rasterize/Export | pre-launched with the subkernel | launched on first use (5-10 s) | launched on first use | launched on first use | built in (default 144 dpi) | built in | built in |
| SymbolDefinition MCP tool | same kernel; name Sessions`<id>`f | same kernel; name Sessions`<id>`f | n/a | n/a | n/a | n/a | not offered |
Internal`TimeRemaining[] | about 60 | about 60 | Infinity | Infinity | 300 | 300 | about 60 |
How to use the matrix:
- Trace: check
Trace[1 + 1] =!= {}first. Where it is{}, use message handlers withStack,Internal`InheritedBlockspies or stack sampling (MessagesAndStacks.md,OverridesAndWatchpoints.md,TracingAndPerformance.md), or run the Trace in wolframscript. $MessageList: useBlock[{$MessageList = {}}, expr]when you count messages (it is Protected; assigning fails).- Out history:
%andOut[n]work in the MCP evaluator, but every input of a call gets its own line number, so assign results to variables instead of counting lines. - MCP Local prints your unevaluated symbols in the
Out[n]=text with their full context (Out[1]= Sessions`<id>`f[Sessions`<id>`x], whileToString[f[x]]gives"f[x]"); MCP Session printsf[x]. - Fresh kernel: where you would
Quit[]in a notebook to start over, never do that in MCP; run the code in wolframscript instead. First-time effects (autoloading, package loading events,GeneralUtilities`TraceLoadingoutput) only show there, because MCP kernels have already loaded many packages. - Time limits and aborts: return diagnostics as the value of the call, not as
Printoutput (see "Output budget"). - After a time-out or a crash in MCP Local, check
{$ProcessID, SessionTime[]}: a new PID (or a smallSessionTime[]) means the subkernel was restarted and all definitions are gone.Out[n]keeps counting, so the line number does not show it. - The remote MCP server quiets everything: wrap the code under test in
Quiet[expr, None, All]to see realwillPrintflags and to makeEvaluationDataandVerificationTestrecord messages (Checkcatches them even without it):EvaluationData[1/0; 2]["MessagesExpressions"]gives{}there,Quiet[EvaluationData[1/0; 2], None, All]["MessagesExpressions"]gives{Hold[Message[Power::infy, HoldCompleteForm[0^(-1)]]]}.
Contain a $RecursionLimit overflow with Catch (this gave the same result in MCP Local, MCP Session, wolframscript,
wolfram -script, CloudEvaluate and the remote MCP server):
ClearAll[rec]; rec[n_] := rec[n + 1] + 1;
{Catch[Block[{$RecursionLimit = 50}, rec[0]], _TerminatedEvaluation, Function[{v, tag}, Failure["RecursionLimit", <|"Tag" -> tag|>]]], "after"}
(* $RecursionLimit::reclim: Recursion depth of 50 exceeded.
{Failure["RecursionLimit", <|"Tag" -> TerminatedEvaluation["RecursionLimit", 50]|>], "after"} *)
In the MCP evaluators the Catch does not see the overflow when it is the whole input or sits directly inside If,
With or the right-hand side of a function you call: it returns TerminatedEvaluation["RecursionLimit"] without
calling its handler. Inside a list, res = Catch[...]; ..., Module, Block, Table, another Catch or as a
function argument it works (checked in both methods), so also test the value (MessagesAndStacks.md). In
CloudEvaluate the 64 wrapper frames count toward the limit: Block[{$RecursionLimit = 50}, 1 + 1] already overflows
there.
MCP Local: never let the first message of a fresh subkernel happen under a low $RecursionLimit. The first message
the subkernel prints makes the evaluator load packages inside your evaluation. Under a limit of 30 or 50 that load fails:
Block[{$RecursionLimit = 30}, Message[General::argx, f, 2]; 1] returned TerminatedEvaluation["RecursionLimit"]
instead of 1, and $Context stayed EntityFramework`Private` (WolframAlphaClient`Private` in another run)
for every later call of every session, so new symbols went there. A quieted overflow did no harm, and after one ordinary
message (1/0; in an earlier call) the same code was safe. MCP Session was not affected.
Where your symbols live
ClearAll[demoFn];
demoFn[x_] := x;
{$Context, Context[demoFn], MemberQ[{"Global`", $Context}, Context[demoFn]]}
(* MCP Local, MCP Session: {"Sessions`<id>`", "Sessions`<id>`", True}
wolframscript, CloudEvaluate, remote MCP server: {"Global`", "Global`", True} *)
- Each MCP evaluator session has its own context
Sessions`<id>`, its$Context, and does not see the definitions of other sessions. Code meant for several environments should accept both user contexts: filter user symbols withMemberQ[{"Global`", $Context}, Context[s]](Context[s] === "Global`"misses them in the MCP evaluator), and put both on the context path when you format expressions (below). - In MCP Local one subkernel runs every session: definitions stay separate, but global settings, handlers, loaded
packages and symbols with an explicit context (
Global`x,dbg`f) are shared. - When a Chatbook update is installed in the user paclet directory (checked with Chatbook 2.7, whose installer paclet
loads it at every kernel start, also with
-noinit), wolframscript andwolfram -scriptstart withWolfram`Chatbook`on$ContextPath(with an empty user base directorywolfram -scripthad only{"System`", "Global`"}). Defining a function whose name is one of the roughly 100 exported Chatbook symbols then fails; check withMemberQ[$ContextPath, "Wolfram`Chatbook`"]:CellToString[x_] := x + 1; {CellToString[1], Context[CellToString]} (* wolframscript, wolfram -script: SetDelayed::write: Tag CellToString in CellToString[x_] is Protected. {"1", "Wolfram`Chatbook`"} MCP Local, MCP Session: {2, "Sessions`<id>`"} remote MCP server: {2, "Global`"} *) - When strings are made from expressions, symbols of a context that is not on
$ContextPathprint with their context. Put both user contexts on the context path while formatting:Block[{$ContextPath = Join[{"Global`", $Context}, $ContextPath]}, ToString[Hold[demoX[1]], InputForm]] (* "Hold[demoX[1]]" *) - SymbolDefinition MCP tool: give the full name,
Sessions`<id>`demoFn. A bare name returns "does not exist" plus a "Did you mean" list that contains the right full name.
Each input is parsed just before it runs
The MCP evaluator splits the code of a tool call into top-level inputs (a line, or an expression that spans several
lines) and parses each one right before it is evaluated, after the inputs before it have run. A -f file works the
same way; a -code string is one input. Each input gets its own In[n]; an Out[n]= is shown only for an input that
does not end in ; and whose result is not Null (when no output would be shown at all, the last one is).
So a Get or Needs on its own line makes short names work from the next line on, but a name in the same input as
the Get is created in the current context first. With a small package EnvDemo.wl (BeginPackage["EnvDemo`"],
exported square[x_] := x^2), one tool call:
Get["/tmp/EnvDemo.wl"]
{EnvDemo`square[3], square[3], Context[square]}
(* MCP Local, MCP Session, two lines of a -f script: {9, 9, "EnvDemo`"} *)
Get[...]; square[3] as one input leaves Sessions`<id>`square[3] unevaluated in the MCP evaluator (in a -f
script: square::shdw and Global`square[3]). A fully qualified name works everywhere, even in the same input as the
Get. So: load on its own line (or in its own call), and call package functions by their full names.
The inputs of a call run one after the other. Abort[], the time limit (which covers the whole call) and Quit[] stop
the remaining inputs; an uncaught Throw only ends its own input:
Print["a"]
Throw[1]
"after"
(* MCP Local, MCP Session:
During evaluation of In[1]:= a
Throw::nocatch: Uncaught Throw[1] returned to top level.
Out[2]= Hold[Throw[1]]
Out[3]= "after" *)
The MCP evaluator also repairs incomplete input without a warning: a missing ], } or ) is added at the end of the
line where appending it at the very end would join two lines into an implicit multiplication. Usually that is what you
meant; wolframscript reports the syntax error instead.
envF[x_] := Module[{y},
y = x + 1
envF[2]
(* MCP Local, MCP Session: Out[n]= 3, and the definition is envF[x_] := Module[{y}, y = x + 1] *)
{1, 2 gives {1, 2} the same way. Check pasted code with the CodeInspector MCP tool when results look impossible (see
HeadlessAndCrashes.md).
Running code in each environment
MCP evaluator tool. Omit session on the first call and pass the returned id afterwards (this keeps your
definitions, $Context and In/Out history). Give long probes an inner limit below the tool limit so that you get
partial results back:
TimeConstrained[Pause[3]; "finished", Min[1, Internal`TimeRemaining[] - 10], $TimedOut]
(* $TimedOut *)
wolframscript.
-code '...'runs one input and prints the result in OutputForm (strings lose their quotes):wolframscript -code '{2, "s", 1/2}'prints{2, s, 1/2}; add-format InputFormto get{2, "s", 1/2}.-f file.wlsprints only explicitPrintoutput (-printprints the last result,-print allevery non-Null one). Each top-level expression is parsed after the previous one ran, but the file is one evaluation:$Linestays 1,$MessageListandGeneral::stopaccumulate over the file, andAbort[], an uncaughtThrow(afterThrow::nocatch) or a$RecursionLimitoverflow end the rest of the script, with exit code 0:Print[{$Line, Length[$MessageList]}]; 1/0; Print[{$Line, Length[$MessageList]}]; Abort[]; Print["never printed"];
The order of{1, 0} $Aborted 1 Power::infy: Infinite expression - encountered. 0 {1, 1}Printoutput and messages in the captured stdout is not reliable ($Abortedcame before the message). Underwolfram -scriptthe same file prints{0, 0}and{0, 1}and nothing after the abort.- Messages go to stdout and never change the exit code;
Exit[n]does. - Always bound runs and redirect output to files (a lingering kernel or front end keeps a pipe open):
Plaintimeout -s KILL 300 wolframscript -f test.wls < /dev/null > out.txt 2> err.txt; echo "exit=$?" # 0 = finished, 137 = time limit (GNU timeout; uutils timeout gives 124) or killed from outside (e.g. out of # memory: compare the run time with the limit), 139 = kernel crash (segfault)timeout 300sends SIGTERM, which a busy wolframscript ignores:timeout 5 wolframscript -code 'Pause[25]; 1'ran for 30 s, printed1and "The product exited for an unknown reason.". After a kill, look for kernels you started that were left behind (ps -o pid,ppid,etime,args -C WolframKernel, parent PID 1) and kill only those. -timeout Nprints$TimedOutand exits with code 0.
wolfram -script file. Trace records nothing, $Line is 0, init files are loaded unless you add -noinit, an
uncaught Throw ends the script without a message, and Abort[] ends it too. wolfram -noinit -script file starts the
way MCP servers do; wolfram -sandbox -noinit -script /abs/path/file adds protected mode (use an absolute path:
a relative one gave Get::noopen). See HeadlessAndCrashes.md.
CloudEvaluate works from any local kernel, including MCP Local (about 1 s per call); definitions of the non-System symbols in the expression are sent along:
CloudEvaluate[{$EvaluationEnvironment, Trace[1 + 1], Print["dropped"]; Length[Stack[]]}]
(* {"WebEvaluation", {}, 67} -- no Trace, Print dropped, 64 wrapper frames above the 3 of this input *)
Abort[] there gives CloudEvaluate::srverr and $Failed; General::stop can appear twice (relayed and local);
relative file writes land in the persistent cloud user-files directory.
Remote MCP server. Stateless JSON-RPC over HTTP; no initialize is needed for a single call. The response is JSON or
Server-Sent Events (data: {...} lines):
curl -s https://agenttools.wolfram.com/mcp -H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"WolframLanguageEvaluator","arguments":{"code":"{$EvaluationEnvironment, Trace[1 + 1], Internal`TimeRemaining[]}"}}}'
# ... "text":"Out[1]= {\"WebAPI\", {}, 59.999908}" ...
Each call starts a new kernel (Out[1]= every time), so put everything into one input. Deployed APIs: see
CloudAndHTTP.md.
Loading the helper package in each environment
The helper package is scripts/WolframDebugging.wl in this skill directory (functions in HelperFunctions.md):
Get["/absolute/path/to/wolfram-debugging/scripts/WolframDebugging.wl"] (* on its own line or in its own call *)
WolframDebugging`CollectMessages[myFunction[1, 2]] (* fully qualified, on a later line *)
| environment | how |
|---|---|
| MCP Local, MCP Session | Get on its own line (or alone in a call); then WolframDebugging`Name[...] on later lines or in later calls |
wolframscript -f, wolfram -script | Get[...] on its own line; Print[ToString[WolframDebugging`Name[...], InputForm]] |
wolframscript -code | wolframscript -code 'Get["..."]; WolframDebugging`Name[...]' -format InputForm (full names work in the same input) |
| CloudEvaluate | load locally, then CloudEvaluate[WolframDebugging`Name[...]]; the definitions are sent along (ShowDefinition gives "Null" there) |
| deployed API | load locally before CloudDeploy; non-System definitions are bundled (see CloudAndHTTP.md) |
| remote MCP server | no local files: use the helper-free recipes of the references; Get of a public URL works, but publishing a copy needs the user's consent |
Safety rules for shared and server kernels
MCP Local is one kernel shared by every session and agent of the server; in MCP Session your code runs inside the server process. Whatever you leave behind affects everyone, and some actions take the server down.
Never do this in an MCP evaluator:
Quit[],Exit[](MCP Local: all state of all agents is lost).Input,InputString,Dialog,ChoiceDialog,TraceDialogor anything else that reads stdin (InputStringgives no response at all, whatever the time limit; in MCP Session the whole server hangs).DialogInputjust returns$Failed.Run[...](never abortable; in MCP Session its output goes into the JSON-RPC stream) andWriteString["stdout", ...]or any handler that writes to"stdout"in MCP Session.- Top-level settings:
$RecursionLimit = ...(a value of 77 closed an MCP Session server),$IterationLimit,Off[...],SetOptions[...],SetSystemOptions[...].$Preand$Posthave no effect in either method. - In MCP Local, a low
$RecursionLimit(even in aBlock) before the subkernel has printed its first message: the failed package load leaves$Contextset to a package's private context for every session (see above). Internal`AddHandlerwithout removing the handler in the same call: it fires in every session and, in MCP Session, also for the server's own quieted messages.- Unscoped redefinitions of System or package functions; overriding
ToString,Print,MessageorWriteLineeven briefly in MCP Session (the server formats its responses with them). SetAttributes[..., Locked],ClearAll/Removeof System symbols;LockedandTemporaryset insideBlockorInternal`InheritedBlockare not undone.- Probing unknown internals:
Package`PackageInformation[]andRuntimeTools`SetExecutionState[{"RuntimeAnalysisTools" -> True}]crash the kernel. Use a throwaway wolframscript. TaskRemove[Tasks[]](removes other agents' tasks); remove only the tasks you created.- Returning huge results: they are kept in the session and formatting them can take a minute.
Scoped equivalents:
| instead of | use |
|---|---|
$RecursionLimit = n | Block[{$RecursionLimit = n}, expr] |
Off[f::tag] | Quiet[expr, f::tag] |
Internal`AddHandler["Message", h] | Internal`HandlerBlock[{"Message", h}, expr] (one handler pair per block; nest for more) |
redefining f (System or package) | Internal`InheritedBlock[{f}, Unprotect[f]; PrependTo[DownValues[f], HoldPattern[lhs] :> rhs]; expr] (see OverridesAndWatchpoints.md) |
SetOptions[f, opt -> v] | pass the option, or Internal`InheritedBlock[{f}, SetOptions[f, opt -> v]; expr] |
SetSystemOptions[...] | WithCleanup that restores the old value (below) |
{Internal`InheritedBlock[{Plot}, SetOptions[Plot, PlotTheme -> "Scientific"]; Options[Plot, PlotTheme]], Options[Plot, PlotTheme]}
(* {{PlotTheme -> "Scientific"}, {PlotTheme :> $PlotTheme}} *)
With[{old = SystemOptions["CompileOptions" -> "TableCompileLength"]},
{WithCleanup[SetSystemOptions["CompileOptions" -> {"TableCompileLength" -> Infinity}],
SystemOptions["CompileOptions" -> "TableCompileLength"],
SetSystemOptions[old]],
SystemOptions["CompileOptions" -> "TableCompileLength"]}]
(* {{"CompileOptions" -> {"TableCompileLength" -> Infinity}}, {"CompileOptions" -> {"TableCompileLength" -> 250}}} *)
If a global handler is unavoidable, add and remove it in one call; WithCleanup also runs the cleanup on aborts, throws
and time-outs:
Module[{h, seen = Internal`Bag[], n0 = Length[Last[Internal`Handlers["Message"]]]},
h = Function[m, Internal`StuffBag[seen, Last[m]]];
WithCleanup[Internal`AddHandler["Message", h], Quiet[1/0], Internal`RemoveHandler["Message", h]];
{Internal`BagPart[seen, All], Length[Last[Internal`Handlers["Message"]]] - n0}]
(* {{False}, 0} -- the handler saw the quieted message; no handler is left behind *)
Output budget
Large output wastes context and time: MCP responses are cut to about 10 KB, formatting a multi-megabyte result can take over a minute, and a single raw stack can be hundreds of KB. Rules:
- Never return raw stacks, traces,
TestReportObjectorPacletObjectexpressions, ASTs or long lists. End big intermediate results with;and return counts,Dimensions,Take[..., UpTo[n]]or truncated strings. Shortdoes nothing here (the page width is infinite). Truncate withTotalWidth; it does not shorten long strings, so addStringTake. Very small widths can fail withFormat::toobig; stay above about 40.
Module[{big = Range[10^5], long = StringRepeat["abc", 200]},
{StringLength[ToString[big, InputForm]],
StringLength[ToString[Short[big], InputForm]],
ToString[big, InputForm, TotalWidth -> 60],
ToString[big, InputForm, TotalWidth -> 20],
StringLength[ToString[long, InputForm, TotalWidth -> 60]],
StringTake[ToString[long, InputForm, TotalWidth -> 60], UpTo[40]]}]
(* {688895, 688902, "{1, 2, 3, 4, 5, 6, 7, <<99990>>, 99998, 99999, 100000}", "{1, <<99999>>}", 602,
"\"abcabcabcabcabcabcabcabcabcabcabcabcabc"} *)
- For held stack frames or trace items use
ToString[Unevaluated[e], InputForm, TotalWidth -> n]inside aReplace[..., (HoldCompleteForm | HoldForm)[e_] :> ..., {1}](15.0 wraps frames inHoldCompleteForm, older versions inHoldForm), neverFirst/ReleaseHold(that evaluates the frame again). The helperWolframDebugging`ShortString[expr, n]does this, including theGlobal`context fix. - Return diagnostics as the value of the call (an association or a short string), collected in an
Internal`Bag.PrintandEchoare dropped by CloudEvaluate,Echoby the remote MCP server (Block[{$Notebooks = False}, Echo[...]]makes it visible there),Printis lost on time-outs on the remote MCP server (after an MCP Local subkernel restart it arrives without its label), and MCP Session and the remote MCP server drop messages after 10 prints and messages in one call.
Getting the Wolfram Engine
The bundled scripts in this skill require wolframscript, the command-line interface to the Wolfram Language. This guide covers installation on each platform.
Check If Already Installed
Run the following in your terminal:
wolframscript -code '1+1'
If it prints 2, you're ready to go — no further setup needed.
macOS
Via Homebrew (recommended)
brew install --cask wolfram-engine
After installation, wolframscript should be available on your PATH automatically.
Manual Download
- Download the Wolfram Engine from https://www.wolfram.com/engine/.
- Open the
.dmgand drag Wolfram Engine to Applications. - Run the app once to complete activation.
wolframscriptis installed at/usr/local/bin/wolframscript.
Linux
- Download the
.shinstaller from https://www.wolfram.com/engine/. - Run:
sudo bash WolframEngine_*_Linux.sh - Follow the prompts and activate when complete.
After installation, wolframscript is typically at /usr/bin/wolframscript.
Windows
- Download the installer from https://www.wolfram.com/engine/.
- Run the
.exeinstaller and follow the prompts. - Activate when prompted.
wolframscript.exeis added to your PATH automatically. If not, the default location is:C:\Program Files\Wolfram Research\WolframScript\wolframscript.exe
Activation
The Wolfram Engine is free for development use but requires activation with a Wolfram Account. If you don't have one, create an account at https://account.wolfram.com.
When you first run wolframscript, it will prompt for activation. You can also activate manually:
wolframscript -activate
Troubleshooting
wolframscriptnot found — Ensure the install directory is on your PATH. You can check the location withwhich wolframscript(macOS/Linux) orwhere wolframscript(Windows).- Activation fails — Check your internet connection and verify your Wolfram Account credentials at https://account.wolfram.com.
- License issues — The free Wolfram Engine license covers non-production development use. For production or commercial use, see https://www.wolfram.com/engine/commercial-options/.
More Information
- Wolfram Engine: https://www.wolfram.com/engine/
- Wolfram Account: https://account.wolfram.com
Headless kernels, startup differences, crashes and hard hangs
What changes when code that was written in a notebook runs headless (MCP evaluator, wolframscript, cloud), how the
environments start differently, how to compare two environments, what a kernel crash looks like in each environment and
how to find the line that crashes, what no time limit can interrupt, how to launch processes safely, cheap static checks,
and a few smaller facts (Catch/Throw, memory, Function Repository, Instrumentation` ). Environment names are defined
in Environments.md. Behavior was checked with Wolfram 15.0 on Linux; no desktop notebook was available for the checks.
Notebook-only functions fail headless
Headless kernels have no notebook. These return $Failed and issue FrontEndObject::notavail in MCP Local, MCP
Session, wolframscript and wolfram -script, and return $Failed without any message in CloudEvaluate, deployed APIs
and the remote MCP server: NotebookDirectory[], EvaluationNotebook[], Notebooks[], SelectedNotebook[],
CreateDocument[...], NotebookPut[...], CurrentValue[...], FrontEndExecute[...], FrontEndTokenExecute[...],
CopyToClipboard[...], DialogInput[...] and SystemDialogInput[...]. SetOptions[EvaluationNotebook[], ...] stays
unevaluated as SetOptions[$Failed, ...] with SetOptions::optnf.
{NotebookDirectory[], Head[Quiet[EvaluationNotebook[]]] === NotebookObject}
(* MCP Local, MCP Session, wolframscript:
FrontEndObject::notavail: A front end is not available; certain operations require a front end.
{$Failed, False}
CloudEvaluate, remote MCP server: {$Failed, False} -- no message at all *)
- The message is subject to
General::stop: after three of them in one evaluation, further notebook calls fail silently (in MCP Session the count can include messages of earlier calls of the session).Check[expr, alt, FrontEndObject::notavail]still catches the suppressed ones locally, but never fires in the cloud. - The failure usually surfaces later as a secondary error:
SetDirectory[NotebookDirectory[]]givesSetDirectory::badfileabout$Failed;FileNameJoin[{NotebookDirectory[], "data.csv"}]builds a bad path. - Not every notavail is a failure:
Monitor[...]prints the message but returns its result.PrintTemporarybehaves likePrintin MCP and wolframscript;MessageDialog["text"]prints the text;CellPrintprints the cell's text (in CloudEvaluate and on the remote MCP serverMessageDialogandCellPrintreturn$Failedsilently). $Notebooks/$FrontEndare no guard ($NotebooksisTrueand$FrontEndis set in the cloud). Guard notebook-only code withIf[Head[Quiet[EvaluationNotebook[]]] === NotebookObject, ...], which isTrueonly in a notebook or insideUsingFrontEnd[...].- Results: the MCP evaluator returns
PlotandManipulateresults as images andDynamic/Buttonas text; test the function behind aManipulatewith explicit parameter values instead.
Headless replacements:
| notebook idiom | headless replacement |
|---|---|
NotebookDirectory[], SetDirectory[NotebookDirectory[]] | an explicit absolute path; in a package, DirectoryName[$InputFileName] captured while the file loads (below) |
CreateDocument, NotebookPut, NotebookWrite | build Notebook[{Cell[...], ...}] and Put it to a .nb file (no front end needed; Export to .nb starts a headless front end) |
NotebookImport[f, "Input" -> "InputText"], NotebookEvaluate[f] | extract the input cells as held expressions (below) and evaluate them in order; headless, NotebookImport returns a list of Failure["InterpretationFailure", ...] and NotebookEvaluate stays unevaluated |
ChoiceDialog, DialogInput, Input, InputString | make the answer a function argument or option |
Monitor, PrintTemporary, ProgressIndicator, Dynamic | return progress data instead |
CurrentValue, FrontEndExecute, CopyToClipboard | delete, or guard as above |
Locate files relative to the package at load time. With a package that contains
$dir = DirectoryName[$InputFileName] at top level and dirLater[] := DirectoryName[$InputFileName]:
{EnvDemo`$dir, EnvDemo`dirLater[]}
(* after Get["/tmp/EnvDemo.wl"]:
MCP Local: {"/tmp/", ""}
MCP Session: {"/tmp/", ".../Scripts/"} directory of the server's start script (repository dev server)
wolframscript -f s: {"/tmp/", "<directory of s>"}
wolframscript -code: {"/tmp/", ""} *)
DirectoryName[""] is "", and FileNameJoin[{"", "data.csv"}] is "/data.csv", so a late
FileNameJoin[{DirectoryName[$InputFileName], "data.csv"}] silently points at the file system root.
Read a notebook's input cells without a front end:
Module[{file = "/tmp/demo.nb"},
Put[Notebook[{Cell[BoxData[RowBox[{"x", "=", RowBox[{"1", "+", "1"}]}]], "Input"],
Cell["Some text", "Text"], Cell[BoxData[SuperscriptBox["x", "2"]], "Input"]}], file];
Cases[Import[file, "Notebook"],
Cell[BoxData[b_], "Input" | "Code", ___] :> ToExpression[b, StandardForm, HoldComplete], Infinity]]
(* {HoldComplete[x = 1 + 1], HoldComplete[x^2]}
(in the MCP evaluator x is created in Sessions`<id>`, where run-time symbols go; MCP Local shows Sessions`<id>`x) *)
Does this code use the front end?
Every front end request goes through MathLink`CallFrontEnd. Count the requests with a never-matching rule inside
Internal`InheritedBlock (works in MCP Local, MCP Session, wolframscript and CloudEvaluate; the only signal in the cloud,
where no message is issued):
Module[{calls = Internal`Bag[], r},
r = Internal`InheritedBlock[{MathLink`CallFrontEnd},
Unprotect[MathLink`CallFrontEnd];
PrependTo[DownValues[MathLink`CallFrontEnd],
HoldPattern[MathLink`CallFrontEnd[a_, ___] /; (Internal`StuffBag[calls, Head[Unevaluated[a]]]; False)] :> Null];
Quiet[{NotebookDirectory[], ImageDimensions[Rasterize[Graphics[Disk[]], ImageResolution -> 72]]}]];
{r, Counts[Internal`BagPart[calls, All]]}]
(* MCP Local: {{$Failed, {360, 360}}, <|FrontEnd`EvaluationNotebook -> 1, FrontEnd`Value -> 2, FrontEnd`ExportPacket -> 1|>}
wolframscript, MCP Session (first rendering, 5-10 s):
{{$Failed, {360, 360}}, <|FrontEnd`EvaluationNotebook -> 1, FrontEnd`SetOptions -> 1, FrontEnd`Value -> 2, FrontEnd`ExportPacket -> 1|>}
CloudEvaluate (no notavail message):
{{$Failed, {360, 360}}, <|FrontEnd`EvaluationNotebook -> 1, FrontEnd`Value -> 4, FrontEnd`SetOptions -> 2, FrontEnd`FrontEndExecute -> 1, List -> 1, FrontEnd`ExportPacket -> 1|>} *)
FrontEnd`ExportPacket/FrontEnd`Value = rendering (works headless, slow the first time);
FrontEnd`EvaluationNotebook, FrontEnd`NotebookPutReturnObject and similar = needs a real notebook. Helper:
WolframDebugging`FrontEndCalls[expr, timeout] (also reports front end messages and whether a front end was launched).
Rendering launches a headless front end
Rasterize, Export to PNG/PDF, Image[graphics] and even ExportString[g, "SVG"] start a headless front end
(WolframNB ... -platform offscreen, about 190 MB) on first use: 5-10 s in wolframscript and MCP Session. The MCP Local
subkernel gets one at startup; it runs in protected mode and cannot launch a new one, so if it loses it, Rasterize
returns $Failed with Rasterize::nofe until the subkernel restarts (checked by killing that front end). A
wolfram -sandbox kernel gives Rasterize::nofe (and Developer`UseFrontEnd::nofestart for UsingFrontEnd). Plain
ToString[Graphics[...]] is "-Graphics-" and needs no front end.
The default resolution differs between local kernels and the cloud. Pass ImageResolution, RasterSize or ImageSize
whenever pixel sizes matter:
AbsoluteTiming[{ImageDimensions[Rasterize[Graphics[Disk[]]]],
ImageDimensions[Rasterize[Graphics[Disk[]], ImageResolution -> 72]]}]
(* MCP Local, MCP Session, wolframscript (front end already running): {0.03, {{480, 480}, {360, 360}}}
CloudEvaluate: {..., {{720, 719}, {360, 360}}} *)
UsingFrontEnd[expr] gives a script a front end for notebook operations (UsingFrontEnd[EvaluationNotebook[]] returns a
NotebookObject), but after UsingFrontEnd[NotebookEvaluate[file]] the kernel, the front end and its helper kernel keep
running after the script ends and hold stdout open: end such scripts with Developer`UninstallFrontEnd[].
Dialogs and standard input
Never call ChoiceDialog, Input, InputString, Dialog or TraceDialog in an MCP evaluator or a script: headless
they fall back to reading stdin. (DialogInput and SystemDialogInput just return $Failed with
FrontEndObject::notavail.)
| environment | effect |
|---|---|
| MCP Session | the server hangs forever; the tool time limit does not help (checked with InputString: no response within 100 s with a 10 s limit) |
| MCP Local | no response at all, whatever the time limit (checked with InputString: none within 240 s with a 10 s limit) |
| wolframscript | InputString returns EndOfFile when stdin is /dev/null; on an open stdin that never sends data it blocks forever (the kernel even survived killing wolframscript, until stdin closed); ChoiceDialog with /dev/null printed its prompt in an endless loop (67,000 times in 10 s); Dialog[] printed In[2]:= and ended without a result |
wolframscript -code 'InputString["prompt> "]' -format InputForm < /dev/null
# prompt> EndOfFile
Always run scripts with < /dev/null.
Startup differences
| environment | how the kernel starts |
|---|---|
| installed MCP server | WolframKernel -run PacletSymbol["Wolfram/AgentTools", "Wolfram`AgentTools`StartMCPServer"][] -noinit -noprompt |
| MCP Local subkernel | WolframKernel -wstp -noicon -noinit -pacletreadonly -run ChatbookSandbox..., then protected mode |
| wolframscript | WolframKernel -runfirst ... (sets $EvaluationEnvironment = "Script"); init files are loaded |
wolfram -script | init files loaded unless -noinit is given; TestReport MCP tool: -script .../TestReport.wls -noinit |
| CloudEvaluate, remote | WolframKernel -noinit -nopaclet -run ... |
# probe.wls:
# Print[ToString[{$EvaluationEnvironment, TrueQ[Developer`$ProtectedMode], Trace[1 + 1] =!= {}, $ContextPath,
# Select[$LoadedFiles, StringEndsQ[#, "init.m"] && !StringStartsQ[#, $InstallationDirectory] &]}, InputForm]]
wolframscript -f probe.wls # {"Script", False, True, {"WolframScript`", "Wolfram`Chatbook`", "System`", "Global`"}, {"/usr/share/Wolfram/Kernel/init.m", "~/.Wolfram/Kernel/init.m"}}
wolfram -script probe.wls # {"Session", False, False, {"Wolfram`Chatbook`", "System`", "Global`"}, {same two init.m files}}
wolfram -noinit -script probe.wls # {"Session", False, False, {"Wolfram`Chatbook`", "System`", "Global`"}, {}}
wolfram -sandbox -noinit -script /abs/probe.wls # {"Session", True, False, {...}, {}} (a relative path gave Get::noopen)
What this means:
-noinit(every MCP server and the cloud) skips theinit.mfiles (user and$BaseDirectory) andInitializationValue(the installation'sAddOns/Autoloadpackages still load). Anything they set is missing:$Pathentries ("the package is found in the notebook but not here"),SetOptions,Off[...],$HistoryLength. Reproduce an MCP server's startup withwolfram -noinit -script repro.wls, the Local subkernel with-noinit -pacletreadonly, and protected mode with-sandbox.InitializationValueis stored per$EvaluationEnvironment: values set underwolfram -script("Session", as in a notebook; not checked there) are not applied in wolframscript ("Script"), and the reverse.$ContextPath: wolframscript addsWolframScript`, MCP Local and MCP Session have{"Sessions`<id>`", "System`"}and CloudEvaluate 36 contexts.Wolfram`Chatbook`in the probe output above comes from the user base of the machine checked here, which has a Chatbook update installed (an empty user base gave{"System`", "Global`"}); with it, defining a function named like a Chatbook symbol (CellToString, ...) fails in wolframscript andwolfram -script(seeEnvironments.md).- Persistence locations differ, which changes
PersistentSymbol,Once[..., "Local"]andLocalCache:
{Replace[$PersistencePath, Verbatim[PersistenceLocation][t_, ___] :> t, {1}],
Replace[$PersistenceBase, Verbatim[PersistenceLocation][t_, ___] :> t], $LocalBase}
(* wolframscript, MCP Session: {{"KernelSession", "Local", "Local", "Installation"}, "Local", "file:///<home>/.Wolfram/Objects"}
MCP Local (fresh subkernel): {{"KernelSession", "Installation"}, "KernelSession", "file:///tmp/m000001<pid>1/LocalObjects"} *)
In MCP Local, PersistentSymbol["name"] does not see values stored in the user's "Local" location (it is not on
$PersistencePath; PersistentSymbol["name", "Local"] finds them), and Once[..., "Local"] results are recomputed
after every subkernel restart (the $LocalBase is per process; the long-running subkernel of one server showed the
home directory's $LocalBase, so check it). (Verbatim is needed: a bare PersistenceLocation[t_, ___] pattern
evaluates and issues PersistenceLocation::unknown.)
- Kernel-lifetime state: memo values survive a redefinition, and
Once[expr]is computed once per kernel, which in MCP means once per server or subkernel lifetime, across all calls and sessions:
ClearAll[memo]; memo[x_] := memo[x] = x^2; memo[2]; memo[x_] := memo[x] = x^3;
{memo[2], memo[3]}
(* {4, 27} -- the stale memo[2] = 4 from the old definition is still used; ClearAll before redefining *)
- Other differences seen:
$CharacterEncoding("UTF8"in wolframscript,"UTF-8"elsewhere),$TimeZoneandLANG(the cloud uses America/Chicago anden_US.UTF-8),Directory[](the client's project root in MCP Local), the default ofPlotHighlighting(Nonein the cloud), environment variables (an MCP server inherits them from the MCP client), and the version of aResourceFunction(the locally cached one; pin withResourceVersion -> "x.y.z").
Comparing two environments
Record the same facts in both environments and diff them. Evaluate this definition in each environment:
ClearAll[envFingerprint];
envFingerprint[] := <|
"Version" -> $Version, "EvaluationEnvironment" -> $EvaluationEnvironment,
"ProtectedMode" -> TrueQ[Developer`$ProtectedMode], "TraceWorks" -> (Trace[1 + 1] =!= {}),
"Context" -> $Context, "ContextPath" -> $ContextPath, "Path" -> $Path,
"InitFiles" -> Select[$LoadedFiles, StringEndsQ[#, "init.m"] && !StringStartsQ[#, $InstallationDirectory] &],
"Directory" -> Directory[], "CharacterEncoding" -> $CharacterEncoding, "TimeZone" -> $TimeZone,
"RecursionLimit" -> $RecursionLimit, "HistoryLength" -> $HistoryLength, "LocalBase" -> $LocalBase,
"MessageHandlers" -> Length[Last[Internal`Handlers["Message"]]]|>;
In environment A (MCP Local can write below /tmp):
Put[envFingerprint[], "/tmp/fpA.wl"]
In environment B:
With[{a = Get["/tmp/fpA.wl"], b = envFingerprint[]},
Association @ Map[
# -> If[ListQ[a[#]] && ListQ[b[#]],
<|"OnlyInA" -> Complement[a[#], b[#]], "OnlyInB" -> Complement[b[#], a[#]]|>, {a[#], b[#]}] &,
Select[Keys[b], a[#] =!= b[#] &]]]
(* A = wolframscript, B = MCP Local:
<|"EvaluationEnvironment" -> {"Script", "Session"}, "ProtectedMode" -> {False, True},
"Context" -> {"Global`", "Sessions`<id>`"},
"ContextPath" -> <|"OnlyInA" -> {"Global`", "Wolfram`Chatbook`", "WolframScript`"}, "OnlyInB" -> {..., "Sessions`<id>`"}|>,
"InitFiles" -> <|"OnlyInA" -> {"~/.Wolfram/Kernel/init.m", "/usr/share/Wolfram/Kernel/init.m"}, "OnlyInB" -> {}|>,
"Directory" -> {"<shell cwd>", "<project root>"}, "CharacterEncoding" -> {"UTF8", "UTF-8"}, "MessageHandlers" -> {0, 1}|> *)
For the cloud, evaluate CloudEvaluate[envFingerprint[]] from a local kernel (the definition is sent along). Helpers:
WolframDebugging`EnvironmentFingerprint[] and WolframDebugging`FingerprintDiff[fpA, fpB] record and compare many
more keys (handlers of every type, Off messages, paclet versions, option hashes, locale, persistence).
Kernel crashes
| environment | what a crash looks like |
|---|---|
| wolframscript | exit code 139; stderr Segmentation fault (core dumped) and The product exited for an unknown reason.; output printed before the crash is kept |
wolfram -script | exit code 139 |
| MCP Session | the server process dies and sends no response; a child process can keep stdout open, so a client that waits for an answer just times out |
| MCP Local | only General::quit: The kernel quit unexpectedly during an evaluation. comes back, exactly as for Quit[]; the next call runs in a new subkernel (new PID, the definitions of every session lost; the Out[n] numbering continues) without any notice |
Known crash triggers to avoid in shared kernels: Package`PackageInformation[] and
RuntimeTools`SetExecutionState[{"RuntimeAnalysisTools" -> True}]. Reproduce crashes only in throwaway kernels.
Breadcrumbs. PutAppend opens and closes the file on every call, so the records survive a crash. This works in every
local environment, including MCP Local (write below $TemporaryDirectory):
crumb[tag_] := PutAppend[{tag, $ProcessID, DateString["Time"]}, "/tmp/crumbs.wl"];
crumb["start"]; data = Range[10];
crumb["loaded data"]; result = suspectStep[data];
crumb["after suspectStep"];
timeout -s KILL 60 wolframscript -f crash.wls < /dev/null > out.txt 2> err.txt; echo "exit=$?"
# exit=139 (err.txt: Segmentation fault (core dumped) / The product exited for an unknown reason.)
wolframscript -code 'ReadList["/tmp/crumbs.wl"]' -format InputForm
# {{"start", <pid>, "21:58:48"}, {"loaded data", <pid>, "21:58:48"}} -> the crash is in suspectStep
Prefix bisection. Split the file into its top-level expressions and run prefixes (expressions 1..k, so that state
built by earlier lines is kept) in fresh kernels. Writing the prefix files works anywhere (MCP Local included); running
them needs a shell or RunProcess:
Module[{src = ReadString["/tmp/crash.wls"], ends},
ends = Cases[CodeParser`CodeParse[src, "SourceConvention" -> "SourceCharacterIndex"][[2]],
_[___, KeyValuePattern[CodeParser`Source -> {_, e_}]] :> e];
Table[Export["/tmp/prefix" <> ToString[k] <> ".wls", StringTake[src, ends[[k]]], "Text"], {k, Length[ends]}]]
(* {"/tmp/prefix1.wls", ..., "/tmp/prefix5.wls"} (load CodeParser` first in wolframscript: Needs["CodeParser`"]) *)
for k in 2 4 3; do timeout -s KILL 60 wolframscript -f /tmp/prefix$k.wls < /dev/null > /dev/null 2>&1; echo "prefix $k: exit $?"; done
# prefix 2: exit 0
# prefix 4: exit 139
# prefix 3: exit 0 -> top-level expression 4 crashes
Choose k by binary search for long files (about log2(n) runs of 6-9 s each). Helper:
WolframDebugging`RunIsolated["code"] or WolframDebugging`RunIsolated[File[path]] runs code in a fresh wolframscript
under timeout -s KILL and returns the exit code, a status ("OK", "TimedOut", "Crashed", ...), stdout, stderr and the
leftover kernels it killed; it needs RunProcess, so it fails in MCP Local (protected mode).
Hard hangs
Details on time limits and stack sampling are in TracingAndPerformance.md. The short version:
TimeConstrainedinterruptsPause, loops, waitingURLRead/URLFetchcalls,RunProcess(the child is killed) andReadLineon a process. It cannot interruptRun[...]or a blocked stdin read at all, and long single primitives only when they finish (a 0.2 s limit stoppedSortof 3*10^7 reals after 2.6 s andEigenvaluesof a 2000x2000 matrix after 4.3 s; a 0.5 s limit stoppedN[Pi, 10^7]after 7 s).AbortProtectandWithCleanupcleanup code delays the abort.URLRead/URLFetchhave no default time-out: useURLRead[url, TimeConstraint -> 10]orTimeConstraint -> <|"Connecting" -> 5, "Reading" -> 10|>(other keys, such as"Connect", are silently ignored), orURLFetch[url, "ConnectTimeout" -> 5, "ReadTimeout" -> 10].Import[url]insideTimeConstrainedaborts the whole evaluation: useCheckAbort[TimeConstrained[Import[url], 10, $TimedOut], $TimedOut].
{AbsoluteTiming[TimeConstrained[Run["sleep 3"], 1, "stopped"]],
AbsoluteTiming[TimeConstrained[RunProcess[{"sleep", "3"}], 1, "stopped"]]}
(* wolframscript: {{3.00754, 0}, {1.04101, "stopped"}} -- Run ignored the 1 s limit
MCP Local: RunProcess::pnfd: Program "sleep" not found. Check Environment["PATH"].
{{0.04555, $Failed}, {0.100993, $Failed}} -- both are blocked in protected mode; the message is misleading *)
When an MCP call hangs or times out:
- Read the result. An ordinary time-out gives
Out[n]= Failure["EvaluationTimeExceeded", ...], keeps thePrintoutput and the state, and skips the later inputs of the call. MCP Local: the Failure withoutOut[n]=(andPrintoutput without itsDuring evaluation of In[n]:=label) means a non-abortable call: the subkernel was killed and restarted about 20 s after the limit, whatever the limit (all state lost; the Failure for a 5 s limit came after 22-24 s, for a 10 s limit after 28 s). MCP Session: a Failure that arrives much later than the limit means a non-abortable call finished late (AbortProtect[Pause[9]]with a 3 s limit answered after 9 s); a blockingRun["sleep 8"]under a 5 s limit even returned its normal result after 8 s and ran the later inputs. No response at all: the call is blocked on stdin or a dialog (either method), or the MCP Session server crashed. - In the next call check
{$ProcessID, SessionTime[]}to see whether you are in a new kernel ($Lineis no sign: it continues the session's numbering in a new subkernel). - Re-run the suspect code with an inner
TimeConstrainedwell belowInternal`TimeRemaining[]and a boundedScheduledTaskstack sampler (WolframDebugging`SampleStacks[expr, maxSeconds]). Only about one sample during the whole wait means a non-interruptible call:Run, a stdin read, or one long primitive. - Look for blocking calls:
Run,Input*, dialogs,ReadLine/Readon$Input, network calls without time-outs, cleanup code, huge numeric primitives. - Reproduce in a throwaway wolframscript under
timeout -s KILL(seeEnvironments.md) and afterwards kill leftover kernels and front ends that you started (ps -o pid,ppid,etime,args -C WolframKernel,WolframNB).
Launching processes
Run[...]is never abortable, and in MCP Session its output goes into the JSON-RPC stream. PreferRunProcess.StartProcesschildren keep running after an aborted read; alwaysKillProcess:
Module[{p = StartProcess[{"sleep", "30"}], line},
line = TimeConstrained[ReadLine[p], 1, "no output yet"];
{line, ProcessStatus[p], KillProcess[p]; ProcessStatus[p]}]
(* wolframscript: {"no output yet", "Running", "Finished"}
MCP Local: StartProcess::pnfd: Program "sleep" not found. ... {ReadLine[$Failed], ProcessStatus[$Failed], ProcessStatus[$Failed]} *)
ReadString[ProcessConnection[p, "StandardOutput"], EndOfBuffer]reads what is available without blocking.- Protected mode (MCP Local,
wolfram -sandbox) blocksRun,RunProcess,StartProcess,LaunchKernelsand writes outside$TemporaryDirectory; the messages are misleading (RunProcess::pnfd: Program ... not found; underwolfram -sandboxalsoExport::nodir: Directory ... does not exist), and some writes fail with a silent$Failed(ExportandCreateDirectoryin MCP Local;PutandWriteStringgive::noopen).
Static checks first
A linter finds a class of "impossible" runtime behavior in a second. Use the CodeInspector MCP tool (file or code;
keep the report short with confidenceLevel, limit and tagExclusions), or the helper
WolframDebugging`LintSummary["code" or File[path], minConfidence] (one line per issue).
| tag | example |
|---|---|
GroupMissingCloser, UnexpectedCloser, ExpectedOperand (Fatal) | f[x_] := {1, 2], x + * 2; fix these first: issues after an unclosed bracket are not reported |
Comma | {1, 2, x,} |
UnscopedObjectError | Map[#^2, list] (missing &) |
ImplicitTimesAcrossLines | a line break inside parentheses that multiplies two lines |
IfSet | If[x = 1, ...] |
DuplicateVariables, DuplicateKeys, DuplicateClauses | Module[{a = 1, a = 2}, a], Association["a" -> 1, "a" -> 2], Switch with a repeated pattern |
TopLevelDefinitionCompoundExpression | f[x_] := Print[x]; x (only Print[x] belongs to the definition) |
PlusString, Arguments | "a" + "b", Which[x > 1, "big", "small"] (confidence 0.55: hidden at the MCP tool's default 0.75) |
Not detected: a trailing ; that makes a Module return Null, f[x_] = RandomReal[] (Set instead of SetDelayed), and a
binary operator at a line end that joins two lines. Locate syntax errors in a string with SyntaxQ/SyntaxLength
(a length below StringLength is the error position; above it means "input is incomplete"):
{SyntaxQ["f[x_] := x + * 2; g[1]"], SyntaxLength["f[x_] := x + * 2; g[1]"],
SyntaxLength["f[x_] := (x + 1"], StringLength["f[x_] := (x + 1"],
SyntaxQ["a = 1\nb = 2 +\nc = 3"]}
(* {False, 13, 17, 15, True} -- the last one parses as a = 1; b = 2 + (c = 3) *)
The inspector as data (load it first, on its own line: Needs["CodeInspector`"]):
{#[[1]], #[[3]], #[[4]][CodeParser`Source]} & /@ CodeInspector`CodeInspect["f[x_] := If[x = 1, {1, 2,}, x]"]
(* {{"Comma", "Error", {{1, 26}, {1, 26}}}, {"IfSet", "Warning", {{1, 13}, {1, 18}}}} -- {line, column} ranges *)
The MCP evaluator silently inserts a missing closing bracket (see Environments.md), so inspect code that behaves
impossibly before you debug it.
Catch, Throw and Enclose
{Catch[Catch[1 + Throw[5, "inner"], "other"], _, <|"Tag" -> #2, "Value" -> #1|> &],
Catch[Catch[1 + Throw[5], _, List]],
Catch[Catch[1 + Throw[5, "t"]], _, {"outer", ##} &],
Enclose[ConfirmQuiet[1/0], #[{"HeldMessageName", "HeldMessageCall"}] &]}
(* {<|"Tag" -> "inner", "Value" -> 5|>, 5, {"outer", 5, "t"},
{Hold[Power::infy], Hold[Message[Power::infy, HoldCompleteForm[0^(-1)]]]}} *)
Catch[expr, _, f]catches every tagged throw (and tells you the tag); it does not catch an untaggedThrow[x]. A plainCatch[expr]catches only untagged throws.- An uncaught
ThrowgivesThrow::nocatchandHold[Throw[...]]in the MCP evaluator (the next input of the call still runs); in a-fscript it printsThrow::nocatchand ends the rest of the script; underwolfram -scriptit ends the script without any message. The exit code stays 0. Enclose/Confirm*failures carry"ConfirmationType","HeldMessageName"and"HeldMessageCall". Their"Message"property is a string with linear box syntax, such as"\!\(\*TagBox[FractionBox[...]]\) produced a message on evaluation.": read the held properties instead.- Code under test that contains
Catch[..., _]or runs insideEvaluationDatacan swallow a probe'sThrow; seeMessagesAndStacks.md.
Memory and leaks
{MaxMemoryUsed[Total[RandomReal[1, 10^6]]], ByteCount[RandomReal[1, 10^6]]}
(* {8000440, 8000200} -- peak bytes while evaluating (varies a little), size of one result *)
Module temporaries leak when a local symbol escapes the Module. One that is still referenced stays alive; once the
reference is dropped it is collected:
ClearAll[leaky, leakCache]; leakCache = {};
leaky[n_] := Module[{tbl}, tbl = RandomReal[1, n]; AppendTo[leakCache, Hold[tbl]]; Total[tbl]];
With[{n0 = Length[Names["*`tbl$*"]]},
Do[leaky[1000], {50}];
{Length[Names["*`tbl$*"]] - n0, leakCache = {}; Length[Names["*`tbl$*"]] - n0}]
(* {50, 0} *)
An escaped temporary that has DownValues (tbl[1] = ... instead of tbl = ...) is never collected, even after
the reference is dropped (the same test gives {50, 50}; one that never escaped is removed): such leaks last as long as
the kernel. In a shared MCP kernel, remove leaked temporaries you created (Remove @@ Names[...] with names you are sure
are yours). The helper
WolframDebugging`LeakCheck[expr, max] reports the memory delta and new temporaries by name. MCP kernels keep
results in the session history ($HistoryLength is Infinity there, 0 in the cloud): end big intermediate results
with ;.
Function Repository helpers
Some community functions are handy for quick checks; they are downloaded from the cloud on first use (about 1-5 s) and work in MCP Local:
ResourceFunction["GeneratedMessageList"][1/0; First[{}]]
(* {"Power::infy: Infinite expression Power[0, -1] encountered.", "", "First::nofirst: {} has zero length and no first element."} *)
Others: "FailOnMessage", "MessagedQ", "CatchAll", "TimeMemoryUsed", "SearchMessages" (find a message by its text)
and "FailWhenUndefined" (adds a catch-all rule so that an unmatched call returns a Failure instead of staying
unevaluated). ResourceFunction uses the locally cached version; two machines can run different versions.
Instrumentation (advanced)
The Instrumentation` component rewrites a copy of a package's source directory so that every definition records
its source location; this gives file:line provenance for messages, line coverage (CoverageInstrument,
CoverageEvaluate) and per-function profiles (ProfileInstrument, ProfileEvaluate) without a front end. Run it in a
throwaway wolframscript kernel: it loads the instrumented package into the kernel and prints a ProgressIndicator
expression while instrumenting.
Quiet[Needs["Instrumentation`"]];
Instrumentation`MessageInstrument["/path/to/src", "/tmp/instr"];
Get["/tmp/instr/Kernel/InstrDemo.wl"];
Module[{prov = Internal`Bag[]},
Internal`HandlerBlock[{"Message", Function[m, Internal`StuffBag[prov,
Cases[Stack[_], HoldPattern[(HoldCompleteForm | HoldForm)[msg`InfoWrapper[_, {fn_, file_, line_}]]] :>
fn <> " @ " <> FileNameTake[file] <> ":" <> ToString[line]]]]},
Quiet[InstrDemo`MyFunction[-1, 1]]];
Internal`BagPart[prov, All]]
(* {{"MyFunction @ InstrDemo.wl:7", "OtherFunction @ InstrDemo.wl:5"}} (wolframscript) *)
Here /path/to/src contains Kernel/InstrDemo.wl, in which OtherFunction[x_] := 1/x is on line 5 and
MyFunction[a_, b_] := Table[OtherFunction[i], {i, a, b}] on line 7. The HoldPattern is required: msg`InfoWrapper
has definitions, so an unprotected pattern would evaluate to _. The component's own
Instrumentation`EnableMessageProvenance[] prints an empty Column[{}] in 15.0 because it matches HoldForm frames,
while 15.0 frames are HoldCompleteForm.
Helper Functions (WolframDebugging.wl)
API reference of scripts/WolframDebugging.wl, the helper package of this skill: 55 public symbols in the context
WolframDebugging` that wrap the recipes of the other references into bounded, side-effect-free calls. Read it when
a helper is mentioned elsewhere and you need its options, its result shape or its environment limits. Checked with
Wolfram 15.0.
Loading
Get["/absolute/path/to/wolfram-debugging/scripts/WolframDebugging.wl"] (* on its own line or in its own call *)
WolframDebugging`CollectMessages[myFunction[1, 2]] (* fully qualified, on a later line *)
| environment | how |
|---|---|
| MCP evaluator (Local and Session) | Get on its own line or in its own call, then full names. Each top-level input of a call is parsed just before it runs, so a name in the same input as the Get (Get[...]; name[...]) is created in the session context first. |
| wolframscript | Get on its own line of a -f file, or wolframscript -code 'Get["/abs/.../WolframDebugging.wl"]; Print[ToString[WolframDebugging`EnvironmentInfo[], InputForm]]' (-code prints OutputForm and drops string quotes: print with ToString[..., InputForm]) |
wolfram -script | as with -f |
| CloudEvaluate | load locally, then CloudEvaluate[WolframDebugging`CollectMessages[...]]: the definitions are sent along (7 helper calls in one CloudEvaluate took 6 s); ShowDefinition does not work there |
| deployed API | load locally before CloudDeploy; helpers used in the deployed expression are bundled with it (see HTTPDiagnostics) |
| remote MCP server | local files cannot be loaded: use the helper-free recipes of the other references |
Loading takes 0.1 s and has no side effects (no messages, Global` symbols, handlers or settings; dependencies load on
first use). Get it again after an update: all definitions are replaced.
Conventions
- Fully qualified calls, always:
WolframDebugging`Name[...]. - Held arguments: the code under test is evaluated once, inside the helper (under
StackBegin, with its handlers active). Functions that inspect a value (StuckCalls,FormatStack,HTTPSummary, ...) evaluate their argument. - Spies and overrides (
StackAtCall,TimeCalls,LogCalls,WithOverrides) work insideInternal`InheritedBlock: definitions that your code adds to those symbols (memoized values) are discarded afterwards. - Results:
"Result"is the value of your code; above"MaxResultBytes"(10^4 bytes;Infinitykeeps all) it isMissing["TooLarge", <|"ByteCount" -> n, "Preview" -> "..."|>]. An uncaughtThrowgivesFailure["UncaughtThrow", ...],Abort[]gives$Aborted, a helper stop givesMissing["Stopped"]: nothing escapes.WithOverridesand theCaptureEvaluationrecords hold the value asHoldComplete[...], so it is not re-evaluated. - Failures: an invalid call returns
Failure["WolframDebugging", <|"MessageTemplate", "MessageParameters", "Function", "Call", "Expected"|>]without a message; unknown option names and invalid option values are named in it, with the valid options. AlsoFailure["TraceUnavailable", ...],Failure["ProtectedMode", ...](MCP Local) andMissing["UnknownSymbol", name](names given as strings never create symbols). - Output bounds: strings are cut to about 150 characters (
...), big subexpressions are elided as<<k>>, lists are capped byMax...options, stacks are formatted text; raw frames only with"RawStack" -> True. - Messages of your code still print (recorded, not hidden, except with
"SuppressPrinting" -> True); in aVerificationTest, list them as expected messages. - Options are given as strings (
"StackFrames" -> 3). Stack frames areHoldCompleteForm[...]in 15.0 (HoldForm[...]before); every helper accepts both and never evaluates a frame.
WolframDebugging`CollectMessages[1 + 1, "StackFrame" -> 3]
(* Failure["WolframDebugging", <|"MessageTemplate" -> "Unknown option(s) `2` for `1`. Valid options: `3`.", "MessageParameters" -> {...},
"Function" -> "WolframDebugging`CollectMessages", "Call" -> "CollectMessages[1 + 1, \"StackFrame\" -> 3]", "Expected" -> "CollectMessages[expr, opts]"|>] *)
The examples below use these definitions; outputs are from wolframscript unless noted:
otherFn[x_] := 1/x; myFn[a_, b_] := Table[otherFn[i], {i, a, b}];
area[r_?NumericQ] := Pi r^2;
hlp[x_] := x^2; fib[0] = 0; fib[1] = 1; fib[n_] := fib[n - 1] + hlp[fib[n - 2]];
fact[0] = 1; fact[n_] := n fact[n - 1];
loop[] := Module[{k = 0}, While[True, k++]];
Core
ShortString[expr, n]
One-line InputForm string of expr with at most n (default 150) characters. Strips one HoldComplete/
HoldCompleteForm/HoldForm; prints Global` and session symbols without context. Use it for anything you print.
WolframDebugging`ShortString[Range[1000], 60]
(* "{1, 2, 3, 4, 5, 6, 7, 8, 9, <<987>>, 997, 998, 999, 1000}" *)
EnvironmentInfo[]
Where the code runs and what that means (run it first when behavior is surprising): "Environment", "Version",
"TraceWorks", "ProtectedMode", "Context", "UserContexts" (where your symbols live), "QuietedGlobally",
"ProcessID", "TimeRemaining", "Notes".
KeyTake[WolframDebugging`EnvironmentInfo[], {"Environment", "TraceWorks", "ProtectedMode", "UserContexts"}]
(* <|"Environment" -> "wolframscript", "TraceWorks" -> True, "ProtectedMode" -> False, "UserContexts" -> {"Global`"}|> *)
MCP Local: "MCP evaluator, Method Local (...)", True, True, {"Global`", "Sessions`<id>`"}; MCP Session:
"MCP evaluator, Method Session (...)", False; CloudEvaluate: "CloudEvaluate", False, True.
Messages and Stacks
CollectMessages[expr, opts]
Records every message of expr: name, text with short arguments, whether it really printed or was quieted, and the last
stack frames. The first tool for "which message, from where"; works in every environment (no Trace). Options:
"IncludeQuieted" (False) also record messages silenced by Quiet/Off; "StackFrames" (6) frames per message, 0 =
none; "MaxMessages" (25) records kept, counting continues; "StringLength" (150); "StopAt" (None) stop at a
message: "Power::infy", "Last::*", "*::infy", a pattern, or {spec, k} for the k-th match (give names as strings:
General::stop evaluates to its text); "IgnoreOuterQuiet" (True) evaluate as Quiet[expr, None, All], cancelling a
Quiet around the call (the remote MCP server quiets every input); "ResetMessageList" (True)
Block[{$MessageList = {}}, ...] (fresh General::stop count; MCP Session never resets it); "SuppressPrinting" (False)
Block[{$Messages = {}}, ...]; "MaxResultBytes". "Printed" is False for quieted messages and for those suppressed
by General::stop (their willPrint flag is still True).
WolframDebugging`CollectMessages[myFn[-1, 1]]
(* <|"Result" -> {-1, ComplexInfinity, 1}, "MessageCount" -> 1, "Messages" -> {<|"Message" -> HoldForm[Power::infy],
"Text" -> "Power::infy: Infinite expression 0^(-1) encountered.", "Printed" -> True, "Quieted" -> False,
"Stack" -> {"myFn[-1, 1]", "Table[otherFn[i], {i, -1, 1}]", "otherFn[i]", "1/0", "0^(-1)"}|>}|> *)
"StopAt" -> "First::*" on {First[{}], Last[{}]} gives "Result" -> Missing["Stopped"] after one message; it throws,
so a Catch[..., _] in your code can intercept it.
StackAtMessage[expr, msg, opts]
The full stack at the first printed message (or the first matching msg: Power::infy, "Power::*", "*::infy", a
pattern), formatted. Use it when CollectMessages' last frames are not enough. Options: "MaxCount" (1) record this
many matches; "Stop" (True) stop the evaluation after "MaxCount" matches; "Complete" (True) StackComplete
(keeps the frames of calls already rewritten into their body, such as myFn[-1, 1]); "IncludeQuieted" (False);
"IgnoreOuterQuiet" (True); "RawStack" (False) also return the frames; "MaxResultBytes"; the FormatStack options.
With "MaxCount" > 1 the matches are in "Captures"; "Message" -> None: no match.
WolframDebugging`StackAtMessage[myFn[-1, 1], Power::infy]
(* <|"Result" -> Missing["Stopped"], "Message" -> "Power::infy: Infinite expression 0^(-1) encountered.",
"Stack" -> "(6 frames)\n1| myFn[-1, 1]\n2| Table[otherFn[i], {i, -1, 1}]\n3| otherFn[i]\n4| 1/0\n5| 0^(-1)\n6| Message[Power::infy, HoldCompleteForm[0^(-1)]]",
"StackLength" -> 6|> *)
Frames show expressions as pushed (otherFn[i], not otherFn[0]): use StackAtCall for argument values.
StackAtCall[expr, callPattern, opts]
The stack each time a call matching callPattern (f[0], _f, f[x_] /; x < 0) is evaluated; the call frame shows
the actual arguments. A never-matching conditional rule is prepended to f inside Internal`InheritedBlock, so the
definitions are unchanged afterwards. Options: "MaxCount" (1); "Stop" (True; use False when probing Throw);
"Complete" (False); "RawStack" (False) adds "RawStacks"; "MaxResultBytes"; plus the FormatStack options.
WolframDebugging`StackAtCall[myFn[-1, 1], otherFn[0]]
(* <|"Result" -> Missing["Stopped"], "Count" -> 1, "Stacks" -> {"(2 frames)\n1| Table[otherFn[i], {i, -1, 1}]\n2| otherFn[0]"}|> *)
Not seen: calls answered by literal rules (f[0] = 1) and calls made inside kernel code. f must not be Locked.
FormatStack[stack, opts]
Numbered lines, recursion collapsed (-- frames 2-11: a 2-frame cycle repeated 5 times (first and last shown) --).
stack: frames (Stack[_], Stack[], your capture) or a "RawStack" -> True result; a formatted string is returned as
is. Options: "MaxFrames" (25, the last ones); "MaxFrameLength" (150); "Filter" (All | "Calls" drops plumbing
such as Table, If, Times | "User" | context prefixes | a pattern for the frame contents); "Start"/"End"
(None | pattern: keep from the first/to the last match); "Collapse" (True); "ShortContexts" (False).
r = WolframDebugging`StackAtMessage[myFn[-1, 1], "RawStack" -> True];
WolframDebugging`FormatStack[r, "Filter" -> "Calls"]
(* "(6 frames, 2 after Filter)\n1| myFn[-1, 1]\n3| otherFn[i]" *)
StackSummary[stack]
Size and composition of a stack without its contents: "Length", "ByteCount", "TopHeads", "Contexts". Useful for
deep recursion before formatting anything.
WolframDebugging`StackSummary[r]
(* <|"Length" -> 6, "ByteCount" -> 1240, "TopHeads" -> {{"myFn", 1}, {"Table", 1}, {"otherFn", 1}, {"Times", 1}, {"Power", 1},
{"Message", 1}}, "Contexts" -> {{"System`", 4}, {"Global`", 2}}|> *)
CaptureEvaluation[expr] and $CaptureFunction
One record for a $Failed/Failure without explanation: "KernelID", "PID", "Result" (HoldComplete),
"ResultString", "MessageCount", "Messages" (first 10), "PrintCount", "Prints" (first 10; Print is suppressed),
"Stack" (last 12 frames at the first message), "Aborted", "Thrown", "Seconds".
WolframDebugging`CaptureEvaluation[Print["hi"]; 1/0; Throw[5]]
(* <|"KernelID" -> 0, "PID" -> 4242, "Result" -> HoldComplete[Throw[5]], "ResultString" -> "Throw[5]", "MessageCount" -> 1,
"Messages" -> {"Power::infy: Infinite expression 0^(-1) encountered."}, "PrintCount" -> 1, "Prints" -> {"hi"},
"Stack" -> {"Print[\"hi\"]; 1/0; Throw[5]", "1/0", "0^(-1)", "Message[Power::infy, HoldCompleteForm[0^(-1)]]"},
"Aborted" -> False, "Thrown" -> "Throw[5]", "Seconds" -> 0.001|> *)
$CaptureFunction is the same as a self-contained pure function (System` /Internal` functions and its own
local variables: no definitions needed) for subkernels, task bodies and handlers:
With[{cap = WolframDebugging`$CaptureFunction}, ParallelMap[cap[f[#]] &, list]].
With[{cap = WolframDebugging`$CaptureFunction}, Map[cap[otherFn[#]]["ResultString"] &, {1, 2}]]
(* {"1", "1/2"} *)
Performance and Trace
SampleStacks[expr, maxSeconds, opts]
Profiler and hang locator that works everywhere (no Trace): a ScheduledTask samples the stack while expr runs,
stopped after maxSeconds (Automatic: at most 10 s, safely below the remaining tool time). Returns "Seconds",
"TimeLimit", "TimedOut", "Samples", "Functions%" (% of samples with the function on the stack),
"InnermostFunction%", "Builtin%" (innermost frame head), "LastFrames" (last sample, with live local values),
"Result". Options: "Interval" (0.01 s); "MaxEntries" (8); "MaxFrames" (12); "MaxFrameLength" (100);
"MaxResultBytes".
WolframDebugging`SampleStacks[loop[], 1]
(* <|"Seconds" -> 1.001, "TimeLimit" -> 1., "TimedOut" -> True, "Samples" -> 98, "Functions%" -> <|"loop" -> 100.|>,
"InnermostFunction%" -> <|"loop" -> 100.|>, "Builtin%" -> <|"Increment" -> 80.6, "While" -> 19.4|>,
"LastFrames" -> {"loop[]", "Module[{k = 0}, While[True, k++]]", "While[True, k$17041++]", "k$17041++"}, "Result" -> $TimedOut|> *)
A call that cannot be interrupted (a long Sort, Run, a blocked read) gets at most one sample: the last sample names
it.
TimeCalls[expr, {f, ...}, opts]
Exact call counts and inclusive seconds per function (outermost call only: recursion is not counted twice); works
everywhere. Option: "MaxResultBytes". Not for Locked symbols or OwnValues; calls answered by literal rules
(fib[0] = 0) are not counted; counts of Flat/Orderless heads (Plus, StringJoin) are too high (use LogCalls).
WolframDebugging`TimeCalls[fib[15], {fib, hlp}]
(* <|"TotalSeconds" -> 0.023, "Calls" -> <|"fib" -> 986, "hlp" -> 986|>, "Seconds" -> <|"fib" -> 0.023, "hlp" -> 0.01|>,
"Result" -> 186242594112190847520182173826|> *)
TraceAvailableQ[]
True when Trace records evaluations here: wolframscript and MCP Local (notebooks: not checked here); False in MCP
Session, wolfram -script, CloudEvaluate, deployed APIs and the remote MCP server.
The three Trace-based helpers below return Failure["TraceUnavailable", ...] where it is False.
TraceCalls[expr, form, n, opts]
The first n (20) evaluations matching form, after argument evaluation, as short strings; the evaluation is stopped
once n are collected ("EvaluationFinished" -> False). Options: "MaxLength" (150) and any Trace option
(TraceInternal -> True also shows calls inside System functions, TraceOff, TraceDepth, ...).
WolframDebugging`TraceCalls[fib[8], _hlp, 3]
(* <|"Calls" -> {"hlp[0]", "hlp[1]", "hlp[0]"}, "EvaluationFinished" -> False|> *)
CountCalls[expr, form, opts]
How often calls matching form were evaluated, by head. Options: "MaxEntries" (25; the rest are summed under
"(other heads)") and Trace options.
WolframDebugging`CountCalls[fib[8], _fib | _hlp]
(* <|"fib" -> 67, "hlp" -> 33|> *)
FindHang[expr, maxSteps, opts]
Runs expr for at most maxSteps (10^5) evaluation steps; if unfinished, gives the stack heads and the last steps.
Options: "LastSteps" (15); "MaxLength" (120); "MaxStackHeads" (25); "MaxResultBytes". Finished:
<|"Finished" -> True, "Steps", "Result"|>.
WolframDebugging`FindHang[loop[], 2000, "LastSteps" -> 3]
(* <|"Finished" -> False, "Steps" -> 2000, "StackHeads" -> {"loop", "Module", "While"}, "LastSteps" -> {"k$18051++", "k$18051++", "k$18051++"}|> *)
Overrides
LogCalls[{f, ...}, expr, opts] and CallLogSummary[log, n, opts]
Every call of the functions with depth, result and time (spy rules inside Internal`InheritedBlock; recursion, Hold
attributes, Flat heads, System symbols such as StringJoin). Options: "MaxCalls" (200, all are counted);
"IncludeLiteralRules" (True: also calls answered by rules like f[0] = 1); "MaxResultBytes". Returns
<|"Result", "Calls" -> {<|"ID", "Depth", "Parent", "Call", "Result", "Seconds"|>, ...}, "TotalCalls"|>;
"Call"/"Result" are HoldComplete[...] (a truncated string above 2000 bytes), Missing["NotReturned"] when a call
threw or aborted. CallLogSummary prints the first n (30) calls as a tree; option "MaxLength" (120).
log = WolframDebugging`LogCalls[{fact}, fact[3]];
WolframDebugging`CallLogSummary[log]
(* "fact[3] -> 6 (0.13 ms)\n fact[2] -> 2 (0.09 ms)\n fact[1] -> 1 (0.05 ms)\n fact[0] -> 1 (0. ms)" *)
Not for Locked symbols, symbols with OwnValues, or the functions the logger itself uses (Block, TrueQ, Not,
...).
WithOverrides[{lhs :> rhs, ...}, expr, opts]
Evaluates expr with the rules temporarily in front of the existing definitions (sym :> v OwnValues, f[...] :> v
DownValues, f[...][...] :> v SubValues; -> acts like :>) and returns HoldComplete[result]: mock HTTP (URLRead,
URLFetch), time (Now), files, slow functions. Stubs are loaded first, Locked symbols refused; literal left-hand
sides (f[7]) are tried before pattern ones whatever the order. Option: "MaxResultBytes".
WolframDebugging`WithOverrides[{otherFn[0] :> "MOCK"}, myFn[-1, 1]]
(* HoldComplete[{-1, "MOCK", 1}] *)
SnapshotDefinitions[sym] and RestoreDefinitions[sym, snapshot]
All values, messages and attributes of sym (works for ReadProtected symbols); RestoreDefinitions puts them back and
gives True when sym matches the snapshot. For changes that must span several tool calls; prefer WithOverrides.
Assign the snapshot to a variable, do not print it.
snap = WolframDebugging`SnapshotDefinitions[otherFn];
otherFn[x_] := 0;
{otherFn[2], WolframDebugging`RestoreDefinitions[otherFn, snap], otherFn[2]}
(* {0, True, 1/2} *)
Watchpoints and Probes
WatchChanges[{sym, ...}, expr, opts]
Records every change of the symbols' values or definitions (Internal`SetValueMonitor + a "ValueChange" handler)
with the user functions on the stack. Events: HoldComplete[x, old, new, OwnValues],
HoldComplete[x, x[[1]], 5, Part], HoldComplete[x, Clear], definition changes, Block entry/exit. Options:
"MaxEvents" (20, all are counted); "MaxLength" (160); "MaxResultBytes".
counter = 0; bump[] := counter++;
WolframDebugging`WatchChanges[{counter}, bump[]; bump[]]
(* <|"Result" -> 1, "Count" -> 2, "Changes" -> {<|"Event" -> "HoldComplete[counter, 0, 1, OwnValues]", "Callers" -> {"bump"}|>,
<|"Event" -> "HoldComplete[counter, 1, 2, OwnValues]", "Callers" -> {"bump"}|>}|> *)
StopWhen[sym, test, expr, opts]
Stops at the first assignment that gives sym a value v with test[v] True and returns the change and the stack
(user frames, or the last frames when only System code is involved). Otherwise <|"Stopped" -> False, "Result"|>.
Options: "MaxFrames" (15); "MaxLength" (120); "MaxResultBytes".
state = 0;
WolframDebugging`StopWhen[state, # > 2 &, Do[state = k, {k, 5}]]
(* <|"Stopped" -> True, "Event" -> "HoldComplete[state, 2, 3, OwnValues]", "Stack" -> {"Do[state = k, {k, 5}]", "state = k"}|> *)
NewSymbolsDuring[expr, opts]
Symbols created at run time (ToExpression, Symbol, Get, ...): typos, leaks, wrong contexts while loading. Symbols
of the input itself were created when it was parsed and are not listed (ToExpression creates symbols in $Context:
Sessions`<id>` in the MCP evaluator). Options: "MaxSymbols" (50); "MaxResultBytes".
WolframDebugging`NewSymbolsDuring[ToExpression["newSym1 + newSym2"]]
(* <|"Result" -> newSym1 + newSym2, "Count" -> 2, "NewSymbols" -> {"Global`newSym1", "Global`newSym2"}|> *)
FileWritesDuring[expr, opts]
Files opened for writing ("Wolfram.File.OpenWrite" handler; a notification, the write still happens). Options:
"MaxFiles" (50); "MaxResultBytes".
WolframDebugging`FileWritesDuring[Export[FileNameJoin[{$TemporaryDirectory, "wd-example.txt"}], "x", "Text"]]
(* <|"Result" -> "/tmp/wd-example.txt", "Count" -> 1, "Writes" -> {{"OpenWrite", "/tmp/wd-example.txt"}}|> *)
CapturePrints[expr, max, opts]
Suppresses Print and CellPrint and returns the first max (20) texts. Echo is captured everywhere: it goes
through Print, or, where $Notebooks is True (CloudEvaluate, deployed APIs, the remote MCP server, UsingFrontEnd),
through CellPrint, whose Echo cells are recorded with the same text.
Block[{Print = ...}] hides prints in every environment (Block[{$Output = {}}, ...] does not in MCP Session).
Options: "MaxLength" (200 per text); "MaxResultBytes".
WolframDebugging`CapturePrints[Print["a"]; Echo[2, "x:"]; 3]
(* <|"Result" -> 3, "PrintCount" -> 2, "Prints" -> {"a", ">> x: 2"}|> *)
FailedAssertions[expr, opts]
Assert calls that failed, also when Assert is Off (the default); "Line"/"File" are included for code loaded with
Get. Options: "MaxAssertions" (20); "MaxResultBytes".
check[x_] := (Assert[x > 0]; x);
WolframDebugging`FailedAssertions[check[-1] + check[2]]
(* <|"Result" -> 1, "Count" -> 1, "Failed" -> {<|"Assert" -> "-1 > 0", "Callers" -> {"check"}|>}|> *)
LeakCheck[expr, max, opts]
Symbols and Module temporaries that expr left behind (by name pattern, the max (5) largest) and the MemoryInUse
change. Option: "MaxResultBytes".
cache = {}; leaky[] := Module[{t}, t[1] = 1; AppendTo[cache, t]];
KeyDrop[WolframDebugging`LeakCheck[Do[leaky[], 3], 2], {"MemoryDelta", "Result"}]
(* <|"NewSymbols" -> 3, "NewTemporaries" -> 3, "TemporariesByName" -> <|"t$*" -> 3|>,
"LargestTemporaries" -> {{"t$18294", 424}, {"t$18295", 424}}, "OtherNewSymbols" -> {}|> *)
Unevaluated Calls
WhyNoMatch[f[args], opts]
Which definition applies to f[args] and why the others do not, without Trace and without evaluating any rule body: the
arguments are evaluated once as the evaluator would (Hold attributes, Sequence, Flat, Listable, Orderless), then the
kernel's matcher runs each rule with tests and conditions instrumented. Reports argument counts, the first failing
argument, test/condition values, rule order, OwnValue heads, built-ins (ArgumentsPattern), symbols in other contexts,
similar names. Options: "EvaluateArguments" (True); "MaxRules" (12); "MaxLength" (110); "Hints" (True).
WolframDebugging`WhyNoMatch[area["4"]]
(* <|"Summary" -> "no rule matches; area[\"4\"] stays unevaluated (1 rule(s) checked)",
"Head" -> <|"Symbol" -> "Global`area", "Definitions" -> <|"DownValues" -> 1|>|>, "Call" -> "area[\"4\"]",
"Rules" -> {"DownValues[[1]]: area[(r_)?NumericQ] -> test NumericQ[\"4\"] gave False"}|> *)
WolframDebugging`WhyNoMatch[myFn[1]]["Rules"]
(* {"DownValues[[1]]: myFn[a_, b_] -> the call has 1 argument(s), the pattern takes 2"} *)
An argument that throws or aborts gives "Summary" -> "the analysis was interrupted: ...".
StuckCalls[result, opts]
Summarizes the unevaluated calls in a (large) result: count per head, the smallest example, and why (no definitions,
similar names, defined in another context, autoload stub, rules that did not match). Options: "MaxHeads" (8);
"MaxLength" (80); "Heads" ({}: System heads to include). Also lists Failure/Missing/$Failed found in the
result.
WolframDebugging`StuckCalls[{area["4"], Lenght[{1}], area[2]}]
(* <|"StuckCalls" -> 2, "ByHead" -> <|"area" -> "1x, has 1 DownValues, none matched (use WhyNoMatch), e.g. area[\"4\"]",
"Lenght" -> "1x, NO definitions (similar names: System`Length), e.g. Lenght[{1}]"|>|> *)
Definitions and Source
ShowDefinition[sym or "name", n]
Definition as text with short contexts, ReadProtected bypassed inside Internal`InheritedBlock, at most n (3000)
characters. A string or a string-valued expression is taken as the name (unknown: Missing["UnknownSymbol", name]).
An unloaded autoload stub shows only the stub (CloudGet = ActivateLoad[...]): call EnsureLoaded first. Under
CloudEvaluate it returns "Null" (Definition is broken in cloud kernels; use DownValues there).
rp[x_] := x + 1; SetAttributes[rp, ReadProtected];
WolframDebugging`ShowDefinition[rp]
(* "rp[x_] := x + 1" *)
SymbolKind[sym or "name"]
What a symbol is, without loading it: "Symbol", "Attributes", "AutoloadStub", "Autoload" (mechanism and loader
context), "KernelCode", "Counts" (Own/Down/Up/Sub values), "Usage" (first 150 characters).
WolframDebugging`SymbolKind["CloudPut"]
(* <|"Symbol" -> "System`CloudPut", "Attributes" -> {Protected, ReadProtected}, "AutoloadStub" -> True,
"Autoload" -> {"Package`ActivateLoad", "CloudObjectLoader`"}, "KernelCode" -> False,
"Counts" -> <|"Own" -> 1, "Down" -> 0, "Up" -> 0, "Sub" -> 0|>, "Usage" -> "CloudPut[expr] writes expr to a new anonymous cloud object. ..."|> *)
In MCP Local the package is already loaded: "AutoloadStub" -> False, "Down" -> 7.
FindSymbolSource["name" or sym, opts]
Source files and line ranges of a symbol's definitions (contexts → FindFile → paclet roots → CodeParser metadata;
works for stubs). Options: "MaxDefinitions" (10); "Kinds" (All | e.g.
{"DownValue", "UpValue", "Options", "Message"}); "MaxLength" (400). Also "Contexts", "EntryFiles",
"LoadedRoots", "KernelCode", "MXFiles", "Notes" (why nothing was found). Several definitions on one source line
(f[x_] := 1; f[] := 0;) are one entry, so "TotalDefinitions" can be lower than Length[DownValues[f]].
KeyTake[WolframDebugging`FindSymbolSource["CodeParser`CodeParse", "Kinds" -> {"DownValue"}, "MaxDefinitions" -> 1, "MaxLength" -> 60],
{"PacletRoots", "TotalDefinitions", "Definitions"}]
(* <|"PacletRoots" -> {"/usr/local/Wolfram/Wolfram/15.0/SystemFiles/Components/CodeParser"}, "TotalDefinitions" -> 3,
"Definitions" -> {<|"File" -> ".../CodeParser/Kernel/CodeParser.wl", "Lines" -> {848, 859}, "Kind" -> "DownValue",
"Text" -> "CodeParse[s_String, opts:OptionsPattern[]] :=\nCatch[\nModule[ ... (185 chars)"|>}|> *)
PacletRoot[file]
The nearest enclosing directory with a PacletInfo.wl/.m (Missing["NotFound", file] outside paclets); always
terminates.
WolframDebugging`PacletRoot[FindFile["CodeParser`"]]
(* "/usr/local/Wolfram/Wolfram/15.0/SystemFiles/Components/CodeParser" *)
Package Loading
LoadTrace[expr, opts]
The autoloads and file loads that evaluating expr causes, with nesting depth and trigger:
"Loads" -> {{depth, "Autoload"|"Get", target, resolved file or loader context, trigger}, ...}, plus "LoadCount",
"NewFileCount", "NewFilesByDirectory", "NewFiles" ($LoadedFiles difference: also .mx files). Options:
"MaxLoads" (30); "MaxDepth" (Infinity; 0 = top-level loads); "MaxFiles" (20); "MaxLength" (80);
"MaxResultBytes".
KeyTake[WolframDebugging`LoadTrace[ErlangB[2, 3]], {"Result", "LoadCount", "Loads", "NewFileCount"}]
(* <|"Result" -> 9/17, "LoadCount" -> 2, "Loads" -> {{0, "Autoload", "System`ErlangB", "SpecialFunctions`StatisticalFunctions`", "ErlangB[2, 3]"},
{0, "Autoload", "Statistics`Library`AdmissibleUnivariateInputQ", "Statistics`Library`", "Statistics`Library`AdmissibleUnivariateInputQ[2]"}},
"NewFileCount" -> 2|> *)
First-time effects only: in MCP Local the same call gives "LoadCount" -> 0 (already loaded). Use a fresh
wolframscript.
ContextSourceInfo["Ctx`"]
Where a context's code comes from and whether the loaded code is current: "InPackages" (True: Needs is a no-op),
"OnContextPath", "FindFile", "Candidates" (installed versions, the first one wins), "LoadedFileCount",
"LoadedFiles", "OtherLoadedCopies", "StaleMX" (loaded .mx older than the newest source), "NewestSource",
"EditedSinceKernelStart" (source edited after this kernel started: the running code cannot contain the edit).
KeyTake[WolframDebugging`ContextSourceInfo["CodeParser`"], {"InPackages", "Candidates", "LoadedFileCount", "StaleMX", "EditedSinceKernelStart"}]
(* <|"InPackages" -> True, "Candidates" -> {{"CodeParser", "1.13", "/usr/local/Wolfram/Wolfram/15.0/SystemFiles/Components/CodeParser"}},
"LoadedFileCount" -> 19, "StaleMX" -> {}, "EditedSinceKernelStart" -> {}|> *)
AutoloadStubQ[sym or "name"] and EnsureLoaded[sym or "name"]
AutoloadStubQ tells whether a symbol is still an unloaded autoload stub, without loading it. EnsureLoaded evaluates
the stub (loading its package) and gives True when no stub remains; do this before overriding or inspecting a stub.
{WolframDebugging`AutoloadStubQ["CloudPut"], WolframDebugging`EnsureLoaded["CloudPut"], WolframDebugging`AutoloadStubQ["CloudPut"]}
(* {True, True, False} *)
MCP Local: {False, True, False} (preloaded).
Tests
The examples use this file (two failing tests and a duplicate TestID):
file = FileNameJoin[{$TemporaryDirectory, "wd-demo.wlt"}];
Export[file, "VerificationTest[1 + 1, 2, TestID -> \"Pass\"]
VerificationTest[StringJoin[\"a\", \"b\"], \"ba\", TestID -> \"Wrong\"]
VerificationTest[1/0; 1, 1, TestID -> \"Pass\"]", "Text"];
WolframDebugging`TestFailureSummary[TestReport[file], "Format" -> "Text"]
(* "Wrong [Failure/SameTestFailure]\n in: StringJoin[\"a\", \"b\"]\n exp: \"ba\"\n act: \"ab\"\nPass [MessagesFailure/SameMessagesFailure]\n in: 1/0; 1 ..." *)
TestFailureSummary[report, opts]
One record per failed test of a TestReportObject, a TestObject or a list: "TestID", "Outcome" (with failure
type), "Input", "Expected", "Actual", "Messages" (repeats collapsed), "ExpectedMessages", "FailedSteps" (for
IntermediateTest). Never print a report object itself. Options: "MaxBytes" (2000: fields are shortened, then records
dropped); "MaxLength" (160); "Format" ("Association" | "Text", shown above).
TestSource[file, idPattern]
The source of the tests whose TestID (with or without the @@file:line suffix) matches the string pattern; nothing is
evaluated.
WolframDebugging`TestSource[file, "Wrong"]
(* {<|"TestID" -> "Wrong", "Lines" -> {2, 2}, "Code" -> "VerificationTest[StringJoin[\"a\", \"b\"], \"ba\", TestID -> \"Wrong\"]"|>} *)
RunTestsByID[file, idPattern, opts]
TestReport of the file in which only the matching tests (and "Setup" tests) run; returns a summary. Options:
"Setup" (None | TestID pattern of setup tests, e.g. "GetDefinitions" | "LoadContext"); "Context" (Automatic: the
file is read in $Context, where your typed definitions are, and symbols the tests create go there; another context:
the file is read there, and $Context is taken off $ContextPath); "TimeConstraint" (Automatic: per test, below the remaining tool time); "ReturnReport"
(False: True returns the TestReportObject); "MaxBytes" (2000).
WolframDebugging`RunTestsByID[file, "Wrong"]
(* <|"File" -> "/tmp/wd-demo.wlt", "TestsRun" -> 1, "Succeeded" -> 0, "Failed" -> 1, "Outcomes" -> {"Wrong" -> "Failure"},
"Failures" -> "Wrong [Failure/SameTestFailure]\n in: StringJoin[\"a\", \"b\"]\n exp: \"ba\"\n act: \"ab\""|> *)
ReproduceTest[test, opts]
Re-evaluates a test input like the harness ($Messages = {}, only messages that would print are recorded, input under
StackBegin) and returns "Result", "Messages" and "StackAtFirstMessage". test: a TestObject, a TestSource
record or HoldComplete[input]. Options: "Frames" (12); "MaxLength" (120); "TimeConstraint" (30);
"PrintMessages" (False).
WolframDebugging`ReproduceTest[HoldComplete[myFn[-1, 1]]]
(* <|"Result" -> "{-1, ComplexInfinity, 1}", "Messages" -> {"Power::infy: Infinite expression 0^(-1) encountered."},
"StackAtFirstMessage" -> {"Table[otherFn[i], {i, -1, 1}]", "1/0", "0^(-1)"}|> *)
CheckTestFile[file]
Static checks for problems that TestReport reports badly or not at all: "SyntaxError" (then no test of the file runs
and the TestReport tool reports success with 0 tests), "TopLevelAbort"/Throw/Exit/Quit,
"MalformedVerificationTest" (more than 3 positional arguments: the test is dropped), "NoTestID",
"DuplicateTestID".
WolframDebugging`CheckTestFile[file]
(* {<|"Line" -> 3, "Issue" -> "DuplicateTestID", "Detail" -> "Pass"|>} *)
Parallel and Asynchronous
ParallelCapture[f, list, opts]
Maps f in parallel under $CaptureFunction and reports messages, aborts, throws, items run in the master
("RanInMaster") and "MasterOnlyHeads": functions left unevaluated on a subkernel but defined in the master (not
distributed: package contexts, ReadProtected/MX code). Options: "MaxRows" (5); "DistributedContexts" (Automatic).
Launch and close kernels yourself (otherwise ParallelMap launches its default number; after CloseKernels[] it does
not relaunch and every item runs in the master); subkernels exist in wolframscript, wolfram -script and MCP Session
only (wolframscript run):
sq[x_] := x^2; pkg`cube[x_] := x^3;
LaunchKernels[1];
{KeyTake[WolframDebugging`ParallelCapture[sq, {1, 2, 3}], {"Kernels", "RanInMaster", "ProblemCount", "FirstResults"}],
WolframDebugging`ParallelCapture[pkg`cube, {2}]["Problems"][[1, {"ResultString", "MasterOnlyHeads"}]]}
(* {<|"Kernels" -> 1, "RanInMaster" -> 0, "ProblemCount" -> 0, "FirstResults" -> {"1", "4", "9"}|>,
<|"ResultString" -> "pkg`cube[2]", "MasterOnlyHeads" -> {"pkg`cube"}|>} *)
KernelReport[]
Parallel kernels and their process IDs, WolframKernel child processes of this kernel and those not tracked as
subkernels (orphans), and the number of tasks. "ChildKernels" is Missing["RunProcessUnavailable"] in MCP Local. A
kernel just closed can still be listed as a child for a moment.
KeyTake[WolframDebugging`KernelReport[], {"Kernels", "ChildKernels", "Tasks"}]
(* <|"Kernels" -> {}, "ChildKernels" -> {}, "Tasks" -> 0|> *)
With one subkernel (wolframscript): <|"Kernels" -> {"Local (1) id=1"}, "SubkernelPIDs" -> {4243}|>.
TaskReport[]
<|"Count", "Tasks" -> {<|"UUID", "Status", "Type", "Expression", "Runs"|>, ...}|> (first 25), e.g.
<|"Count" -> 0, "Tasks" -> {}|>. In MCP Local, Tasks[] includes other sessions' tasks: remove only your own.
SubmitAndWait[expr, timeout]
Runs expr as a SessionSubmit task under $CaptureFunction, waits at most timeout (10) seconds, removes the task
and returns the capture record plus "Wait" ("Finished" | "TimedOut").
KeyTake[WolframDebugging`SubmitAndWait[1/0; 5], {"ResultString", "Messages", "Wait"}]
(* <|"ResultString" -> "5", "Messages" -> {"Power::infy: Infinite expression 0^(-1) encountered."}, "Wait" -> "Finished"|> *)
Cloud and HTTP
HTTPSummary[response, opts]
<|"StatusCode", "ContentType", "Text"|> of an HTTPResponse or a URLRead[..., {"StatusCode", "Headers", "Body"}]
association (HTML reduced to visible text, JSON compacted); <|"Failure", "Text", "URL"|> for a Failure. "MaxLength" (300).
WolframDebugging`HTTPSummary[HTTPResponse["<html><body>Not <b>found</b></body></html>", <|"StatusCode" -> 404, "ContentType" -> "text/html"|>]]
(* <|"StatusCode" -> 404, "ContentType" -> "text/html;charset=utf-8", "Text" -> "Not found"|> *)
DebugHTTPResponse[deployable, request, opts]
Runs GenerateHTTPResponse locally (where messages, handlers and stacks work) and returns the response summary,
"Seconds", "MessageCount", "Messages" and "FirstMessageStack" (from the first user-code frame on). request: an
HTTPRequest, a URL, or an association/list of parameters. Options: "Method" ("GET"; "POST" sends the parameters as a
form body); "MaxMessages" (10); "StackFrames" (8); "StringLength" (200); "MaxLength" (300); "SuppressPrinting"
(True).
api = APIFunction[{"a" -> "Integer", "b" -> "Integer"}, myFn[#a, #b] &];
KeyTake[WolframDebugging`DebugHTTPResponse[api, <|"a" -> "-1", "b" -> "1"|>], {"StatusCode", "Text", "MessageCount", "FirstMessageStack"}]
(* <|"StatusCode" -> 200, "Text" -> "{-1, ComplexInfinity, 1}", "MessageCount" -> 1,
"FirstMessageStack" -> {"myFn[-1, 1]", "Table[otherFn[i], {i, -1, 1}]", "otherFn[i]", "1/0", "0^(-1)"}|> *)
deployable: an APIFunction, a FormFunction ("Method" -> "POST" to submit it) or a Delayed.
GenerateHTTPResponse runs the body under EvaluationData, which catches every Throw (status 500 with
Throw::nocatch): the collector only records.
HTTPDiagnostics[expr, opts]
The body wrapper for deployed code:
APIFunction[{...}, WolframDebugging`HTTPDiagnostics[myFn[#a, #b], "TimeLimit" -> 250] &] (load the package before
CloudDeploy). Returns the value of expr unchanged, or a JSON HTTPResponse: "Success", "Reason" ("Messages",
"UncaughtThrow", "Aborted", "TimedOut", "FailureResult", "DebugRequested"), "Result", "Messages",
"Output" (Print text), "Stack" (at the first message, or the last sample on a time-out), "Seconds",
"Environment", "Request". Options: "Debug" (False; Automatic: on for debug=1/true/yes); "DebugParameter"
("debug"); "FailOnMessages" (True); "TimeLimit" (None | seconds below the 300 s limit); "StatusCode" (500);
"StackFrames" (8); "MaxMessages" (10); "StringLength" (200); "MaxPrints" (10); "Log" (None |
CloudObject/file: PutAppend, read with ReadList).
The report goes to whoever made the request and holds the request parameters, messages, stack frames, Print text and
results, so deploy the wrapped code with the default Permissions -> "Private" (call it as the owner with
URLRead[HTTPRequest[obj, ...]]) and take the wrapper out before others use the API. With "Debug" -> Automatic, any
caller can ask for a report.
WolframDebugging`HTTPSummary[WolframDebugging`HTTPDiagnostics[myFn[-1, 1]], "MaxLength" -> 150]
(* <|"StatusCode" -> 500, "ContentType" -> "application/json", "Text" -> "{\"Success\":false,\"Reason\":\"Messages\",
\"Result\":\"{-1, ComplexInfinity, 1}\",\"Messages\":[{\"Message\":\"Power::infy\",\"Text\":\"Power::infy: Infinite express..."|> *)
Deployed ("WebAPI"), a=-1, b=1 answered 500 with "Stack":["myFn[-1, 1]",...,"0^(-1)"], an endless loop with a 5 s
"TimeLimit" answered "Reason":"TimedOut" with the sampled stack, and with "Debug" -> Automatic, debug=1 answered
200 with "DebugRequested";
as the body of a deployed Delayed or FormFunction it answered the same 500 report.
WithHTTPLog[expr, opts]
Every HTTP request made through URLFetch (URLRead, URLExecute, CloudGet, CloudPut, ...) or URLSave (Import
of a URL, URLDownload): function, method, URL, status, seconds. Shows the 404 that URLExecute hid. Options:
"MaxRequests" (50); "URLLength" (120); "MaxResultBytes". Returns <|"Result", "RequestCount", "Requests"|>.
WolframDebugging`WithHTTPLog[Quiet[URLRead["http://127.0.0.1:1/x", TimeConstraint -> 5]]]["Requests"]
(* {<|"Function" -> "URLFetch", "Method" -> "GET", "URL" -> "http://127.0.0.1:1/x", "Status" -> $Failed, "Seconds" -> 0.065|>} *)
Headless and Environments
EnvironmentFingerprint[], EnvironmentFingerprint[keys, opts], EnvironmentFingerprint[All, opts]
The kernel described compactly: "Kind", "Version", "CommandLineFlags", "ProtectedMode", "FrontEnd",
"InitFiles", "ContextPath", "PathExtras", "Directories", "Encoding", "Locale", "Persistence", "Limits",
"Hooks", "Handlers", "OffGeneralMessages", "OptionsHash", "TraceWorks", "Paclets" (option), ... (All adds the
slow "CloudConnected"). Put one in environment A, compare in B with FingerprintDiff[Get[file], ...].
fp = WolframDebugging`EnvironmentFingerprint[];
KeyTake[fp, {"Kind", "CommandLineFlags", "TraceWorks", "Handlers"}]
(* <|"Kind" -> "wolframscript", "CommandLineFlags" -> {"-runfirst", "-linkmode", "-linkname", "-mathlink"}, "TraceWorks" -> True,
"Handlers" -> <|"MessageTextFilter" -> 1|>|> *)
MCP Local adds "VetoableValueChange", "GetFileEvent" and "Message" handlers (one each).
FingerprintDiff[fpA, fpB, ignore]
The nested keys ("Limits/RecursionLimit") whose values differ: {valueA, valueB}, or <|"OnlyInA", "OnlyInB"|> for
lists. ignore defaults to the volatile keys ("ProcessID", "SessionTime", "MemoryMB", "TimeRemaining", ...).
WolframDebugging`FingerprintDiff[fp, Append[fp, "TraceWorks" -> ! fp["TraceWorks"]]]
(* <|"TraceWorks" -> {True, False}|> *)
FrontEndCalls[expr, timeout]
Counts the front end requests expr makes (every request goes through MathLink`CallFrontEnd), the front end
messages, and whether a headless front end was launched. timeout defaults to 60 s (below the remaining tool time).
Quiet[WolframDebugging`FrontEndCalls[NotebookDirectory[]]]
(* <|"Result" -> "$Failed", "FrontEndCalls" -> <|"FrontEnd`EvaluationNotebook" -> 1|>,
"FrontEndMessages" -> {"FrontEndObject::notavail (quiet)"}, "LaunchedFrontEnd" -> False, "Seconds" -> 0.|> *)
RunIsolated["code" or File[path], opts]
Runs code in a fresh wolframscript kernel with a hard kill time limit (timeout -s KILL) in a private working
directory, kills leftover kernels and their children afterwards, and returns "ExitCode", "Status" ("OK",
"TimedOut" (exit code 124, or 137 after the full time limit), "Killed" (137 earlier, e.g. out of memory),
"Crashed" for other exit codes above 128, "Failed"), "Seconds", the tails of
"StdOut"/"StdErr" and "KilledLeftovers". Options: "TimeLimit" (60); "MaxOutput" (2000 characters);
"Executable" (Automatic). Needs RunProcess and the timeout command (tested on Linux):
Failure["ProtectedMode", ...] in MCP Local.
WolframDebugging`RunIsolated["Print[1 + 1]", "TimeLimit" -> 60]
(* <|"ExitCode" -> 0, "Status" -> "OK", "Seconds" -> 6.2, "StdOut" -> "2\n", "StdErr" -> "", "KilledLeftovers" -> {}|> *)
Static Checks
LintSummary["code" or File[path], minConfidence]
One line per CodeInspector issue with confidence minConfidence (0.5) or more, formatting and remarks excluded, first
50: "L<line>:<column> Tag (Severity confidence) description", or "No issues.".
WolframDebugging`LintSummary["f[x_] := If[x = 1, {1,2,}, x]"]
(* "L1:13 IfSet (Warning 0.85) `If` has `Set` as first argument.\nL1:25 Comma (Error 1.) Extra `,`." *)
Messages and stacks
How to see messages as data (which message, from where, printed or quieted), how Quiet, Off, Check,
General::stop and $MessageList really behave, how to get a stack trace at a message or at any call, and how to read,
filter and shrink stacks. Read it when code issues messages, returns $Failed, hits a recursion limit or throws
unexpectedly. Behavior was checked with Wolfram 15.0 (MCP Local, MCP Session, wolframscript, CloudEvaluate and the remote
MCP server where stated; see Environments.md for these names).
The examples use these definitions:
otherFn[x_] := 1/x; myFn[a_, b_] := Table[otherFn[i], {i, a, b}];
Which tool for which question
| question | first choice | section |
|---|---|---|
| which messages, printed or quieted, from where? | a "Message" handler that records into an Internal`Bag; WolframDebugging`CollectMessages[expr] | Message handlers |
| first message only, as data, nothing printed | Enclose[ConfirmQuiet[expr], ...] | Messages as data |
| all messages, Print output and timing as data | EvaluationData[expr]; WolframDebugging`CaptureEvaluation[expr] | Messages as data |
| the call chain that led to a message | handler + Throw[Stack[_], tag] + StackBegin[StackComplete[expr]]; WolframDebugging`StackAtMessage[expr, Power::infy] | Stack at a message |
the stack (with argument values) when f gets particular arguments | never-matching conditional rule; WolframDebugging`StackAtCall[expr, f[0]] | Stack at a call |
| hide or rewrite one message | "Message.Veto", "MessageTextFilter" handlers | Other handler types |
recursion/iteration limit, uncaught Throw, failed Assert | lower the limit + stack at the message; probe Throw; "Assertions" handler | Other triggers |
Helpers are in scripts/WolframDebugging.wl (load it with Get in its own call, call them fully qualified; options and
outputs: HelperFunctions.md). Everything below works without them, including on the remote MCP server.
Message handlers: Internal`HandlerBlock
Internal`HandlerBlock[{"Message", f}, expr] calls f for every message issued while expr evaluates, then removes
f. The argument is Hold[Message[name, args...], willPrint]:
Internal`HandlerBlock[{"Message", Print[ToString[#, InputForm]] &}, {myFn[-1, 1], Quiet[First[{}]]}]
Power::infy: Infinite expression 1/0 encountered. (printed first; 2-D in wolframscript)
Hold[Message[Power::infy, HoldCompleteForm[0^(-1)]], True]
Hold[Message[First::nofirst, HoldCompleteForm[{}]], False] (quieted: willPrint is False)
Out= {{-1, ComplexInfinity, 1}, First[{}]}
- Arguments of messages issued by kernel functions are wrapped in
HoldCompleteFormin 15.0 (older versions:HoldForm); arguments of an explicitMessage[f::tag, 5]arrive unwrapped:Hold[Message[f::tag, 5], True]. The held argument ofPower::infyis0^(-1)(the message comes fromPower[0, -1], not from1/0). Printin a handler is only for illustration: one evaluation can issue thousands of messages (a fresh kernel loading a package issues quietedGeneral::newsymby the thousand). Record into a bag and filter onwillPrint(Last[m]).Print[InputForm[x]]in awolframscript -fscript prints the textInputForm[...]with string quotes stripped; usePrint[ToString[x, InputForm]].
Collect the printed messages without stopping (MCP Local, MCP Session, wolframscript, CloudEvaluate; on the remote MCP server see Environments below):
Module[{bag = Internal`Bag[]},
Internal`HandlerBlock[{"Message", Function[m, If[Last[m],
Internal`StuffBag[bag, Replace[m, Hold[Message[mn_, ___], _] :> ToString[Unevaluated[mn], InputForm]]]]]},
{Quiet[1/0], First["xyz"]}];
Internal`BagPart[bag, All]]
(* {"First::normal"} -- the quieted Power::infy arrived with willPrint False and was skipped *)
WolframDebugging`CollectMessages[expr] does this with message text, a printed/quieted flag and the last stack frames
of each message.
Rules for writing handlers:
- Never use
#[[1]]on the handler argument:Partre-evaluatesMessage[...](the message is issued again and the extracted value isNull).#[[1, 1]]evaluates the message name:General::stopbecomes its template text. Use patterns (Hold[Message[mn_, args___], flag_]does not evaluate anything),Delete[#, -1](→Hold[Message[...]]),Extract[#, {1, 1}, HoldForm](→HoldForm[First::nofirst]) andLast[#](the flag). - Exactly one
{"Type", f}pair perHandlerBlock; nest blocks for several handlers. A malformed spec (for example{{"Message.Veto", f}, {"Message", g}}) issuesInternal`HandlerBlock::stringand does not evaluate the body. - Handlers are added, never replaced: the MCP evaluator's own Chatbook handlers keep running beside yours. Handlers run
in installation order (oldest first); a handler that
Throws stops the newer ones from seeing that message. - The
"Message"handler's return value is ignored and it runs after the text was printed: it cannot hide a message (use"Message.Veto"). Stop the evaluation from a handler with a taggedThrow(orAbort[]). - A message pattern written as
mySym::erroutside a hold evaluates to its text if the message has one; match insideHold[Message[mySym::err, ___], _]or compare names as strings.
What willPrint means
| situation | willPrint | text printed |
|---|---|---|
| plain message | True | yes |
inside Quiet[...], after Off[msg], inside Internal`DeactivateMessages or ConfirmQuiet | False | no |
4th and later occurrence after General::stop | True | no |
General::stop itself | True | yes |
Off[General::stop] | True | yes, every occurrence |
inside Block[{$Messages = {}}, ...] | True | no (MCP Session still shows it) |
Quiet[expr, None, All] inside an outer Quiet | True | yes (cancels the outer Quiet) |
remote MCP server (every input runs inside Quiet) | always False | shown by the server anyway |
| message issued in a parallel subkernel | handler in the master not called | printed by the master as From kernel 1 ... |
True therefore means "not quieted", not "printed". Per message the handler types run in this order: "Message.Veto",
"Message.Silent", "MessageTextFilter" (skipped for quieted messages and after General::stop, still called under
$Messages = {} or when "Message.Silent" returned False), then the text is printed, then the "Message" handlers.
Persistent handlers: Internal`AddHandler, Internal`RemoveHandler, Internal`Handlers
Internal`AddHandler["Message", f] installs f globally until Internal`RemoveHandler["Message", f]. Only use it
in a throwaway kernel (wolframscript):
Internal`AddHandler["Message", Print];
First["xyz"];
Print[Internal`Handlers["Message"]];
Internal`RemoveHandler["Message", Print];
Print[Internal`Handlers["Message"]];
Internal`RemoveHandler["Message", Print];
First::normal: Nonatomic expression expected at position 1 in First[xyz].
Hold[Message[MessageName[First, normal], HoldCompleteForm[1], HoldCompleteForm[First[xyz]]], True]
Message -> {Print}
Message -> {}
Internal`RemoveHandler::noevent: -- Message text not found -- (Message) (removing a handler that is not installed)
- Global handlers leak. They persist across MCP calls (both methods); in MCP Local they fire for every session and
agent sharing the subkernel; in MCP Session they also see the server's own quieted messages (about 11
Show::gtypeper1 + 1call). A notebook can show stray handler output from front-end background evaluations (untested). - Reference counted: adding the same handler twice lists it once but needs two removals.
Internal`Handlers[]lists every handler type ("Message","Message.Veto","Message.Silent","MessageTextFilter","GetFileEvent","NewSymbol","ValueChange","Assertions","Wolfram.System.Print", ...);Internal`Handlers["Message"]gives"Message" -> {newest, ..., oldest}.Select[Internal`Handlers[], Last[#] =!= {} &]shows what is installed: in MCP Local a J/Link"VetoableValueChange", an MUnit"GetFileEvent",Internal`MessageButtonHandler("MessageTextFilter") and Chatbook's"Message"handler; in a fresh wolframscript only the"MessageTextFilter"one.
If a global handler is unavoidable (for example the code under test spawns evaluations a block does not cover), add and remove it in the same call:
Module[{bag = Internal`Bag[], h},
h = Function[m, If[Last[m], Internal`StuffBag[bag, Extract[m, {1, 1}, HoldForm]]]];
WithCleanup[Internal`AddHandler["Message", h]; myFn[-1, 1], Internal`RemoveHandler["Message", h]];
{Internal`BagPart[bag, All], MemberQ[Last[Internal`Handlers["Message"]], h]}]
(* {{HoldForm[Power::infy]}, False} -- recorded, and removed again *)
Other handler types: hide, silence or rewrite messages
Internal`HandlerBlock[{"Message.Veto", (!MatchQ[#, Hold[Message[Power::infy, ___], _]]) &},
{Check[1/0, "Check fired"], First[{}]}]
(* only First::nofirst is printed; {ComplexInfinity, First[{}]} -- the vetoed message did not trigger Check *)
"Message.Veto": same argument as"Message"; returning exactlyFalseremoves the message completely (not printed,Checkdoes not fire,"Message"handlers not called, hidden from the MCP tool output in MCP Local and MCP Session). Any other return value lets it through."Message.Silent": returningFalsesuppresses only the text; the message still counts (Internal`HandlerBlock[{"Message.Silent", False &}, Check[1/0, "Check fired"]]→"Check fired", nothing printed in MCP Local and wolframscript). In MCP Session the tool output still shows the message."MessageTextFilter": called with the text template,Hold[name]andHold[Message[...]]; a returned string replaces the template. Works in MCP Local and wolframscript, no effect on MCP Session output:
Internal`HandlerBlock[{"MessageTextFilter", ("[myFn] " <> #1) &}, First[{}]]
(* First::nofirst: [myFn] {} has zero length and no first element. *)
- Shorter message arguments:
Block[{$MessagePrePrint = Shallow}, Range[200][[300]];]printsPart::partw: Part 300 of {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, <<190>>} does not exist.(MCP Local, wolframscript; MCP Session ignores it and truncates long arguments itself).$MessagePrePrint = Shorthas no effect (infinite page width).
Quiet, Off, Check, General::stop, $Messages and $MessageList
| mechanism | effect | scope and gotchas |
|---|---|---|
Quiet[expr], Quiet[expr, {msgs}] | not printed, willPrint False, Check outside does not fire | scoped: preferred. Quiet[expr, None, All] cancels an outer Quiet |
Off[msg] / On[msg] | like Quiet for that message | global: persists across MCP calls and sessions. Use Quiet[expr, {msg}] instead |
Check[expr, failExpr] | returns failExpr if an unquieted message was issued; does not stop evaluation or suppress printing | Quiet[Check[1/0, "x"]] → "x" (still fires); Check[Quiet[1/0], "x"] → ComplexInfinity |
General::stop | after 3 occurrences of a message in one evaluation the rest are not printed | accounting uses $MessageList; willPrint stays True |
Block[{$Messages = {}}, expr] | nothing printed, everything else unchanged (Check fires, handlers see True) | MCP Session ignores it ($Messages is already {} there; the tool collects messages through a handler) |
$MessageList | list of HoldForm[name] issued in the current evaluation | Protected: $MessageList = {} gives Set::wrsym; use Block[{$MessageList = {}}, expr] |
$MessageList is reset for every input in MCP Local (each line or multi-line expression of a tool call), once per
script in wolframscript (a whole -f file is one evaluation) and wolfram -script (the third First[{}] statement of a
file triggers General::stop), and never in MCP Session (it accumulates over the server's lifetime and all sessions,
so General::stop can fire on the first occurrence in a call: the third Power::infy of a session prints it). Wrap
experiments in Block[{$MessageList = {}}, ...].
Quieted messages are added while inside Quiet (and count toward General::stop), but Quiet restores the list on exit:
{Block[{$MessageList = {}}, Quiet[Table[1/0, 5]]; $MessageList], Block[{$MessageList = {}}, Quiet[Table[1/0, 5]; $MessageList]]}
(* {{}, {HoldForm[Power::infy], HoldForm[Power::infy], HoldForm[Power::infy], HoldForm[General::stop]}} *)
When counting occurrences, use fresh expressions: an unchanged literal subexpression such as First[{}] is evaluated
only once, so Do[First[{}], 4] issues one message while Do[g[{}], 4] with g[x_] := First[x] issues four.
Messages as data: EvaluationData, ConfirmQuiet
KeyTake[Block[{$Messages = {}}, EvaluationData[myFn[-1, 1]]], {"Success", "FailureType", "MessagesExpressions", "OutputLog"}]
(* <|"Success" -> False, "FailureType" -> "MessageFailure",
"MessagesExpressions" -> {Hold[Message[Power::infy, HoldCompleteForm[0^(-1)]]]}, "OutputLog" -> {}|> *)
- Keys:
"Result"(aRuleDelayed),"Success","FailureType","OutputLog"(Print/Echo text),"Messages","MessagesText","MessagesExpressions","Timing","AbsoluteTiming","InputString". Quieted messages are not recorded. It does not suppress printing (hence theBlock; in MCP Session the tool shows the messages anyway). - Use
"MessagesExpressions":"Messages"holds evaluated names, soGeneral::stop,Throw::nocatchand user messages with text appear as template strings ("Uncaught `1` returned to top level."). EvaluationDatacatches everyThrow, tagged or not:KeyTake[Catch[EvaluationData[Throw[1, "t"]], "t"], {"Result", "Success"}]→<|"Result" :> Hold[Throw[1, "t"]], "Success" -> False|>plusThrow::nocatch(see "When a Throw-based probe returns the normal result" below).
First message only, evaluation stopped there, nothing printed:
Enclose[ConfirmQuiet[myFn[-1, 1]], #[{"HeldMessageName", "HeldMessageCall"}] &]
(* {Hold[Power::infy], Hold[Message[Power::infy, HoldCompleteForm[0^(-1)]]]} *)
ConfirmQuiet[expr, {msg}] reacts only to the listed messages. Other Confirm* functions ignore messages.
Stacks: Stack, StackBegin, StackComplete
Stack[]: the heads of the expressions being evaluated (tiny).Stack[_]: every frame asHoldCompleteForm[expr](older versions:HoldForm).Stack[patt]: frames whose expression matchespatt.- A frame holds the latest form of an evaluation chain: when
f[x]is rewritten by its definition, its frame is replaced by the right-hand side (Module[...],If[...], ...), sofitself vanishes from the stack, whatever its body.StackComplete[expr]keeps those frames. StackBegin[expr]starts a fresh stack (removes the frames of whatever runs your code: wolframscript, CloudEvaluate).- Nest them as
StackBegin[StackComplete[expr]]:StackBegininsideStackCompleteturnsStackCompleteoff. - Frames show expressions as they were pushed:
otherFn[i]insideTable, nototherFn[0]. For argument values use the stack-at-a-call probe below.
outerFn[x_] := innerFn[x^2]; innerFn[y_] := Stack[_];
{StackBegin[outerFn[2]], StackBegin[StackComplete[outerFn[2]]], StackComplete[StackBegin[outerFn[2]]]}
(* {{}, {HoldCompleteForm[StackComplete[outerFn[2]]], HoldCompleteForm[outerFn[2]], HoldCompleteForm[innerFn[2^2]]}, {}} *)
Stack size added by each environment (why StackBegin matters):
| environment | Stack[_] at top level | stack at Power::infy in StackComplete[myFn[-3, 3]] without StackBegin |
|---|---|---|
| MCP Local, MCP Session | none (Stack[_] as the whole input is {}) | 13 frames |
| remote MCP server | 2–3 frames (they hold your whole input) | not checked |
| wolframscript | 17–19 frames, 90–120 KB (the frames embed the script) | 28 frames, 120 KB |
wolfram -script | 3–4 frames | 14 frames |
| CloudEvaluate | about 68 frames, 310 KB | 78 frames, 315 KB |
With StackBegin the stack at that message is 9 frames and 2.1 KB in every environment. A real package stack is large:
in a fresh kernel, the stack at URLRead::invhttp from StackBegin[StackComplete[URLRead["http://localhost:1/x"]]] had
59 frames, 269 KB, about 83,000 characters in InputForm. Capturing is cheap; never return a raw stack from an MCP call,
format it (below).
Frames are inert only while wrapped. First[frame], frame[[1]], ReleaseHold[frame], First /@ stack and
Cases[stack, HoldCompleteForm[e_] :> e] evaluate the frame again (side effects, repeated messages, even re-running the
Throw that captured it). Safe: patterns, Extract[frame, 1, Hold], Cases[stack, _[(h_Symbol)[___]] :> h], and
Replace[stack, _[e_] :> ToString[Unevaluated[e], InputForm, TotalWidth -> 150], {1}].
Stack at a message
Throw the stack from a "Message" handler (MCP Local, MCP Session, wolframscript, CloudEvaluate):
Module[{tag, st},
st = Catch[Internal`HandlerBlock[{"Message", Replace[#, Hold[Message[_, ___], True] :> Throw[Stack[_], tag]] &},
StackBegin[StackComplete[myFn[-1, 1]]]], tag];
If[ListQ[st],
Block[{$ContextPath = Join[{"Global`", $Context}, $ContextPath]},
StringRiffle[Replace[Take[st, Position[st, _[_Message], {1}][[-1, 1]]],
_[e_] :> ToString[Unevaluated[e], InputForm, TotalWidth -> 150], {1}], "\n"]],
st]] (* st is the normal result when no message was issued *)
StackComplete[myFn[-1, 1]]
myFn[-1, 1]
Table[otherFn[i], {i, -1, 1}]
otherFn[i]
1/0
0^(-1)
Message[Power::infy, HoldCompleteForm[0^(-1)]]
- One specific message:
Hold[Message[Power::infy, ___], True]. Heads only:Stack[]instead ofStack[_]→{StackComplete, myFn, Table, otherFn, Times, Power, Message, Function, Replace, Throw}. Take[..., Position[...][[-1, 1]]]drops the handler's own frames after theMessageframe. The$ContextPathblock avoids context prefixes on your symbols.- The message is printed before the handler runs, and the
Throwabandons the computation (the result is lost). WithoutStackCompletethemyFnandotherFnframes are missing; withoutStackBeginyou get the wrapper frames above. - Package code often issues and quiets internal messages before the public one (
URLReadquietsURLFetch::invhttp, then issuesURLRead::invhttp; a fresh kernel also sent 15,000 quietedGeneral::newsymduring that call); matchingTrueskips them.
The same with a named handler, keeping the raw frames for the filters below:
infyHandler[Hold[Message[Power::infy, ___], True]] := Throw[Stack[_], "infy"];
stk = Catch[Internal`HandlerBlock[{"Message", infyHandler}, StackBegin[StackComplete[myFn[-3, 3]]]], "infy"];
{Length[stk], ByteCount[stk]}
(* {9, 2104} *)
WolframDebugging`StackAtMessage[expr, Power::infy] returns the stack up to the message as one string of numbered
lines ("Stack"; raw frames on request, see HelperFunctions.md);
WolframDebugging`FormatStack[stack] renders any stack as numbered, truncated lines and collapses recursion cycles;
WolframDebugging`StackSummary[stack] gives its length, size, most common heads and contexts.
Filter, trim and format a stack
Only frames of your own functions. Typed code lives in Global` (wolframscript, cloud) or in Sessions`<id>`
($Context in the MCP evaluator), so test both (add your package contexts):
Cases[stk, _[(s_Symbol)[___]] /; MemberQ[{"Global`", $Context}, Context[s]]]
(* {HoldCompleteForm[myFn[-3, 3]], HoldCompleteForm[otherFn[i]], HoldCompleteForm[infyHandler[Hold[Message[...], True]]]} *)
From the first frame matching a pattern on:
Replace[stk, {___, first : _[_myFn], rest___} :> {first, rest}] // Length
(* 8 *)
The last n frames as one line each (Take[st, -UpTo[n]] is invalid; use -Min[n, Length[st]]):
Block[{$ContextPath = Join[{"Global`", $Context}, $ContextPath]},
StringRiffle[Replace[Take[stk, -Min[5, Length[stk]]],
_[e_] :> ToString[Unevaluated[e], InputForm, TotalWidth -> 100], {1}], "\n"]]
1/0
0^(-1)
Message[Power::infy, HoldCompleteForm[0^(-1)]]
infyHandler[Hold[Message[Power::infy, HoldCompleteForm[0^(-1)]], True]]
Throw[Stack[_], "infy"]
Which functions dominate (deep recursion):
Tally[Cases[stk, _[(h_Symbol)[___]] :> h]]
(* {{StackComplete, 1}, {myFn, 1}, {Table, 1}, {otherFn, 1}, {Times, 1}, {Power, 1}, {Message, 1}, {infyHandler, 1}, {Throw, 1}} *)
TotalWidth truncates structurally ({1, 2, ..., <<962>>, ...}) but does not shorten one long string, and widths below
about 15 give "-toobig-" with Format::toobig: add StringTake[s, UpTo[n]] for hard limits. Short does nothing in the
MCP evaluator or wolframscript.
Stack at a call with particular arguments
Prepend a rule whose condition records the stack and then fails. The condition runs while the call frame, with its evaluated arguments, is on the stack; evaluation is otherwise unaffected and the definitions are restored afterwards:
probeBag = Internal`Bag[];
Internal`InheritedBlock[{otherFn},
DownValues[otherFn] = Prepend[DownValues[otherFn],
HoldPattern[otherFn[0]] /; (Internal`StuffBag[probeBag, Stack[_]]; False) :> Null];
Quiet @ StackBegin[myFn[-3, 3]]]
(* {-1/3, -1/2, -1, ComplexInfinity, 1, 1/2, 1/3} -- normal result *)
{Internal`BagLength[probeBag], Internal`BagPart[probeBag, 1], DownValues[otherFn]}
(* {1, {HoldCompleteForm[Table[otherFn[i], {i, -3, 3}]], HoldCompleteForm[otherFn[0]],
HoldCompleteForm[Internal`StuffBag[probeBag, Stack[_]]; False], HoldCompleteForm[Internal`StuffBag[probeBag, Stack[_]]]},
{HoldPattern[otherFn[x_]] :> 1/x}} *)
- The frame shows
otherFn[0], the actual argument. Putting the capture in the right-hand side instead would replace the call frame. - Stop at the first hit by throwing from the condition:
Catch[Internal`InheritedBlock[{otherFn},
DownValues[otherFn] = Prepend[DownValues[otherFn],
HoldPattern[otherFn[x_ /; x == 0]] /; (Throw[Stack[], "probe"]; False) :> Null];
StackBegin[StackComplete[myFn[-3, 3]]]],
"probe"]
(* {StackComplete, myFn, Table, otherFn, CompoundExpression, Throw} *)
- System functions:
Unprotectinside the block (attributes and definitions come back on exit):
Module[{bag = Internal`Bag[]},
Internal`InheritedBlock[{StringLength},
Unprotect[StringLength];
PrependTo[DownValues[StringLength],
HoldPattern[StringLength[x_ /; !StringQ[x]]] /; (Internal`StuffBag[bag, Stack[]]; False) :> Null];
Quiet @ StackBegin[StringLength /@ {"ab", 7}];];
{Internal`BagPart[bag, All], MemberQ[Attributes[StringLength], Protected], DownValues[StringLength]}]
(* {{{List, StringLength, CompoundExpression, Internal`StuffBag}}, True, {}} *)
- End the block body with
;(or returnHoldComplete[...]): the value of anInternal`InheritedBlockthat changed a definition is evaluated again after the block exits, outside yourQuiet(StringLength[7]returned from the block printedStringLength::stringagain). WolframDebugging`StackAtCall[expr, otherFn[0]]does this for any call pattern. Literal rules such asf[0] = 1are tried before your conditional rule, and calls made from kernel code (Total, auto-compiledTable) never reach it; seeOverridesAndWatchpoints.mdfor the full list of what an override does not see.
Other triggers
$RecursionLimit and $IterationLimit
Lower the limit locally (defaults 1024 and 4096) and capture the stack at the message. In MCP Local do this only after
the subkernel has printed an ordinary message (1/0; in an earlier call): its first message fails under a low limit and
leaves $Context broken for every session (Environments.md).
recFn[n_] := 1 + recFn[n + 1];
recStk = Catch[Internal`HandlerBlock[{"Message", Throw[Stack[_], "rec"] &},
StackBegin[Block[{$RecursionLimit = 20}, recFn[1]]]], "rec"];
{Length[recStk], Tally[Cases[recStk, _[(h_Symbol)[___]] :> h]]}
(* {22, {{Block, 1}, {Plus, 18}, {recFn, 1}, {Message, 1}, {Throw, 1}}} -- the message is $RecursionLimit::reclim *)
itFn[n_] := itFn[n + 1];
Catch[Internal`HandlerBlock[{"Message", Throw[Stack[_], "it"] &},
StackBegin[Block[{$IterationLimit = 50}, itFn[1]]]], "it"]
(* 4 frames: Block[{$IterationLimit = 50}, itFn[1]], itFn[50 + 1], Message[$IterationLimit::itlim, ...], Throw[...] *)
While/Do loops do not count toward $IterationLimit; for loops use stack sampling (TracingAndPerformance.md).
Never set $RecursionLimit globally in an MCP kernel (in MCP Session a low global value closed the server); use Block.
In 15.0 the runaway evaluation is replaced by TerminatedEvaluation[...], and how much is replaced depends on the
environment:
{Block[{$RecursionLimit = 50}, recFn[1]], "after"}
(* MCP Local, MCP Session: {TerminatedEvaluation["RecursionLimit"], "after"}
wolfram -script: the same inside Print[ToString[...]]; a statement ending in ";" is dropped whole; later lines run
wolframscript -f: the whole script ends; its result is TerminatedEvaluation[RecursionLimit], later lines never run
CloudEvaluate: Hold[Throw[TerminatedEvaluation["RecursionLimit"], TerminatedEvaluation["RecursionLimit", 50]]] + Throw::nocatch *)
Contain it portably (checked in MCP Local, MCP Session, wolframscript and the remote MCP server; in CloudEvaluate with a
limit of 150, because its 64 wrapper frames count toward the limit). The termination is a Throw with a
TerminatedEvaluation[...] tag, but under StackBegin in wolframscript a Catch sees it only when a
CompoundExpression, Module, Block, Table or another Catch lies between them (not a list, If, With or a
function argument). Both MCP methods run every input under a StackBegin-like wrapper (Stack[_] at the top is
{}), with a slightly different rule: a Catch[...] that is the whole input, sits directly inside If or With, or is
the right-hand side of a function you call becomes TerminatedEvaluation["RecursionLimit"] itself (its handler is not
called), while one inside a list or a function argument, or res = Catch[...]; ..., works. Assign the result and also
test the value:
recRes = Catch[Block[{$RecursionLimit = 50}, recFn[1]], _TerminatedEvaluation, Function[{value, tag}, tag]];
If[FreeQ[recRes, _TerminatedEvaluation], recRes, Failure["RecursionLimit", <|"Terminated" -> recRes|>]]
(* Failure["RecursionLimit", <|"Terminated" -> TerminatedEvaluation["RecursionLimit", 50]|>] *)
Wrapping the part in StackBegin[...] also keeps wolframscript from ending the script (that part becomes
TerminatedEvaluation["RecursionLimit"]).
Uncaught Throw (Throw::nocatch)
Throw::nocatch is issued after the evaluation has unwound, so "Message" handlers never see it (and in
wolfram -script an uncaught Throw ends the file silently). Find where the Throw comes from by probing Throw
itself, in record mode (throwing from the condition of a rule for Throw is unreliable: unless a Catch for the
original tag lies inside yours, the original or your Throw ends up uncaught):
thrower[x_] := Throw[x, "nope"]; wrapper[x_] := 1 + thrower[x];
Module[{bag = Internal`Bag[]},
Internal`InheritedBlock[{Throw},
Unprotect[Throw];
PrependTo[DownValues[Throw],
HoldPattern[Throw[_, "nope"]] /; (Internal`StuffBag[bag, Stack[]]; False) :> Null];
Catch[StackBegin[StackComplete[wrapper[5]]], _, Function[{value, tag}, Null]];];
Internal`BagPart[bag, All]]
(* {{StackComplete, wrapper, Plus, thrower, Throw, CompoundExpression, Internal`StuffBag}} *)
Assert
An "Assertions" handler receives every failing Assert as HoldComplete[Assert[test]] (with {line, file} when the
code was loaded with Get), even though Assert is off by default; passing assertions are not reported:
assertFn[x_] := (Assert[x > 0]; Sqrt[x]);
Module[{bag = Internal`Bag[]},
Internal`HandlerBlock[{"Assertions", Internal`StuffBag[bag, {#, Stack[]}] &},
StackBegin[StackComplete[assertFn /@ {4, -1}]]];
Internal`BagPart[bag, All]]
(* {{HoldComplete[Assert[-1 > 0]], {StackComplete, Map, List, assertFn, CompoundExpression, Assert, Function, Internal`StuffBag, List}}}
loaded from a file: HoldComplete[Assert[-1 > 0, {1, "/path/to/file.wl"}]] *)
WolframDebugging`FailedAssertions[expr] lists them.
When a Throw-based probe returns the normal result
A tagged Throw from your handler or probe is intercepted by a catch-all Catch[..., _] in the code under test, and by
EvaluationData, VerificationTest/TestReport and GenerateHTTPResponse; EvaluationData and GenerateHTTPResponse
turn it into Throw::nocatch, which can trigger your handler again at an unrelated place. The code continues with its
fallback and you get no stack, or the wrong one:
safeFirst[x_] := Catch[First[x], _, Function[{value, tag}, "fallback"]];
Catch[Internal`HandlerBlock[{"Message", Throw[Stack[], "msg"] &}, StackBegin[StackComplete[safeFirst[{}]]]], "msg"]
(* "fallback" *)
Record and continue instead (no Throw):
Module[{bag = Internal`Bag[]},
{Internal`HandlerBlock[{"Message", If[Last[#], Internal`StuffBag[bag, Stack[]]] &},
StackBegin[StackComplete[safeFirst[{}]]]],
Internal`BagPart[bag, All]}]
(* {First[{}], {{StackComplete, safeFirst, Catch, First, Message, Function, If, Internal`StuffBag}}} *)
Plain Catch[expr] (no tag), Enclose, Check and Quiet do not intercept a tagged Throw.
Environment notes
- Remote MCP server: every input runs inside
Quiet, so all handlers seewillPrint = Falseand recipes that test forTruerecord nothing. Detect it withLookup[Internal`QuietStatus[], "Global"] === "Quiet"("Unquiet"in MCP Local and MCP Session; do not wrap the test inQuiet). Wrap the code under test inQuiet[expr, None, All](the handler then seesTrueagain) or matchHold[Message[_, ___], _]. - MCP Local and MCP Session: messages render on one line (
InputFormtext), and a call that issued messages gets oneGeneral::messagesline (after the messages of its first input that issued any). - MCP Session: the tool collects messages through its own handler, so only
Quiet,Offand"Message.Veto"hide one from the tool output;Off,Internal`AddHandlerand limit changes affect the server. - MCP Session and the remote MCP server drop messages after 10 prints and messages in one call; return collected data as the
value instead (
Environments.md). - Parallel subkernels: master handlers,
Check,EvaluationDataand$MessageListdo not see subkernel messages; collect inside the subkernel (ParallelAndAsync.md). An unevaluated result such asFirst[{}]returned by a subkernel is evaluated again in the master and issues its message there too. On[f](trace messagesf::trace) only works whereTraceworks (TracingAndPerformance.md).
Overrides and watchpoints
How to spy on, mock or temporarily override any function (your own, a package's or a System function) with
Internal`InheritedBlock, what such overrides cannot see, which changes leak out of a block, how to keep an override
across several tool calls safely, how to find out who changes a variable (watchpoints), and other handler probes (new
symbols, file writes, failed assertions, prints). These tools work where Trace is disabled (MCP Session, the cloud).
Behavior was checked with Wolfram 15.0 in the environments named in Environments.md.
The examples use these definitions:
ClearAll[otherFn, myFn];
otherFn[x_] := 1/x; myFn[a_, b_] := Table[otherFn[i], {i, a, b}];
Which tool for which question
| question | first choice | section |
|---|---|---|
with which arguments is f called, and what does it return? | spy rule in Internal`InheritedBlock; WolframDebugging`LogCalls[{f, g}, expr] | The pattern |
make f return canned data for some arguments | prepended rule; WolframDebugging`WithOverrides[{lhs :> rhs}, expr] | Mocking |
| which HTTP requests does this code make? | spy on URLFetch | Mocking |
| my spy or mock is silently ignored | autoload stub, literal rule, C code caller, auto-compilation | What an override cannot see |
| keep an override over several tool calls | WithCleanup; WolframDebugging`SnapshotDefinitions[f] | Several tool calls |
| who changes this variable? who changes it to a bad value? | value monitor + "ValueChange" handler; WolframDebugging`WatchChanges[{x}, expr], WolframDebugging`StopWhen[x, test, expr] | Watchpoints |
| which symbols, files, failed asserts or prints does this create? | handler probes; WolframDebugging`NewSymbolsDuring[expr], WolframDebugging`FileWritesDuring[expr], WolframDebugging`FailedAssertions[expr], WolframDebugging`CapturePrints[expr, max] | Other handler probes |
the stack when f gets particular arguments | WolframDebugging`StackAtCall[expr, f[0]] | MessagesAndStacks.md |
Helpers are in scripts/WolframDebugging.wl (load it with Get in its own call, call them fully qualified; options and
outputs: HelperFunctions.md). Every recipe below works without them.
The pattern: spy on a function
Module[{calls = Internal`Bag[], inF = False, res},
otherFn; (* 1. evaluate the bare symbol: loads an autoload stub first *)
res = Internal`InheritedBlock[{otherFn}, (* 2. InheritedBlock starts from a copy of all definitions *)
Unprotect[otherFn]; (* needed for System and package symbols; restored on exit *)
PrependTo[DownValues[otherFn], (* 3. prepend: tried before the original rules, which stay *)
HoldPattern[otherFn[args___] /; !inF] :> (* 4. HoldPattern[lhs] :> rhs 5. recursion guard *)
Block[{inF = True}, Internal`StuffBag[calls, HoldComplete[args]]; otherFn[args]]];
myFn[1, 3]];
{res, Internal`BagPart[calls, All], Length[DownValues[otherFn]]}]
(* {{1, 1/2, 1/3}, {HoldComplete[1], HoldComplete[2], HoldComplete[3]}, 1} the extra rule is gone afterwards *)
Same result in MCP Local, MCP Session and wolframscript. Each element matters:
- Load autoload stubs first. Many System and package functions start as stubs that load their package on first use; an override installed before that is silently replaced and the real function runs ("What an override cannot see" below).
Internal`InheritedBlock, notBlock.Block[{f}, ...]starts from a blank symbol: no definitions, no attributes, so your rule replaces the whole function, and a System function loses its attributes (Block[{Table}, ...]dropsHoldAll).Internal`InheritedBlockstarts from a copy of everything and restores all values, attributes (Protected,ReadProtected, ...), options andMessages[f]when it exits, also afterAbort[],Throw,TimeConstrainedand MCP time-outs (exceptions: "Changes that leak out of a block"):
ClearAll[g]; g[x_] := x^2;
{Block[{g}, Length[DownValues[g]]], Internal`InheritedBlock[{g}, Length[DownValues[g]]],
Block[{Plus}, Attributes[Plus]], Internal`InheritedBlock[{Plus}, Attributes[Plus]]}
(* {0, 1, {}, {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected}} *)
- Prepend.
PrependTo[DownValues[f], rule]puts your rule first and keeps the original rules callable. ASetDelayedwith the same left-hand side replaces the original rule (even with other pattern names), and an appended rule never runs after a catch-all rule. HoldPattern[lhs] :> rhs.PrependToevaluates the rule's left-hand side. WithoutHoldPatternthe real function runs with pattern arguments and a dead rule is stored, silently:
ClearAll[sideEffect];
sideEffect[x_] := (Print["real sideEffect ran with ", x]; {"result", x});
Internal`InheritedBlock[{sideEffect},
PrependTo[DownValues[sideEffect], sideEffect[y_String] :> "MOCK"]; (* WRONG: no HoldPattern *)
{First[DownValues[sideEffect]], sideEffect["abc"]}]
(* real sideEffect ran with y_String
real sideEffect ran with abc
{HoldPattern[{"result", y_String}] :> "MOCK", {"result", "abc"}} *)
-> instead of :> evaluates the right-hand side once, when the rule is created.
5. Recursion guard. The spy calls f[args] again, which would match the spy rule forever: $RecursionLimit::reclim,
and in a wolframscript script the whole rest of the script is skipped. The guard (/; !inF plus
Block[{inF = True}, ...]) lets the inner call reach the original rules. Keep guard conditions free of side effects.
With a Boolean guard only the outermost call of a recursive function is recorded;
WolframDebugging`LogCalls[{f}, expr] records every call with its result and timing (also recursive calls, held
arguments, literal rules, Throw/Abort), and WolframDebugging`CallLogSummary[log] prints it as a tree.
The value of the block is evaluated again after the definitions are restored (also outside any Quiet inside the
block, so its messages appear). When it contains an unevaluated call of the overridden function, wrap it:
ClearAll[q]; q[1] := "outside";
{Internal`InheritedBlock[{q}, DownValues[q] = {}; q[1]], Internal`InheritedBlock[{q}, DownValues[q] = {}; HoldComplete @@ {q[1]}]}
(* {"outside", HoldComplete[q[1]]} *)
Mocking
Canned results for specific arguments (the other rules stay active):
Internal`InheritedBlock[{otherFn},
PrependTo[DownValues[otherFn], HoldPattern[otherFn[0]] :> "MOCK"];
myFn[-1, 1]]
(* {-1, "MOCK", 1} *)
WolframDebugging`WithOverrides[{lhs :> rhs, ...}, expr] does this for several rules at once (DownValues, OwnValues and
SubValues, stubs loaded first, Locked symbols rejected) and returns HoldComplete[result].
HTTP. URLRead, URLExecute and CloudGet/CloudPut all send their requests through URLFetch; Import of a URL and
URLDownload go through URLSave. URLExecute calls URLRead[{url}, elements] (a list), so the URLRead mock below
does not affect it. Mock one function for one host:
URLRead; (* load it first if it is still an autoload stub *)
Internal`InheritedBlock[{URLRead},
Unprotect[URLRead];
PrependTo[DownValues[URLRead],
HoldPattern[URLRead[url_String /; StringStartsQ[url, "https://api.example.invalid"], ___]] :>
HTTPResponse["{\"ok\":true}", <|"StatusCode" -> 200, "ContentType" -> "application/json"|>]];
With[{r = URLRead["https://api.example.invalid/x"]}, {r["StatusCode"], r["Body"]}]]
(* {200, "{\"ok\":true}"} *)
or mock URLFetch to cover URLRead and URLExecute together (it receives the URL and a list of the elements wanted):
URLFetch;
Internal`InheritedBlock[{URLFetch},
Unprotect[URLFetch];
PrependTo[DownValues[URLFetch],
HoldPattern[URLFetch[url_String /; StringContainsQ[url, "api.example.invalid"], elems_List, ___]] :>
Replace[elems, {"StatusCode" -> 200, "HeadersReceived" -> {{"content-type", "application/json"}},
"CookiesReceived" -> {}, "BodyByteArray" -> StringToByteArray["{\"answer\":42}"], other_ :> Missing["NotMocked", other]}, {1}]];
{URLExecute["https://api.example.invalid/v1", "RawJSON"], URLRead["https://api.example.invalid/v1"]["StatusCode"]}]
(* {<|"answer" -> 42|>, 200} *)
Record every request instead (the same spy around CloudPut, CloudGet or ResourceUpdate lists the cloud API URLs
they call; requests to .invalid hosts fail at once, in about 0.1 s):
Module[{urls = Internal`Bag[], inFetch = False},
URLFetch;
Internal`InheritedBlock[{URLFetch},
Unprotect[URLFetch];
PrependTo[DownValues[URLFetch], HoldPattern[URLFetch[url_, rest___] /; !inFetch] :>
Block[{inFetch = True}, Internal`StuffBag[urls, url]; URLFetch[url, rest]]];
Quiet[{URLRead["https://example.invalid/a"], URLExecute["https://example.invalid/b"]}]];
Internal`BagPart[urls, All]]
(* {"https://example.invalid/a", "https://example.invalid/b"} *)
The first argument is not always a string (cloud functions pass CloudObject[...]), so the spy matches url_. For
whole request/response logs see WolframDebugging`WithHTTPLog in CloudAndHTTP.md.
Time and randomness:
Block[{Now = DateObject[{2024, 1, 1, 12, 0, 0}, "Instant", "Gregorian", 0.]}, DateString[Now, "ISODateTime"]]
BlockRandom[SeedRandom[42]; RandomInteger[100, 3]] === BlockRandom[SeedRandom[42]; RandomInteger[100, 3]]
(* "2024-01-01T12:00:00"
True *)
Block[{Now = ...}] only affects code that uses Now (not DateObject[], AbsoluteTime[] or Date[]). Do not mock
RandomReal: RandomVariate, RandomChoice and other C code bypass the mock; seed inside BlockRandom instead (it
does not disturb the global generator). Other mocks that need no Unprotect: an UpValue on a fake argument you pass in
(fakeURL /: URLRead[fakeURL, ___] := HTTPResponse[...]), and a prepended SubValues rule for obj[data][prop] calls.
What an override cannot see
Autoload stubs. An unloaded System or paclet function is an OwnValue stub; querying DownValues, Attributes or
Definition does not load it, the first call does, and the package load wipes the rule you prepended. In a fresh
wolframscript kernel (in a long-running MCP kernel the package may be loaded already: then the first element is False
and the mock works):
{MatchQ[OwnValues[JSONTools`ToJSON], {_ :> (_Package`ActivateLoad | Verbatim[Condition][_System`Dump`AutoLoad, _])}],
Internal`InheritedBlock[{JSONTools`ToJSON},
Unprotect[JSONTools`ToJSON];
PrependTo[DownValues[JSONTools`ToJSON], HoldPattern[JSONTools`ToJSON[___]] :> "MOCK"];
JSONTools`ToJSON[{1, 2}]]}
(* {True, "[\n 1,\n 2\n]"} a stub; the REAL function ran, the mock was ignored *)
Evaluating the bare symbol first (JSONTools`ToJSON;) loads the package; after that the same block returns "MOCK".
This is dangerous with side effects: a mocked but unloaded CloudPut wrote a real cloud object. Which symbols are still
stubs differs between a fresh wolframscript kernel, a fresh MCP server and a long-running MCP Local kernel, so always
evaluate the bare symbol first (WolframDebugging`AutoloadStubQ[f], WolframDebugging`EnsureLoaded[f]). For package
symbols that are not stubs yet, Needs the package first. More in PackageLoading.md.
Literal rules and memo values (f[0] = ..., f[n] = ... inside a memoizing definition) are looked up in a hash
table before any pattern rule, wherever you prepend:
ClearAll[lit]; lit[0] = "zero"; lit[x_] := "general";
Internal`InheritedBlock[{lit},
PrependTo[DownValues[lit], HoldPattern[lit[___]] :> "SPY"];
{lit[0], lit[1]}]
Internal`InheritedBlock[{lit},
DownValues[lit] = Replace[DownValues[lit], (* turn literal rules into conditional ones *)
(Verbatim[HoldPattern][lhs_] :> rhs_) /; FreeQ[Unevaluated[lhs], _Pattern | _Blank | _BlankSequence | _BlankNullSequence] :>
(HoldPattern[lhs /; True] :> rhs), {1}];
PrependTo[DownValues[lit], HoldPattern[lit[___]] :> "SPY"];
{lit[0], lit[1]}]
(* {"zero", "SPY"}
{"SPY", "SPY"} *)
To mock a literal call, prepend a literal rule (HoldPattern[lit[0]] :> "MOCK"): it is stored before the old one.
Memo values created inside the block are literal again and are discarded when the block ends.
C code callers and auto-compilation. A prepended rule only sees calls that go through the evaluator. Work done in
C does not: a mock of Plus[1, 2] was ignored by 1 + 2, Plus[1, 2], Total and Sum (numeric Plus never
reaches it), a StringJoin mock by StringRiffle, a RandomReal mock by RandomVariate, a Table mock by Array.
Table with 250 or more elements and Map with 100 or more are compiled automatically and never look at your rule. A
condition with a side effect counts calls without firing:
Module[{n = 0, counts = {}},
Internal`InheritedBlock[{Sin},
Unprotect[Sin];
PrependTo[DownValues[Sin], HoldPattern[Sin[_Real] /; (n++; False)] :> Null]; (* counts calls, never fires *)
Table[Sin[N[k]], {k, 100}]; AppendTo[counts, n];
Table[Sin[N[k]], {k, 1000}]; AppendTo[counts, n];
With[{old = SystemOptions["CompileOptions"]},
WithCleanup[
SetSystemOptions["CompileOptions" -> {"TableCompileLength" -> Infinity, "MapCompileLength" -> Infinity}],
Table[Sin[N[k]], {k, 1000}],
SetSystemOptions[old]]];
AppendTo[counts, n]];
{counts, SystemOptions["CompileOptions" -> "TableCompileLength"]}]
(* {{100, 100, 1100}, {"CompileOptions" -> {"TableCompileLength" -> 250}}}
the 1000-element Table made no visible calls until auto-compilation was switched off; the option is restored *)
Flat heads (StringJoin, Plus, Times, Join, Dot, ...) try a rule on many sub-sequences, so a condition runs
many times per call: the counting condition above, on StringJoin, ran 10 times for one StringJoin["a", "b", "c"].
Use a Boolean guard for them, as in the spy above. Spying on a hot function is slow: a guarded spy on Plus made a loop
of symbolic sums about 18 times slower.
Other limits. A function defined as an OwnValue (f = Function[...]) never reaches DownValues: override its
OwnValue. Calls f[a][b] use SubValues[f]. Listable functions thread before your rule sees the call. 35 System
symbols are Locked (List, True, Symbol, $Version, ...) and cannot be blocked or overridden at all:
{Internal`InheritedBlock[{List}, 1], MemberQ[Attributes[List], Locked]}
(* Internal`InheritedBlock::lockv: -- Message text not found -- (List) ({List})
{Internal`InheritedBlock[{List}, 1], True} *)
Changes that leak out of a block
Attributes set inside a block are restored, except Temporary and Locked, which stay set; and a Locked symbol
can never be blocked or cleared again. Run this only in a throwaway wolframscript kernel, never in a shared MCP kernel:
ClearAll[mySymbol];
Internal`InheritedBlock[{mySymbol}, SetAttributes[mySymbol, {Protected, Flat, Listable, Temporary, Locked}]];
Attributes[mySymbol]
Block[{mySymbol}, 1]
ClearAll[mySymbol]
(* {Locked, Temporary}
Block::lockv: Cannot localize locked symbol mySymbol in local variable specification {mySymbol}.
ClearAll::locked: Symbol mySymbol is locked. *)
ClearAll[f] (and Remove[f]) inside Internal`InheritedBlock[{f}, ...] wipes the outer definitions, and f::tag = ...
inside the block is permanent:
ClearAll[q2, q3]; q2[1] = 1; q3::info = "original";
Internal`InheritedBlock[{q2, q3}, ClearAll[q2]; q2[2] = 2; q3::info = "changed inside"];
{DownValues[q2], q3::info}
(* {{HoldPattern[q2[2]] :> 2}, "changed inside"} q2[1] is gone, the message text changed for good *)
Inside the block use Clear[f] or DownValues[f] = {}, and Messages[f] = Append[Messages[f], HoldPattern[f::tag] :> "text"]
(all restored). Block[{f}, SetOptions[f, "opt" -> 3]] issues SetOptions::optnf (the blocked f has no options)
and still changes the outer options for good. Never ClearAll a System symbol to undo an override: it strips its
attributes (after Unprotect[Table]; ClearAll[Table], Table no longer holds its arguments); restore the saved values
instead.
Overrides that span several tool calls
Within one call, guarantee the cleanup with WithCleanup when you cannot use a block (setup and cleanup also run on
Abort[], Throw, TimeConstrained and MCP time-outs; they cannot be interrupted, so keep them fast):
ClearAll[svc]; svc[x_] := x;
{With[{saved = DownValues[svc]},
WithCleanup[
PrependTo[DownValues[svc], HoldPattern[svc[_]] :> "MOCK"], (* setup *)
{svc[1], TimeConstrained[Pause[5], 0.5, "timed out"]}, (* body *)
DownValues[svc] = saved]], (* cleanup: also runs on Abort, Throw, time-outs *)
svc[1]}
(* {{"MOCK", "timed out"}, 1} *)
Across calls, snapshot everything first and restore it in the call that ends the experiment:
snap = WolframDebugging`SnapshotDefinitions[f] ... WolframDebugging`RestoreDefinitions[f, snap] (gives True
when f matches the snapshot again). Without the helper, save OwnValues, DownValues, UpValues, SubValues,
Options, Attributes and Messages explicitly. Do not use Language`ExtendedDefinition for this: it returns an
empty list for ReadProtected symbols, so there is nothing to restore from:
ClearAll[rp]; rp[x_] := x + 1; SetAttributes[rp, ReadProtected];
{Length[DownValues[rp]], Language`ExtendedDefinition[rp], Length[DownValues[URLFetch]], Language`ExtendedDefinition[URLFetch]}
(* {1, Language`DefinitionList[], 1, Language`DefinitionList[]} *)
An MCP time-out restores scoped overrides (Internal`InheritedBlock, WithCleanup) but not an unscoped
PrependTo[DownValues[f], ...] whose undo line never ran: that rule stays for every later call.
Overrides in a shared MCP kernel
MCP Local runs every session's code in one shared subkernel, and MCP Session runs it inside the MCP server's own kernel: an unscoped change to a System symbol affects every session until the kernel restarts. In fresh MCP Session servers:
Unprotect[Print]; Print[args___] := Nullsilenced every laterPrint; an unscopedMessageoverride hid all later messages.- A prepended
ToStringrule turned every response of the server, from that call on, intoHACKED. - A prepended
WriteLine["stdout", ...]rule made the server go silent for good (it writes its JSON-RPC responses withWriteLine), including the response to that call.
Even a scoped override of a function the evaluator uses for formatting (such as ToString) is active while the MCP
evaluator captures that call's prints and messages: a scoped ToString override turned the call's print line into
During evaluation of In[HACKED]:= HACKED and its message into HACKED: HACKED in MCP Session, and the message into
Power::infy: Infinite expression HACKED encountered. in MCP Local. Record raw data into a bag inside the block and
format it afterwards. Do not rely on $Pre, $Post or $PrePrint in MCP: they have no effect in either method. Wrap
the expression instead. To repair a damaged System symbol, restore the saved values; a fresh session does
not help, because System symbols are shared by all sessions of a kernel.
Watchpoints: who changes this variable?
Internal`SetValueMonitor[x, True] makes every change of x call the "ValueChange" handlers; Stack[_] inside the
handler tells who made the change:
ClearAll[counter, bump, runAll];
counter = 0; bump[] := counter++; runAll[] := (bump[]; counter = 10; bump[]);
Module[{bag = Internal`Bag[]},
Internal`WithLocalSettings[
Internal`SetValueMonitor[counter, True],
Internal`HandlerBlock[{"ValueChange", Internal`StuffBag[bag, {#,
Cases[Stack[_], _[h_Symbol[___]] /; MemberQ[{"Global`", $Context}, Context[h]] :> SymbolName[Unevaluated[h]], {1}]}] &},
StackBegin[StackComplete[runAll[]]]],
Internal`SetValueMonitor[counter, False]]; (* ALWAYS reset: the flag survives ClearAll *)
Internal`BagPart[bag, All]]
(* {{HoldComplete[counter, 0, 1, OwnValues], {"runAll", "bump"}}, {HoldComplete[counter, 1, 10, OwnValues], {"runAll"}},
{HoldComplete[counter, 10, 11, OwnValues], {"runAll", "bump"}}} *)
Same output in MCP Local, MCP Session, wolframscript, CloudEvaluate and on the remote MCP server.
Internal`WithLocalSettings[setup, body, cleanup] (like WithCleanup) resets the flag even after an abort or a
time-out. The event forms:
ClearAll[w];
Module[{bag = Internal`Bag[]},
Internal`WithLocalSettings[
Internal`SetValueMonitor[w, True],
Internal`HandlerBlock[{"ValueChange", Internal`StuffBag[bag, ToString[#, InputForm]] &}, (* strings: see below *)
w = {1, 2}; w[[1]] = 5; AppendTo[w, 3]; Block[{w = 0}, w++]; w =.; w[1] = "def"],
Internal`SetValueMonitor[w, False]];
Internal`BagPart[bag, All]]
(* {"HoldComplete[w, Null, {1, 2}, OwnValues]", "HoldComplete[w, w[[1]], 5, Part]", "HoldComplete[w, {5, 2}, {5, 2, 3}, OwnValues]",
"HoldComplete[w, Block, True]", "HoldComplete[w, Null, 0, OwnValues]", "HoldComplete[w, 0, 1, OwnValues]", "HoldComplete[w, Block, False]",
"HoldComplete[w, OwnValues]", "HoldComplete[w, w[1], \"def\", Removed[\"$$Failure\"], DownValues]"} *)
- Events carry the full old and new values (
HoldComplete[x, old, new, OwnValues]);Partassignments,Unset(HoldComplete[x, OwnValues]),Clear(HoldComplete[x, Clear]), entering and leaving aBlock, and new definitions (DownValues,UpValues,DefaultValuesevents) are reported. AModulevariable with the same name is a different symbol and is not reported. - Convert events to strings before returning them. Definition events contain a special removed-symbol object
(
Removed["$$Failure"]) that cannot be serialized: in MCP Local a result containing one comes back asBinarySerialize::serializefailandOut[n]= $Failed(MCP Session returns it). - The flag survives
ClearAll[x](Internal`GetValueMonitor[x]staysTrue): always reset it in the cleanup. - It works on system variables too (
$ContextPathduringNeeds["CodeParser`"]: 309 events) and costs little until a handler is installed; a tight loop then produced about 700,000 events per second, so count or cap what you store. - The handler's return value is ignored and it runs after the assignment.
WolframDebugging`WatchChanges[{x, y}, expr]records changes with their callers.
Stop at the first bad value: Throw from the handler.
ClearAll[state];
state = 0;
{Module[{tag},
Catch[
Internal`WithLocalSettings[
Internal`SetValueMonitor[state, True],
Internal`HandlerBlock[{"ValueChange", Function[ev,
If[MatchQ[ev, HoldComplete[state, _, new_ /; new > 2, OwnValues]], Throw[ev, tag]]]},
Do[state = k, {k, 5}]; "no bad value"],
Internal`SetValueMonitor[state, False]],
tag]],
state}
(* {HoldComplete[state, 2, 3, OwnValues], 3} *)
Add Stack[_] to the thrown value to see the caller (WolframDebugging`StopWhen[state, # > 2 &, expr] does that). A
Catch[..., _] in the code under test can eat the Throw; then record without throwing as above.
Freeze a variable and report who tries to change it: Internal`ValueChangeVeto[x, True] plus a "VetoableValueChange"
handler that returns False blocks the assignment:
ClearAll[limit, setLimit, configure];
limit = 5; setLimit[n_] := (limit = n); configure[] := setLimit[99];
Module[{bag = Internal`Bag[]},
Internal`WithLocalSettings[
Internal`ValueChangeVeto[limit, True],
Internal`HandlerBlock[{"VetoableValueChange", Function[ev,
If[MatchQ[ev, HoldComplete[limit, ___]],
Internal`StuffBag[bag, {ev, Cases[Stack[_], _[h_Symbol[___]] /; MemberQ[{"Global`", $Context}, Context[h]] :>
SymbolName[Unevaluated[h]], {1}]}]; False, (* False blocks the assignment *)
True]]},
StackBegin[StackComplete[configure[]]]],
Internal`ValueChangeVeto[limit, False]];
{limit, Internal`BagPart[bag, All]}]
(* {5, {{HoldComplete[limit, Null, 99, OwnValues], {"configure", "setLimit"}}}} *)
The second element of a veto event is Null, not the old value. MCP kernels already have a J/Link veto handler; it only
acts on Java objects and composes with yours (return True for everything you do not block).
Other handler probes
All of these are scoped with Internal`HandlerBlock[{"Type", f}, expr] (one type per block; nest blocks for more) and
worked in MCP Local, MCP Session and wolframscript. Internal`Handlers[] lists the handler types.
Symbols created while code runs (ToExpression, Get, Symbol["..."]): typos and context leaks while loading code.
The argument is one list {"name", "context`"}, and the handler runs before the symbol exists:
Module[{log = Internal`Bag[]},
Internal`HandlerBlock[{"NewSymbol", Internal`StuffBag[log, #] &},
ToExpression["newSymA + Global`newSymB; myCtx`newSymC; Module[{tmpq}, tmpq]"]];
Internal`BagPart[log, All]]
(* wolframscript: {{"newSymA", "Global`"}, {"newSymB", "Global`"}, {"newSymC", "myCtx`"}, {"tmpq", "Global`"}}
MCP Local and MCP Session: "Sessions`<id>`" instead of "Global`" for newSymA and tmpq *)
Symbols typed in an MCP call are created when their input (a line or a multi-line expression) is parsed, before any
handler in it runs, so this only sees run-time symbols (WolframDebugging`NewSymbolsDuring[expr]).
Files an evaluation writes (notification only: returning False does not prevent the write; CopyFile, CreateFile
and ExportString are not reported):
Module[{log = Internal`Bag[], file = FileNameJoin[{$TemporaryDirectory, "openwrite-demo.txt"}]},
Internal`HandlerBlock[{"Wolfram.File.OpenWrite", Internal`StuffBag[log, #] &},
Export[file, "x", "Text"]; Put[1, file]; WriteString[file, "y"]; Close[file]; DeleteFile[file]];
Replace[Internal`BagPart[log, All], HoldComplete[h_, f_String] :> {h, FileNameTake[f]}, {1}]]
(* {{OpenWrite, "openwrite-demo.txt"}, {Put, "openwrite-demo.txt"}, {WriteString, "openwrite-demo.txt"}} *)
(WolframDebugging`FileWritesDuring[expr].) Failing Assert calls, although Assert is Off by default:
ClearAll[check]; check[x_] := (Assert[x > 0, "x must be positive"]; Sqrt[x]);
Module[{bag = Internal`Bag[]},
{Internal`HandlerBlock[{"Assertions", Internal`StuffBag[bag, #] &}, check[-1] + check[4]], Internal`BagPart[bag, All]}]
(* {2 + I, {HoldComplete[Assert[-1 > 0, "x must be positive"]]}} *)
While an "Assertions" handler is installed, every Assert evaluates its test (normally skipped while Assert is Off),
so side effects in tests run. Only failing assertions reach the handler (WolframDebugging`FailedAssertions[expr]).
Capture Print and Echo output as data, without printing:
ClearAll[noisy]; noisy[] := (Print["step 1"]; Echo[2, "value:"]; 42);
Module[{bag = Internal`Bag[]},
{Block[{Print = Function[Null, Internal`StuffBag[bag, HoldComplete[##]], HoldAllComplete]}, noisy[]],
Internal`BagPart[bag, All]}]
(* {42, {HoldComplete["step 1"], HoldComplete[">> ", "value:", " ", Unevaluated[2]]}} *)
Print capture works in every environment, but Echo goes through Print only where $Notebooks is False:
CloudEvaluate, deployed APIs, the remote MCP server and code under UsingFrontEnd gave {42, {HoldComplete["step 1"]}}.
There Echo prints a cell with CellPrint, so block CellPrint too (WolframDebugging`CapturePrints does).
A "Wolfram.System.Print.Veto" handler that returns False suppresses prints only in MCP Local and wolframscript; MCP
Session (and the remote MCP server) capture the print before your handler runs:
Internal`HandlerBlock[{"Wolfram.System.Print.Veto", False &}, Print["vetoed print"]; "done"]
(* MCP Local, wolframscript: "done" MCP Session: During evaluation of In[1]:= vetoed print / Out[1]= "done" *)
EvaluationData[expr]["OutputLog"] records prints as strings but still lets them print; in MCP Session and on the
remote MCP server it stays {}, because their evaluator takes the print first
(WolframDebugging`CapturePrints[expr, max] and WolframDebugging`CaptureEvaluation[expr]).
Package loading
How to find out what an evaluation loads (files, contexts, autoloads, .mx files), which copy of a package is in use,
and why edits or new definitions do not take effect. Read it for "my change has no effect", "symbol is undefined after
loading", "it works in a fresh kernel but not here" (or the reverse), and before overriding a function that may not be
loaded yet. Behavior was checked with Wolfram 15.0 in MCP Local and wolframscript (see Environments.md).
Which tool for which question
| question | first choice | section |
|---|---|---|
what did this evaluation load (including .mx)? | $LoadedFiles before/after | What did an evaluation load? |
| which files/contexts, nested, and who triggered them? | "GetFileEvent" handler (+ Stack inside it) | The GetFileEvent handler |
| which autoload stubs fired? | GeneralUtilities`TraceLoading; WolframDebugging`LoadTrace[expr] | Autoloads: TraceLoading |
is sym still an unloaded stub? | OwnValues[sym]; WolframDebugging`AutoloadStubQ[sym] | Autoload stubs |
| which copy of a package is used, and is it current? | FindFile, PacletFind[<|"Context" -> ctx|>], $LoadedFiles; WolframDebugging`ContextSourceInfo["Ctx`"] | Where does a context's code come from? |
| my edit has no effect | the checklist | "My edits don't take effect" |
f stays unevaluated right after loading its package | Names["*`f"], parse-before-run | Shadowed symbols |
| typos and leaked symbols in a package | "NewSymbol" handler while loading | Symbols created while loading |
Helpers are in scripts/WolframDebugging.wl (load it with Get in its own call, call them fully qualified; options and
outputs: HelperFunctions.md). Everything below works without them.
First-time effects need a fresh kernel
Autoloads, file loads and their messages happen once per kernel. The MCP kernels (MCP Local and MCP Session) are long-running and have hundreds of packages loaded already (CloudObject, CodeParser, GeneralUtilities, MUnit, ...), so a loading problem often does not reproduce there, and the probes below show less or nothing. Reproduce loading problems in a fresh kernel:
timeout -s KILL 300 wolframscript -f probe.wls < /dev/null > out.txt 2>&1
The MCP servers also start with -noinit (see "Startup differences" below).
What did an evaluation load?
$LoadedFiles is an append-only log of every file the kernel loaded with Get (.wl, .m, .mx, also data paclets'
.mx files such as ElementData.mx; not files read with Import), with duplicates, in load order:
Drop[$LoadedFiles, before] is exactly what an evaluation loaded. A "GetFileEvent" handler shows the Gets as they
happen, with nesting:
Module[{before = Length[$LoadedFiles], log = Internal`Bag[], res},
res = Internal`HandlerBlock[{"GetFileEvent", Internal`StuffBag[log, #] &}, ArrayReduce[Total, {{1, 2}, {3, 4}}, 1]];
{res, Internal`BagPart[log, All], FileNameTake /@ Drop[$LoadedFiles, before]}]
wolframscript (fresh kernel):
{{4, 6},
{HoldComplete["NumericArrayUtilities`", Identity, First],
HoldComplete[".../Components/NumericArrayUtilities/Kernel/Common.m", Identity, First],
HoldComplete["GeneralUtilities`", Identity, First], HoldComplete["GeneralUtilitiesLoader`", Identity, First],
HoldComplete["GeneralUtilitiesLoader`", Identity, Last], HoldComplete["GeneralUtilities`", Identity, Last],
HoldComplete["Developer`", Identity, First], HoldComplete["Developer`", Identity, Last],
HoldComplete[".../Components/NumericArrayUtilities/Kernel/Common.m", Identity, Last],
HoldComplete["NumericArrayUtilities`", Identity, Last]},
{"init.m", "Common.m", "GeneralUtilities.m", "GeneralUtilitiesLoader.m", "GeneralUtilities.mx", "Developer.m", "Descriptive.mx", "RobustStatistics.mx"}}
fresh MCP Local or MCP Session server (GeneralUtilities already loaded): the same without the GeneralUtilities events and files
MCP evaluator once earlier calls have loaded everything: {{4, 6}, {}, {}}
The .mx files (GeneralUtilities.mx, Descriptive.mx, RobustStatistics.mx) appear only in $LoadedFiles: the
handler does not see them. MCP kernels have hundreds to thousands of entries (about 600 in a fresh MCP Session server,
nearly 2000 in a long-running MCP Local; in both methods every switch between evaluator sessions adds that session's
saved .mx state file), so always filter it (Select[..., StringStartsQ[#, root] &], DeleteDuplicates, Take) and
never return it whole.
The "GetFileEvent" handler
Internal`HandlerBlock[{"GetFileEvent", f}, expr] calls f before and after every Get (also the Gets done by
Needs, by paclet autoload stubs and by files being loaded). The argument is HoldComplete[arg, Identity, First] when
reading starts and HoldComplete[arg, Identity, Last] when it ends; nested loads nest. arg is the literal first
argument of that Get: a context, an absolute or relative path, a stream. Resolve it with FindFile[arg] inside the
handler (later the current directory or $Path may differ). The second element was Identity in every load path
tested; match it with _.
The examples below use a few small files in a directory demoDir (demoDir = "/abs/path/to/demo";):
LoadDemo.wl (a package that does Get[FileNameJoin[{DirectoryName[$InputFileName], "LoadDemoSub.wl"}]]),
LoadAbort.wl (just Abort[];), ShadowDemo.wl (BeginPackage["ShadowDemo`"] exporting shFn[x_] := x^2),
TypoDemo.wl and DeclDemo.wl (shown in their sections), and two paclet directories ver1/VerDemo, ver2/VerDemo
(versions 1.0.0 and 2.0.0 of a paclet with context VerDemo` , whose verFn[] returns "v1" or "v2").
Module[{log = Internal`Bag[]},
Internal`HandlerBlock[{"GetFileEvent", Internal`StuffBag[log, #] &}, Get[FileNameJoin[{demoDir, "LoadDemo.wl"}]]];
Replace[Internal`BagPart[log, All], HoldComplete[f_String, w_, fl_] :> {FileNameTake[f], w, fl}, {1}]]
(* {{"LoadDemo.wl", Identity, First}, {"LoadDemoSub.wl", Identity, First}, {"LoadDemoSub.wl", Identity, Last}, {"LoadDemo.wl", Identity, Last}} *)
A file that aborts (or throws) produces First without Last, so depth counters must tolerate unmatched events:
Module[{log = Internal`Bag[]},
CheckAbort[Internal`HandlerBlock[{"GetFileEvent", Internal`StuffBag[log, #] &},
Get[FileNameJoin[{demoDir, "LoadAbort.wl"}]]], "aborted"];
Replace[Internal`BagPart[log, All], HoldComplete[f_String, w_, fl_] :> {FileNameTake[f], w, fl}, {1}]]
(* {{"LoadAbort.wl", Identity, First}} *)
It does not fire for a missing file (Get::noopen), Needs of a context that is already loaded, kernel autoloads
(they read SystemResources/*.mx), Get of an .mx file, or PacletDirectoryLoad:
Module[{count},
count = Function[expr, Module[{n = 0}, Internal`HandlerBlock[{"GetFileEvent", n++ &}, expr]; n], HoldAll];
{count[Quiet[Get["/nonexistent/x.wl"]]], count[Needs["CodeParser`"]], count[Needs["CodeParser`"]],
count[Adjugate[{{1, 2}, {3, 4}}]], Select[$LoadedFiles, StringContainsQ["Adjugate"]]}]
(* wolframscript: {0, 96, 0, 0, {".../SystemFiles/Kernel/SystemResources/64Bit/LinearAlgebra/Adjugate.mx"}}
MCP Local: {0, 0, 0, 0, {...Adjugate.mx}} -- CodeParser was already loaded there *)
(Checked separately in wolframscript: Get of a DumpSaved .mx file and PacletDirectoryLoad also give 0 events.)
MCP servers already have MUnit's handler installed (Internal`Handlers["GetFileEvent"] gives
"GetFileEvent" -> {MUnit`Package`MUnitGetFileHandler}; a fresh wolframscript has none).
Internal`HandlerBlock adds yours on top and removes it afterwards. Never use Internal`AddHandler for this in an
MCP kernel.
Who triggered a load?
Take the stack inside the handler at the first First event. The trigger is the last frame before the first
Package`ActivateLoad, Get, Needs or System`Dump`AutoLoad frame. Record data instead of printing it (a package
load can fire hundreds of events), and convert frames to strings without evaluating them (15.0 frames are
HoldCompleteForm[...], older versions HoldForm[...]; _[e_] matches both):
Module[{st = None},
Internal`HandlerBlock[{"GetFileEvent", Function[ev, If[st === None && ev[[3]] === First,
st = {ev[[1]], Replace[Stack[_], _[e_] :> ToString[Unevaluated[e], InputForm, TotalWidth -> 70], {1}]}]]},
StackBegin[Length[Diff[{1, 2}, {1, 3}]]]];
st]
(* {"Wolfram`DiffTools`", {"Length[Diff[{1, 2}, {1, 3}]]", "Diff[{1, 2}, {1, 3}]",
"Package`ActivateLoad[Diff, {<<15>>}, \"Wolfram`DiffTools`\", {<<2>>}]", "AbortProtect[Get[\"Wolfram`DiffTools`\"]]",
"Get[\"Wolfram`DiffTools`\"]", <3 frames of the handler itself>}} *)
To catch one particular package, test the event in the handler, e.g. MatchQ[ev, HoldComplete["DataResource`", _, First]].
Wrap the expression in StackBegin (drops the frames of the environment) and add StackComplete if you need to see your
own functions (without it a call is replaced on the stack by its right-hand side; see MessagesAndStacks.md).
Autoloads: GeneralUtilities`TraceLoading
GeneralUtilities`TraceLoading[expr] is available in every kernel without Needs (call it fully qualified). Its usage
text says it reports "all file and MX load events"; in 15.0 it reports only
- autoload stubs that fire:
"Sym" -> "Ctx`"(the stub ofSymloadedCtx`), and Getof.mxfiles given as a string path,
not ordinary .wl/.m loads (its file handler is not defined). It prints, and only the first time a stub fires:
GeneralUtilities`TraceLoading[GroupOrder[SymmetricGroup[3]]]
(* wolframscript -f: /path/to/file/being/read.wl:1: InputForm[GroupOrder -> GroupTheory`PermutationGroups`]
MCP Local: During evaluation of In[2]:= :2: "GroupOrder" -> "GroupTheory`PermutationGroups`"
result: 6; run it again in the same kernel: prints nothing *)
The prefix is $InputFileName:$Line at the time the stub fired, not necessarily the code that triggered it (in MCP Local
the file name is empty and the number is the In[n] line). Copied out of a notebook as plain text, the same printed row
looks like ""*":"*1*": "*InputForm["CloudPut" -> "CloudObjectLoader`"] (not checked in a notebook here). Data
instead of printed lines: the undocumented second argument is a callback, called as callback[Hold[sym] -> "Ctx`", Symbol]
for an autoload and callback[mxPath, Begin]/callback[mxPath, End] around an .mx load. Block[{Print}, ...] silences the printing (and any Print of your code):
Module[{ev = Internal`Bag[], res},
res = Block[{Print}, GeneralUtilities`TraceLoading[RegionEqual[Disk[], Disk[{1, 1}]], Internal`StuffBag[ev, {##}] &]];
{res, Length[Internal`BagPart[ev, All]], Take[Internal`BagPart[ev, All], UpTo[2]]}]
(* {False, 6, {{Hold[RegionEqual] -> "Regions`RegionRelations`RegionEqual`", Symbol},
{Hold[Region`RegionRelationsDump`regionAccessor] -> "Regions`RegionRelations`RegionRelationsLibrary`", Symbol}}}
(fresh kernel; {False, 0, {}} once RegionEqual is loaded, as in MCP Local by now) *)
A package loaded from source is invisible to it (the "GetFileEvent" handler above sees the same Get):
GeneralUtilities`TraceLoading[Get[FileNameJoin[{demoDir, "LoadDemo.wl"}]]; LoadDemo`ldFn[1]]
(* 3 -- nothing printed *)
Helper: WolframDebugging`LoadTrace[expr] combines autoload hooks, the "GetFileEvent" handler and the $LoadedFiles
difference into one bounded result (depth, kind, target, trigger, new files).
Autoload stubs
Most System functions implemented in packages start as stubs: an OwnValue
sym :> Package`ActivateLoad[sym, {group}, "LoaderContext`", opts] (paclet Kernel extensions) or
sym :> System`Dump`AutoLoad[Hold[sym], Hold[group], "Ctx`"] /; System`Dump`TestLoad (kernel .mx files). The first
evaluation of the symbol loads the whole package and replaces the stub. Inspecting does not load it; evaluating does:
stubQ = Function[s, ! FreeQ[Quiet[OwnValues[s]], Package`ActivateLoad | System`Dump`AutoLoad], HoldAllComplete];
{Attributes[GroupOrder]; DownValues[GroupOrder]; ToString[Definition[GroupOrder]]; Context[GroupOrder]; stubQ[GroupOrder],
GroupOrder; stubQ[GroupOrder],
Options[RegionEqual]; stubQ[RegionEqual],
Head[Diff]; stubQ[Diff]}
(* {True, False, False, False} (fresh kernel: wolframscript, or a freshly started MCP server) *)
So: Attributes, DownValues, Definition, Context and the SymbolDefinition tool leave the stub alone; evaluating the
bare symbol, Options[sym], Head[sym] or any call loads it. Consequences:
- Inspect a stub's definitions only after loading it (
sym;), seeDefinitionsAndSource.md. - Defining on a stub fails:
Unprotect[Diff3]; Diff3["mock"] := "MOCK"evaluates the head, the load re-protects the symbol, and you getSetDelayed::write: Tag Diff3 in Diff3[mock] is Protected.; the mock is never installed. Overrides insideInternal`InheritedBlockfail on stubs too (aGroupOrder[_] := "MOCK"there was ignored, and the package loaded inside the block was rolled back to the stub when it exited). Load first, then override (OverridesAndWatchpoints.md). - Helpers:
WolframDebugging`AutoloadStubQ[sym](does not load),WolframDebugging`EnsureLoaded[sym](loads, then True when no stub remains).
DeclarePackage stubs are different: they have no OwnValues, only the attribute Stub, and load the package when the
symbol name is parsed, before anything evaluates. DeclDemo.wl is
BeginPackage["DeclDemo`"]; declFn[x_] := {"declFn", x}; EndPackage[]; (one statement per line):
Block[{$Path = Prepend[$Path, demoDir]},
DeclarePackage["DeclDemo`", {"declFn"}];
{MemberQ[$Packages, "DeclDemo`"],
ToExpression["DeclDemo`declFn", InputForm, Hold],
MemberQ[$Packages, "DeclDemo`"]}]
(* {False, Hold[declFn], True} -- parsing the name inside Hold loaded the package (MCP Local: Hold[DeclDemo`declFn]) *)
Where does a context's code come from?
With[{ctx = "CodeParser`"},
{FindFile[ctx], {#["Version"], #["Location"]} & /@ PacletFind[<|"Context" -> ctx|>], MemberQ[$Packages, ctx],
Length[Select[$LoadedFiles, StringContainsQ["/CodeParser/"]]]}]
(* wolframscript: {".../SystemFiles/Components/CodeParser/Kernel/CodeParser.wl", {{"1.13", ".../SystemFiles/Components/CodeParser"}}, False, 0}
MCP Local: {..., {{"1.13", ...}}, True, 21} *)
FindFile[ctx]and the firstPacletFindentry are what the nextGet/Needswould load;$LoadedFilesis what was loaded. They differ after a paclet update, aPacletDirectoryLoador an.mxbuild.$Packagesis the listNeedschecks, not a list of loaded packages: loader contexts are registered before anything loads, and a package loaded from.mxat startup can be missing from it (the firstNeedsthen loads it again: the GeneralUtilities events in the first example):
{MemberQ[$Packages, "GeneralUtilities`"], AnyTrue[$LoadedFiles, StringEndsQ["GeneralUtilities.mx"]],
MemberQ[$Packages, "CloudObjectLoader`"], MatchQ[OwnValues[CloudPut], {_ :> _Package`ActivateLoad}]}
(* wolframscript: {False, True, True, True} -- GeneralUtilities loaded but not in $Packages; CloudObjectLoader` listed while CloudPut is still a stub
MCP Local: {True, True, True, False} *)
Which version wins
Among paclets, the highest version wins, whatever the PacletDirectoryLoad order; with equal versions the directory
loaded first wins. Needs does nothing once the context is in $Packages, so only Get loads the newly preferred copy
(wolframscript; PacletDirectoryLoad changes the kernel's paclet configuration, so do not try this in a shared MCP
kernel):
PacletDirectoryLoad[FileNameJoin[{demoDir, "ver1"}]]; Needs["VerDemo`"];
PacletDirectoryLoad[FileNameJoin[{demoDir, "ver2"}]];
r1 = {VerDemo`verFn[], FileNameTake[FindFile["VerDemo`"], -4], #["Version"] & /@ PacletFind["VerDemo"]};
Needs["VerDemo`"]; r2 = VerDemo`verFn[];
Get["VerDemo`"]; r3 = VerDemo`verFn[];
{r1, r2, r3}
(* {{"v1", "ver2/VerDemo/Kernel/VerDemo.wl", {"2.0.0", "1.0.0"}}, "v1", "v2"} *)
(Loading ver2 first and ver1 second gives the same FindFile result; two directories with the same version: the
first one loaded is used.) A development checkout added with PacletDirectoryLoad is therefore ignored when an
installed copy has a higher version, and updated system paclets in the user paclet repository shadow the copies in the
installation (see DefinitionsAndSource.md). Helper: WolframDebugging`ContextSourceInfo["Ctx`"] (candidates, loaded
files, other loaded copies, stale .mx, files edited since the kernel started).
"My edits don't take effect"
Check in this order:
Needsis a no-op once the context is in$Packages(above): useGet["Ctx`"]orGet[file].- Reloading keeps old rules. A second
Getadds and replaces rules but never removes deleted ones (withoutProtectbelow, the reload gives"v2"for integers and still"v1 string"for strings), and fails onProtected symbols. Clear first:
Module[{file = FileNameJoin[{$TemporaryDirectory, "ReloadDemo.wl"}], write, r},
write = Export[file, StringRiffle[Join[{"BeginPackage[\"ReloadDemo`\"]", "rdFn", "Begin[\"`Private`\"]"}, #,
{"End[]", "Protect[rdFn]", "EndPackage[]"}], "\n"], "Text"] &;
write[{"rdFn[x_Integer] := \"v1\"", "rdFn[x_String] := \"v1 string\""}]; Get[file];
write[{"rdFn[x_Integer] := \"v2\""}];
r = Check[Get[file], "messages"]; (* SetDelayed::write: Tag rdFn ... is Protected *)
{r, ReloadDemo`rdFn[1], ReloadDemo`rdFn["a"],
Unprotect["ReloadDemo`*"]; ClearAll["ReloadDemo`*", "ReloadDemo`*`*"]; Get[file];
{ReloadDemo`rdFn[1], ReloadDemo`rdFn["a"]}}]
(* SetDelayed::write: Tag rdFn in rdFn[x_Integer] is Protected.
{"messages", "v1", "v1 string", {"v2", rdFn["a"]}} -- nothing changed until the symbols were cleared *)
The reload recipe is Unprotect["Ctx`*"]; ClearAll["Ctx`*", "Ctx`*`*"]; Get["Ctx`"] (memo values and caches go too).
In MCP Local, files can only be written below $TemporaryDirectory.
3. Another copy wins: a higher-version installed paclet, or the first of two equal versions (above). Compare
FindFile, PacletFind[<|"Context" -> ctx|>] and $LoadedFiles.
4. A compiled .mx build is loaded instead of the source. Some paclet loaders (Chatbook's, AgentTools') load a
64Bit/*.mx build when it exists; source edits are then ignored until the .mx is rebuilt or removed. FindFile
still names the .wl loader (for Chatbook: Source/Chatbook/Chatbook.wl); only $LoadedFiles shows the .mx:
With[{root = First[PacletFind[<|"Context" -> "Wolfram`Chatbook`"|>]]["Location"]},
DeleteDuplicates @ Select[$LoadedFiles, StringStartsQ[#, root] && StringEndsQ[#, ".mx"] &]]
(* {"~/.Wolfram/Paclets/Repository/Wolfram__Chatbook-2.7.0/Source/Chatbook/64Bit/Chatbook.mx"} *)
A stale build directory inside a checkout (a built paclet layout that a test runner prefers) can have the same effect (not checked here). 5. The file was edited after the kernel loaded it. MCP servers and their evaluator kernels load their packages at startup; editing the source changes nothing in them until the server restarts (you cannot restart it from inside an evaluator call; ask the user, or test in wolframscript). Files of a package modified after this kernel started:
With[{root = First[PacletFind[<|"Context" -> "Wolfram`AgentTools`"|>]]["Location"]},
{root, DeleteDuplicates @ Select[$LoadedFiles,
StringStartsQ[#, root] && AbsoluteTime[FileDate[#]] > AbsoluteTime[] - SessionTime[] &]}]
(* MCP Local (development checkout loaded by the server):
{"~/AgentTools", {"~/AgentTools/Kernel/AgentSkills.wl", "~/AgentTools/Kernel/AgentToolsObject.wl", ...}}
wolframscript (fresh kernel, installed copy): {"~/.Wolfram/Paclets/Repository/Wolfram__AgentTools-2.2.0", {}} *)
It also lists files that were edited and then loaded later in the session (they are current); for a package loaded at startup, every hit means the running code is older than the file. 6. Your call hits a different symbol (shadowing, next section).
Shadowed symbols and parse-before-run
Each input (one top-level expression: a line, or a multi-line expression, of an MCP tool call or of a -f file; a whole
-code string) is parsed just before it runs, so a name used in the same input as the Get that defines it is created
in the current context first:
Get[FileNameJoin[{demoDir, "ShadowDemo.wl"}]]; {shFn[3], Context[shFn], ShadowDemo`shFn[3]}
(* wolframscript: {Global`shFn[3], "Global`", 9} MCP evaluator: {Sessions`<id>`shFn[3], "Sessions`<id>`", 9}
(no General::shdw message in either) *)
{Names["*`shFn"], Remove["Global`shFn"]; Names["*`shFn"]}
(* {{"Global`shFn", "shFn"}, {"shFn"}} -- two symbols before, only ShadowDemo`shFn after *)
- Put
Get/Needson its own line (or in its own tool call), and call package functions by their full names. Short names work from the next input on (details inEnvironments.md). Names["*`name"]lists every context with that name;Remove["Global`name"]deletes the stray copy (expressions parsed earlier still hold the removed symbol).General::shdwis not always issued, so do not wait for it.- Unevaluated
f[...]right after loading: also checkUnevaluatedCalls.md.
Symbols created while loading (typos, leaks)
A "NewSymbol" handler receives {"name", "Context`"} for every symbol created while the code is read: typos show up
as new names next to the intended ones, leaks as names outside the package context. TypoDemo.wl:
tdLeaked = 1; before BeginPackage["TypoDemo`"], then tdFn[x_] := tdHelpr[x]; tdHelper[x_] := x + 1; in the
private context:
Module[{bag = Internal`Bag[]},
Internal`HandlerBlock[{"NewSymbol", Internal`StuffBag[bag, #] &}, Get[FileNameJoin[{demoDir, "TypoDemo.wl"}]]];
Internal`BagPart[bag, All]]
(* wolframscript: {{"tdLeaked", "Global`"}, {"tdFn", "TypoDemo`"}, {"x", "TypoDemo`Private`"}, {"tdHelpr", "TypoDemo`Private`"}, {"tdHelper", "TypoDemo`Private`"}}
MCP evaluator: the same except {"tdLeaked", "Sessions`<id>`"} -- files loaded with Get use the session context there *)
Only symbols that did not exist yet are reported (load into a fresh kernel for a complete list). Filter with
Select[list, ! StringStartsQ[#[[2]], "TypoDemo`"] &] for leaks. Helper: WolframDebugging`NewSymbolsDuring[expr].
Startup differences: -noinit
MCP servers (and the TestReport MCP tool's kernel) start with -noinit: no init.m files, so no $Path additions,
SetOptions, Off[...] or packages loaded there. Code that works in a notebook or in wolframscript but not in MCP often
depends on an init file:
{MemberQ[$CommandLine, "-noinit"],
Select[$LoadedFiles, StringStartsQ[#, $UserBaseDirectory | $BaseDirectory] && StringEndsQ[#, "/Kernel/init.m"] &]}
(* wolframscript: {False, {"/usr/share/Wolfram/Kernel/init.m", "~/.Wolfram/Kernel/init.m"}}
MCP Local: {True, {}} *)
Reproduce MCP startup with wolfram -noinit -script file.wl; more startup differences in HeadlessAndCrashes.md.
Gotchas
- First-time effects (autoloads,
GetFileEvent, TraceLoading output) happen once per kernel; MCP kernels have most packages loaded already. Use a fresh wolframscript. $LoadedFilesis the ground truth, including.mxfiles that the"GetFileEvent"handler misses; filter it, it is long."GetFileEvent"argis unresolved;FirstwithoutLastwhen a file aborts; nothing for.mx, kernel autoloads, missing files,PacletDirectoryLoadorNeedsof a loaded context.- TraceLoading reports autoloads and string-path
.mxloads only, prints, and is silent the second time. Needsis a no-op for a context in$Packages;$Packagesmembership does not mean loaded.- Highest version wins over a
PacletDirectoryLoaded checkout; a loader may prefer a stale.mx. - Re-
Getkeeps deleted rules and fails on protected symbols:Unprotect+ClearAllthe contexts first. - Load before inspecting or overriding a stub;
DeclarePackagestubs load when the name is parsed. Get/Needson its own line (or in its own call); full names for package symbols.
Parallel subkernels and asynchronous tasks
Debugging ParallelMap/ParallelTable/ParallelEvaluate (definitions missing on subkernels, output and messages that
the master cannot see, aborts, crashes, leftover kernels) and asynchronous code (SessionSubmit, ScheduledTask,
URLSubmit, LocalSubmit) whose bodies and handlers run inside other evaluations. Read it when parallel results are
wrong or slow, or when a task or handler misbehaves. Behavior was checked with Wolfram 15.0.
Where subkernels exist
| environment | LaunchKernels | what Parallel* does |
|---|---|---|
wolframscript, wolfram -script | works (5 to 8 s per kernel) | runs on subkernels |
| MCP Session | works; kernels stay alive across tool calls | runs on subkernels |
| MCP Local | fails in protected mode (no process is started) | evaluates sequentially in the master |
| CloudEvaluate, deployed API, remote MCP server | returns {} | evaluates sequentially in the master |
WithCleanup[
LaunchKernels[1];
<|"Kernels" -> Length[Kernels[]], "KernelIDs" -> ParallelTable[$KernelID, {3}]|>,
CloseKernels[]]
(* wolframscript: <|"Kernels" -> 1, "KernelIDs" -> {1, 1, 1}|>
MCP Local: LocalSubKernelLaunch::somefail, KernelObject::giveup, ParallelTable::nopar, then
<|"Kernels" -> 0, "KernelIDs" -> {0, 0, 0}|> *)
$KernelIDis 0 in the master: a 0 inside mapped code means the item ran in the master.- Without kernels every
ParallelMap/ParallelTable/... call issues its own::noparmessage and evaluates in the master;ParallelEvaluate[expr]returns{}without a message and does not evaluateexpr. - Debug parallel code in wolframscript or an MCP Session server. Launch one kernel and close it in the same evaluation:
WithCleanup[LaunchKernels[1]; ..., CloseKernels[]]. A bareParallelMaplaunches the default number of kernels itself, and in MCP Session those kernels stay alive for the lifetime of the server (about 300 MB each). It does so only once per kernel: after anyLaunchKernelsorCloseKernels, a laterParallel*call without kernels runs sequentially with::nopar. - Never return
Kernels[], aKernelObjector$ConfiguredKernelsas output: aKernelObjectis about 6 KB inInputForm,$ConfiguredKernelsabout 20 KB. UseLength[Kernels[]].
Definitions missing on the subkernel
The most common parallel bug, and usually an invisible one. The subkernel does not have the definition of f, so it
returns f[x] unevaluated. The master then evaluates the returned f[x]: the result looks right but all the work
ran in the master, and it is wrong if the master's state differs from the subkernel's. Detect it by holding the
result on the subkernel:
pkgDemo`g[x_] := x^2 + 1000;
WithCleanup[
LaunchKernels[1];
{ParallelMap[pkgDemo`g, {1, 2}], (* looks right ... *)
ParallelMap[Hold[Evaluate[pkgDemo`g[#]]] &, {1, 2}], (* ... but the subkernel returned it unevaluated *)
ParallelEvaluate[{$KernelID, Length[DownValues[pkgDemo`g]]}, DistributedContexts -> None],
DistributeDefinitions["pkgDemo`"];
ParallelMap[Hold[Evaluate[pkgDemo`g[#]]] &, {1, 2}]}, (* fixed *)
CloseKernels[]]
(* wolframscript and MCP Session:
{{1001, 1004}, {Hold[pkgDemo`g[1]], Hold[pkgDemo`g[2]]}, {{1, 0}}, {Hold[1001], Hold[1004]}}
MCP Local (no subkernels, all in the master): {{1001, 1004}, {Hold[1001], Hold[1004]}, {}, {Hold[1001], Hold[1004]}} *)
Hold[f[x]]instead ofHold[value](orToString[f[#], InputForm] &returning"f[1]") means thatfis not defined on the subkernel.- Pass
DistributedContexts -> Noneto inspection probes: otherwise the probe itself distributes the definitions and hides the bug it is looking for. - Only symbols whose context starts with
$DistributedContexts(by default$Context) are distributed automatically. Not distributed: symbols of package contexts, explicitGlobal`symbols in MCP Session (whose$ContextisSessions`<id>`), symbols that the code reaches only through strings (ToExpression,Symbol), and ReadProtected definitions.$DistributedDefinitionslists what was sent. - Fixes:
DistributeDefinitions[f](also sends the definitionsfdepends on),DistributeDefinitions["Pkg`"], or load the package on the subkernels (next section). - The subkernel's
$ContextisGlobal`, also when the master runs inSessions`<id>`:ToExpressionandSymbolon a subkernel createGlobal`symbols. - Helper:
WolframDebugging`ParallelCapture[f, list]reports"RanInMaster"and"MasterOnlyHeads"(functions left unevaluated on a subkernel but defined in the master); seeHelperFunctions.md.
ReadProtected (MX-built) packages
DistributeDefinitions silently sends nothing for a ReadProtected symbol (MX builds of paclets often make all package
symbols ReadProtected):
rpDemo`h[x_] := x^3; SetAttributes[rpDemo`h, ReadProtected];
WithCleanup[
LaunchKernels[1];
{DistributeDefinitions[rpDemo`h], DistributeDefinitions["rpDemo`"],
ParallelMap[Hold[Evaluate[rpDemo`h[#]]] &, {2}]},
CloseKernels[]]
(* wolframscript: {{}, {"rpDemo`"}, {Hold[rpDemo`h[2]]}} -- no message *)
Load such code on the subkernels instead. Subkernels have their own $Path (changes to the master's $Path are not
copied), so ParallelNeeds alone fails. With ParDemo.wl in the directory dir (a package whose sq is
ReadProtected) loaded in the master:
WithCleanup[
LaunchKernels[1];
{ParallelNeeds["ParDemo`"]; ParallelMap[Hold[Evaluate[ParDemo`sq[#]]] &, {3}],
With[{d = dir}, ParallelEvaluate[PrependTo[$Path, d]]]; ParallelNeeds["ParDemo`"];
ParallelMap[Hold[Evaluate[ParDemo`sq[#]]] &, {3}]},
CloseKernels[]]
(* From kernel 1 (Local (1)): Get::noopen: Cannot open ParDemo`.
From kernel 1 (Local (1)): Needs::nocont: Context ParDemo` was not created when Needs was evaluated.
{{Hold[sq[3]]}, {Hold[9]}} *)
ParallelEvaluate[Get[FileNameJoin[{dir, "ParDemo.wl"}]]] also works ({Hold[9]}). For a paclet:
ParallelEvaluate[PacletDirectoryLoad[dir]; Needs["Ctx`"]].
Messages and Print output from subkernels
Subkernel messages and Print output are re-printed by the master as plain text (From kernel 1 (Local (1)): followed
by the 2-D message text). The master's Check, EvaluationData, $MessageList, message handlers, Quiet and Off
neither see nor affect them:
WithCleanup[
LaunchKernels[1];
Lookup[EvaluationData[Check[ParallelMap[1/# &, {0, 1}], "check-fired"]], {"Result", "MessagesText", "OutputLog"}],
CloseKernels[]]
(* wolframscript: {{ComplexInfinity, 1}, {}, {"From kernel 1 (Local (1)):", " 1\nPower::infy: Infinite expression - encountered.\n 0"}}
MCP Session: {{ComplexInfinity, 1}, {}, {}} (the relayed text is shown in the tool output)
MCP Local (no subkernels): {"check-fired", {"ParallelMap::nopar : ...", "...Power::infy..."}, {}} *)
Checkdid not fire andMessagesTextis empty: the message is only Print output in the master.Quiet[ParallelMap[1/# &, {0}]]still shows the relayed message;ParallelMap[Quiet[1/#] &, {0}]andParallelEvaluate[Off[Power::infy]]suppress it. PutQuiet,Offand handlers inside the parallel code.- In MCP Session the relayed lines count toward the tool's limit of about 10 printed outputs and messages per call
(each subkernel
Printcosts two); a real message issued later in the same call can disappear. General::stopcounts per subkernel batch, not per master evaluation. When a subkernel reaches it, the master also issues a realGeneral::stopof its own, and that one does trip the master'sCheck.
Capture the master's relay instead of printing it:
Module[{bag = Internal`Bag[], res},
res = WithCleanup[LaunchKernels[1];
Block[{Print = Internal`StuffBag[bag, StringJoin[ToString /@ {##}]] &},
ParallelMap[(Print["sub ", #]; 1/#) &, {0, 1}]],
CloseKernels[]];
{res, Internal`BagPart[bag, All]}]
(* wolframscript (MCP Session: the same with a higher kernel number):
{{ComplexInfinity, 1}, {"kernel 1 (Local (1)):", "sub 0\n", "From kernel 1 (Local (1)):",
" 1\nPower::infy: Infinite expression - encountered.\n 0", "kernel 1 (Local (1)):", "sub 1\n"}} *)
Better: collect messages, prints and the stack inside the subkernel and return them as data. A pure Function
needs no distribution; only pf must be defined on the subkernel. $Messages = {} stops the relay:
pf[x_] := (Print["pf ", x]; 1/x);
capture = Function[x, Module[{msgs = Internal`Bag[], prints = Internal`Bag[], stack = None, res},
res = Internal`HandlerBlock[{"Message", Function[m, If[Last[m],
Internal`StuffBag[msgs, Replace[m, Hold[Message[mn_, ___], _] :> ToString[Unevaluated[mn], InputForm]]];
If[stack === None, stack = Replace[Replace[Stack[_], {a___, mf : _[_Message], ___} :> {a, mf}],
_[e_] :> StringTake[ToString[Unevaluated[e], InputForm], UpTo[80]], {1}]]]]},
Block[{Print = Internal`StuffBag[prints, StringJoin[ToString /@ {##}]] &, $Messages = {}},
StackBegin[StackComplete[pf[x]]]]];
<|"x" -> x, "KernelID" -> $KernelID, "Result" -> ToString[res, InputForm],
"Messages" -> Internal`BagPart[msgs, All], "Prints" -> Internal`BagPart[prints, All], "Stack" -> stack|>]];
WithCleanup[LaunchKernels[1]; ParallelMap[capture, {0, 1}], CloseKernels[]]
(* wolframscript:
{<|"x" -> 0, "KernelID" -> 1, "Result" -> "ComplexInfinity", "Messages" -> {"Power::infy"}, "Prints" -> {"pf 0"},
"Stack" -> {"StackComplete[pf[0]]", "pf[0]", "Print[\"pf \", 0]; 1/0", "1/0", "0^(-1)",
"Message[Power::infy, HoldCompleteForm[0^(-1)]]"}|>,
<|"x" -> 1, "KernelID" -> 1, "Result" -> "1", "Messages" -> {}, "Prints" -> {"pf 1"}, "Stack" -> None|>}
MCP Session: same, with a higher "KernelID" and names like Sessions`<id>`pf[0] (the session context is not on the
subkernel's $ContextPath); MCP Local: "KernelID" -> 0 (ran in the master) *)
Cutting the stack at the Message[...] frame drops the handler's own frames. Helpers:
With[{cap = WolframDebugging`$CaptureFunction}, ParallelMap[cap[f[#]] &, list]] (the same record for any
expression) and WolframDebugging`ParallelCapture[f, list] (a summary); see HelperFunctions.md.
Aborts, throws, time-outs and crashes in subkernels
WithCleanup[
LaunchKernels[1];
{CheckAbort[ParallelMap[If[# == 2, Abort[], #] &, {1, 2, 3}], "MASTER-ABORTED"],
ParallelEvaluate[Throw[7, "tag"]],
ParallelTable[If[i == 2, Throw[i], i], {i, 3}],
ParallelMap[Catch[If[# == 2, Throw[#, "tag"], #], "tag"] &, {1, 2, 3}],
TimeConstrained[ParallelMap[(Pause[3]; #) &, {1, 2}], 1, "TimedOut"],
ParallelEvaluate[$KernelID]},
CloseKernels[]]
(* {"MASTER-ABORTED", {$Aborted}, $Aborted, {1, 2, 3}, "TimedOut", {1}} (wolframscript; MCP Session: same shape) *)
| in the subkernel | the master sees |
|---|---|
Abort[] | the master evaluation is aborted (without CheckAbort a wolframscript run stops) |
uncaught Throw | $Aborted for that result (or the whole ParallelTable), no message |
Catch inside the mapped function | normal results |
returned Failure[...] | the Failure as a result |
master TimeConstrained expires | the subkernel's evaluation is aborted too; the kernel stays usable |
Quit[] or a crash | LinkObject::linkd + KernelObject::rdead, $Failed; the kernel is discarded |
After a Quit[] or crash, ParallelMap does not relaunch the kernel; it falls back to the master:
WithCleanup[
LaunchKernels[1];
{ParallelEvaluate[Quit[]], Length[Kernels[]], ParallelMap[$KernelID &, {1, 2}]},
CloseKernels[]]
(* LinkObject::linkd: Unable to communicate with closed link LinkObject[.../wolfram -noinit -subkernel -wstp, 205, 4].
KernelObject::rdead: Discarding kernel 1 (Local (1)).
ParallelMap::nopar: No parallel kernels available; proceeding with sequential evaluation.
{{$Failed}, 0, {0, 0}} *)
A deterministic crash inside ParallelMap, ParallelTable or ParallelSubmit + WaitAll can loop forever
(not re-checked here, since it pins a CPU): the item is requeued (LaunchKernels::req), the kernel relaunched
(LaunchKernels::clone), it crashes again, and so on until an outer time limit (SetSystemOptions["ParallelOptions" -> ...]
does not stop it); in MCP Session until the tool's time limit, possibly leaving an untracked subkernel process. Probe a
suspect item on one kernel, where nothing is requeued (wolframscript):
crashF[x_] := If[x == 2, Run["kill -9 " <> ToString[$ProcessID]]; Pause[1]; x, x]; (* item 2 kills its kernel *)
WithCleanup[
LaunchKernels[1]; DistributeDefinitions[crashF];
TimeConstrained[ParallelEvaluate[crashF[2], First[Kernels[]]], 30, "TimedOut"],
CloseKernels[]]
(* LinkObject::linkd: ..., KernelObject::rdead: Discarding kernel 1 (Local (1)). -> $Failed (no requeue, no relaunch) *)
Run such probes under timeout -s KILL and check for leftover kernels afterwards (next section and
HeadlessAndCrashes.md).
Trace and stack sampling inside subkernels
Trace works on a subkernel even where the master's Trace is disabled (MCP Session, wolfram -script):
trF[x_] := x^2 + 1;
WithCleanup[
LaunchKernels[1]; DistributeDefinitions[trF];
{Trace[trF[2]], First[ParallelEvaluate[Trace[trF[2]]]]},
CloseKernels[]]
(* wolfram -script and MCP Session:
{{}, {HoldCompleteForm[trF[2]], HoldCompleteForm[2^2 + 1], {HoldCompleteForm[2^2], HoldCompleteForm[4]},
HoldCompleteForm[4 + 1], HoldCompleteForm[5]}}
wolframscript: both traces are full *)
Which item hangs, and where: run a bounded stack sampler (see TracingAndPerformance.md) inside the mapped function:
hangF[x_] := If[x == 2, Module[{k = 0}, While[True, k++]], x^2];
probe = Function[x, Module[{bag = Internal`Bag[], task, res},
task = SessionSubmit[ScheduledTask[Internal`StuffBag[bag, Stack[_]], {0.2, 20}]];
res = TimeConstrained[StackBegin[StackComplete[hangF[x]]], 1, "TimedOut"];
TaskRemove[task];
{x, $KernelID, res, If[Internal`BagLength[bag] == 0, None,
Replace[TakeWhile[Internal`BagPart[bag, -1], FreeQ[#, HoldPattern[bag]] &],
_[e_] :> StringTake[ToString[Unevaluated[e], InputForm], UpTo[60]], {1}]]}]];
WithCleanup[LaunchKernels[1]; ParallelMap[probe, {1, 2}], CloseKernels[]]
(* wolframscript:
{{1, 1, 1, None}, {2, 1, "TimedOut", {"StackComplete[hangF[2]]", "hangF[2]",
"If[2 == 2, Module[{k = 0}, While[True, k++]], 2^2]", "Module[{k = 0}, While[True, k++]]", "While[True, k$16796++]"}}}
MCP Local: the same records with KernelID 0 (sequential fallback) *)
What is sent and received: the Parallel debug tracers
The Parallel`Debug` tracers are loaded with Parallel in 15.0. They show the batches sent to each kernel and the
results that came back (-internal value- = definition distribution). The options are global: restore them.
tf[x_] := 1/x;
WithCleanup[
LaunchKernels[1];
SetOptions[Parallel`Debug`$Parallel, Parallel`Debug`TraceHandler -> "Save",
Parallel`Debug`Tracers -> {Parallel`Debug`SendReceive, Parallel`Debug`Queueing}];
ParallelMap[tf, {1, 2}];
StringTake[ToString[Last[#] /. {Subscript[_, e_] :> e, Short[e_, _] :> e} /.
HoldForm[e_] :> RuleCondition[ToString[Unevaluated[e], InputForm]]], UpTo[100]] & /@ Parallel`Debug`TraceList[],
SetOptions[Parallel`Debug`$Parallel, Parallel`Debug`Tracers -> {}, Parallel`Debug`TraceHandler -> "Print"];
CloseKernels[]]
(* wolframscript (MCP Session: the same with its own kernel and job numbers):
{"Sending to kernel 1: -internal value- (q=0)", "Receiving from kernel 1: -internal value- (q=0)",
"Sending to kernel 1: $`w[(Map[tf])[Unevaluated[{1, 2}]], 1] (q=0)", "Receiving from kernel 1: $`j[{1, 1/2}, 1] (q=0)",
" [(Map[tf])[Unevaluated[{1, 2}]]] done\neid[1]"} *)
Other tracers: Parallel`Debug`MathLink (kernel connections), Parallel`Debug`Exceptions,
Parallel`Debug`SharedMemory (SetSharedVariable reads and writes). SetOptions before Parallel is loaded fails
with SetOptions::optnf: evaluate Kernels[] first (it loads Parallel without launching a kernel, so the
Parallel`Debug`MathLink tracer then also records the launch).
Leftover kernels
Check both the kernels the master knows about and the operating-system child processes (wolframscript or MCP
Session; uses ps, so Linux or macOS):
childKernels[] := Select[StringSplit[RunProcess[{"ps", "-o", "pid=,args=", "--ppid", ToString[$ProcessID]}, "StandardOutput"], "\n"],
StringContainsQ["-subkernel"]];
LaunchKernels[1];
{Length[Kernels[]], Length[childKernels[]]}
CloseKernels[]; Pause[1]; {Length[Kernels[]], Length[childKernels[]]}
(* {1, 1} then {0, 0} *)
- MCP Session keeps kernels (also auto-launched ones) for the whole server lifetime. After a tool time-out during a
parallel call the kernel is either still in
Kernels[](and usable), or discarded while its process keeps running until its current evaluation ends. RunCloseKernels[]and check the child processes again. RunProcessis blocked in MCP Local (RunProcess::pnfd), and in MCP Session never useRun(its output goes into the JSON-RPC stream).- Helper:
WolframDebugging`KernelReport[](kernels, subkernel PIDs, untracked child kernels, task count).
Asynchronous tasks run inside other evaluations
SessionSubmit/ScheduledTask bodies and the handler functions of SessionSubmit, URLSubmit and LocalSubmit run
preemptively inside whatever evaluation is in progress: their Abort[] aborts it, their uncaught Throw unwinds to
its Catch, their messages trip its Check:
{SessionSubmit[ScheduledTask[Throw["from-task", "tg"], {0.3, 1}]];
Catch[Do[Pause[0.05], {30}]; "main-not-thrown", _, {"MAIN-CAUGHT", ##} &],
SessionSubmit[ScheduledTask[Abort[], {0.3, 1}]];
CheckAbort[Do[Pause[0.05], {30}]; "main-not-aborted", "MAIN-ABORTED"],
SessionSubmit[ScheduledTask[Message[General::argx, "task", 2], {0.3, 1}]];
Check[Do[Pause[0.05], {30}]; "main-done", "CHECK-FIRED"]}
(* {{"MAIN-CAUGHT", "from-task", "tg"}, "MAIN-ABORTED", "CHECK-FIRED"} (wolframscript, MCP Local, MCP Session) *)
- Tasks keep firing between MCP tool calls, and a task submitted in one call can abort or throw out of a later
call (
$Aborted, orThrow::nocatchwithHold[Throw[...]]). In MCP Local the kernel is shared, so that later call can be another agent's. - A
Catch[..., _]in the code under test catches a task'sThrow, and aTimeConstrainedaroundTaskWait[task]aborts the task's body if it is running at that moment. - Where task output appears: wolframscript prints it; MCP Session shows it only when it happens during a call (output
between calls is lost; messages still go into the server's cumulative
$MessageList); MCP Local shows neither thePrintoutput nor the messages of tasks (theCheckabove still fired). Return data instead (below).
Keep tasks bounded and remove only your own
myTick = 0;
myTask = SessionSubmit[ScheduledTask[myTick++, {0.2, 50}]]; (* always bounded: {interval, count} *)
Pause[1];
mine[] := Select[Tasks[], StringContainsQ[ToString[#["EvaluationExpression"], InputForm], "myTick"] &];
{myTick, Length[mine[]], TaskRemove[mine[]]; Length[mine[]]}
(* {4, 1, 0} (wolframscript, MCP Local; the first number varies) *)
Tasks[] in MCP Local and MCP Session lists every session's tasks: TaskRemove[Tasks[]] would remove other agents'
tasks too. Filter on something unique in "EvaluationExpression" (it is a HoldForm), or keep the TaskObject.
Helper: WolframDebugging`TaskReport[].
Task results and failures as data
With the default AutoRemove -> True a finished task is removed and task["EvaluationResult"] fails with
TaskObject::timnf; get the result from a handler (request the keys you use in HandlerFunctionsKeys):
res = None;
t = SessionSubmit[41 + 1, HandlerFunctions -> <|"TaskFinished" -> ((res = #EvaluationResult) &)|>,
HandlerFunctionsKeys -> {"EvaluationResult"}];
TimeConstrained[TaskWait[t], 5]; Pause[0.2];
{res, t["TaskStatus"]}
(* {42, "Removed"} *)
AutoRemove -> False keeps the result, but then TaskWait never returns: always wrap it in TimeConstrained. Wrap the
task body so that a failure becomes data instead of hitting whatever evaluation is running:
bag = Internal`Bag[];
run = Function[body, Internal`StuffBag[bag,
CheckAbort[KeyTake[EvaluationData[body], {"Result", "MessagesExpressions", "OutputLog"}], "Aborted"]], HoldAll];
tasks = {SessionSubmit[ScheduledTask[run[Print["tick"]; 1/0; 5], {0.1, 1}]],
SessionSubmit[ScheduledTask[run[Throw[1, "t"]], {0.2, 1}]],
SessionSubmit[ScheduledTask[run[Abort[]], {0.3, 1}]]};
TimeConstrained[TaskWait[tasks], 5]; Internal`BagPart[bag, All]
(* {<|"Result" :> 5, "MessagesExpressions" -> {Hold[Message[Power::infy, HoldCompleteForm[0^(-1)]]]}, "OutputLog" -> {"tick"}|>,
<|"Result" :> Hold[Throw[1, "t"]], "MessagesExpressions" -> {Hold[Message[Throw::nocatch, HoldForm[Throw[1, "t"]]]]}, "OutputLog" -> {}|>,
"Aborted"}
wolframscript and MCP Local; MCP Session: "OutputLog" -> {} (the server captures Print first) *)
EvaluationData turns an uncaught Throw into Throw::nocatch + Hold[Throw[...]]; CheckAbort keeps an Abort[]
inside the task. EvaluationData does not suppress printing (wolframscript still prints tick and the messages).
Helper: WolframDebugging`SubmitAndWait[expr, timeout] (submit, capture, bounded wait, remove).
Handler events: "TaskFinished", "ResultReceived" and "TaskStatusChanged" fire; "PrintOutputGenerated" fires
with #PrintOutput = HoldComplete["text"] and suppresses the print; "MessageGenerated" never fires for
SessionSubmit/LocalSubmit (and in wolframscript adding it hides the task's messages): capture messages by wrapping
the body as above.
URLSubmit
HTTP errors are not failures: a 404 or 500 arrives as a normal "TaskFinished" with that "StatusCode"; only a
connection failure (refused, unknown host) fires "ConnectionFailed":
events = Internal`Bag[];
rec = Function[ev, Internal`StuffBag[events, KeyTake[ev, {"EventName", "StatusCode"}]]];
tasks = URLSubmit[#, HandlerFunctions -> <|"TaskFinished" -> rec, "ConnectionFailed" -> rec|>,
HandlerFunctionsKeys -> {"EventName", "StatusCode"}] & /@
{"http://127.0.0.1:18765/missing.txt", "http://127.0.0.1:1/refused"};
TimeConstrained[TaskWait[tasks], 10]; Internal`BagPart[events, All]
(* (a local web server on port 18765)
{<|"EventName" -> "TaskFinished", "StatusCode" -> 404|>,
<|"EventName" -> "ConnectionFailed", "StatusCode" -> Missing["NotAvailable"]|>,
<|"EventName" -> "TaskFinished", "StatusCode" -> Missing["NotAvailable"]|>} (wolframscript, MCP Local) *)
Mistakes in the handler specification are easy to miss:
{URLSubmit["http://127.0.0.1:18765/hello.txt", HandlerFunctions -> <|"TaskFinish" -> Print|>],
URLSubmit["http://127.0.0.1:18765/hello.txt", HandlerFunctions -> <|"TaskFinished" -> (Print[1]; Print[2]) &|>]} // Map[Head]
(* URLSubmit::invm: TaskFinish is not a known event name.
URLSubmit::invk: Association[TaskFinished -> (Print[1]; Print[2]) & ] is not a known value for HandlerFunctionsKeys.
{TaskObject, Failure} *)
A misspelled event only warns and the task runs without that handler. "Event" -> (a; b) & parses as
("Event" -> (a; b)) &: write "Event" -> ((a; b) &). Handlers run inside the current evaluation like task bodies
(their messages, Throw and Abort[] hit it) and also fire between top-level evaluations.
LocalSubmit
Each LocalSubmit launches a fresh kernel (about 6 s) that receives no definitions; its messages appear nowhere,
and Throw or Abort[] there give $Failed as the result without a message:
lsF[x_] := x + 1;
out = Internal`Bag[];
t = LocalSubmit[ToString[{lsF[1], 1/0}, InputForm],
HandlerFunctions -> <|"TaskFinished" -> (Internal`StuffBag[out, #EvaluationResult] &)|>,
HandlerFunctionsKeys -> {"EvaluationResult"}];
TimeConstrained[TaskWait[t], 30]; Internal`BagPart[out, All]
(* wolframscript: {"{lsF[1], ComplexInfinity}"} -- lsF was not defined there; Power::infy was not shown
MCP Local: LocalSubmit::subkern: LinkLaunch[".../wolfram -noinit"] failed. TaskWait::taskid ... {} *)
Return ToString[..., InputForm] from the remote kernel (as here): an unevaluated lsF[1] that comes back is evaluated
by the local kernel and looks correct (LocalSubmit[{lsF[1], $ProcessID}, ...] delivered {2, <remote PID>}).
LocalSubmit works in wolframscript and MCP Session (there the string shows Sessions`<id>`lsF[1]); it fails in MCP
Local (protected mode) and in the cloud (LocalSubmit::cloud).
Setting Up the Wolfram MCP Server
This guide explains how to connect your client to a Wolfram MCP server. With an MCP server you call the Wolfram tools directly instead of running the bundled scripts. A local server also keeps one Wolfram Language session alive between calls (definitions persist, and no kernel has to start for each call) and provides more tools.
There are two options:
| Wolfram Local MCP | Wolfram Cloud MCP | |
|---|---|---|
| Requires | A local Wolfram installation (Wolfram Engine, Wolfram, or Mathematica) | Nothing: free, no subscription or API key |
| Tools | Depends on the toolset (Step 3) | WolframContext, WolframLanguageEvaluator, WolframAlpha |
| Evaluation | Persistent session | Stateless, 60-second default time limit |
| Agent skills | DeployAgentTools installs them with the server | Not included |
Use the local server for coding agents and for anything that needs heavy computation, notebooks, tests, or paclet tools. Use Wolfram Cloud MCP when there is no local Wolfram installation and the user does not want to install one.
Both options change the user's client configuration, so ask the user before setting either one up. Also ask which toolset they want if the context does not make it clear. New MCP servers appear only after the client is restarted or reloaded, so the tools will not show up in your current session.
Option 1: Wolfram Local MCP
Step 1: Check for wolframscript
wolframscript -code '$VersionNumber'
If wolframscript is not found, read GetWolframEngine.md (in this references/ directory) or use Option 2. Current versions of AgentTools require Wolfram 15.0 or later.
The commands below are written for a POSIX shell. On Windows, shell quoting can mangle the double quotes in the code. To avoid that, put the code in a .wls file, wrap each result in Print[...], and run wolframscript -f file.wls.
Step 2: Install or update the AgentTools paclet
wolframscript -code 'PacletInstall["Wolfram/AgentTools", UpdatePacletSites -> True]["Version"]'
wolframscript -code 'Wolfram`AgentTools`AgentToolsObject["WolframLanguage"]["AgentSkillNames"]'
Wolfram 15 includes an older built-in copy of AgentTools. The first command installs the latest version, and Wolfram uses that version from then on. The second command should print {wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging}. If it prints {}, or the expression comes back unevaluated, the installed AgentTools cannot install agent skills. In that case use InstallMCPServer (Step 5).
Step 3: Choose a toolset
| Toolset | MCP tools | Agent skills installed by DeployAgentTools |
|---|---|---|
Wolfram | WolframContext, WolframLanguageEvaluator, WolframAlpha | wolfram-language, wolfram-alpha, wolfram-debugging |
WolframAlpha | WolframAlphaContext, WolframAlpha | wolfram-alpha |
WolframLanguage | WolframLanguageContext, WolframLanguageEvaluator, ReadNotebook, WriteNotebook, SymbolDefinition, CodeInspector, TestReport | wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging |
WolframPacletDevelopment | The WolframLanguage tools plus CreateSymbolDoc, EditSymbolDoc, EditSymbolDocExamples, CheckPaclet, BuildPaclet, SubmitPaclet | wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging |
- Use cases:
Wolframis for general computation and knowledge,WolframAlphafor Wolfram|Alpha queries only, andWolframLanguagefor Wolfram Language development.WolframPacletDevelopmentadds tools for writing documentation pages and for checking, building, and submitting paclets. - Tools: the
*Contexttools are semantic search (WolframAlphaContextover Wolfram|Alpha,WolframLanguageContextover Wolfram Language documentation and resources,WolframContextover both).ReadNotebook/WriteNotebookconvert notebooks (.nb) to and from markdown,SymbolDefinitionretrieves symbol definitions,CodeInspectorreports code issues, andTestReportruns.wlttest files. - Default toolset: without a toolset argument, the client's default is used:
Wolframfor Claude Desktop, Goose, and LM Studio, andWolframLanguagefor every other client. - One toolset per client: all four toolsets use the MCP configuration key
Wolfram, so a client (at a given user or project level) has only one of them. Switch withOverwriteTarget -> True, or use"MCPServerName"(Step 5) to install two side by side. - LLMKit: the context tools work best with an LLMKit subscription.
WolframAlphaContextrequires one, so installing theWolframAlphatoolset fails withLLMKitRequiredunless the kernel is connected to the Wolfram Cloud with an account that has LLMKit (useWolframinstead). For the other toolsets, anLLMKitSuggestedwarning is informational only.
Step 4: Choose DeployAgentTools or InstallMCPServer
DeployAgentTools is the recommended way. It installs the toolset's MCP server and its agent skills as one tracked deployment, which DeleteObject can remove again. InstallMCPServer writes only the MCP server configuration. Use it only when the MCP server is all that should be installed.
You are reading this from a Wolfram skill that is already installed, so check two things first:
- Existing deployments: run
wolframscript -code 'DeployedAgentTools[]'. If your client and location already have a deployment, the server is already configured. Ask the user to restart the client, or redeploy withOverwriteTarget -> Trueto switch toolsets or to add the skills that an older AgentTools did not install. - Where this skill is installed: this is the directory that contains this
references/folder. Compare its parent directory with the skills directory thatDeployAgentToolswill use (Supported Clients).
Use DeployAgentTools when this skill is already in that directory (same client, same user or project scope), or when no Wolfram skills are installed yet. It handles existing skills safely:
- An identical copy is adopted as is, and
DeleteObjectnever deletes a skill directory that existed before the deployment. - A copy with different content (installed by hand or by another tool, or a deployed copy that the user modified) is left untouched. The MCP server and the other skills are still installed, and the warning
DeployAgentTools::AgentSkillNotInstallednames the skipped skill. - Copies installed by an earlier deployment are updated to the current AgentTools version automatically; a newer copy that another deployment still uses is never downgraded. (Replacing a deployment for the same client and location still needs
OverwriteTarget -> True.)
Use InstallMCPServer, or DeployAgentTools with "SkillsDirectory" -> None (only the MCP server, still tracked as a deployment), when:
- The user only wants the MCP server, or Step 2 showed that the installed AgentTools has no agent skills.
- The Wolfram skills are installed somewhere that
DeployAgentToolsdoes not manage, but that your client also reads.DeployAgentToolswould add a second copy, and the client would see each skill twice. Examples: a Claude Code plugin (a path under~/.claude/plugins/); another skills directory that your client loads, such as~/.agents/skillsor~/.claude/skillsfor a client that also reads those; or the project's skills directory while you deploy at user level (a project-level deployment also works there if the client supports project MCP configuration).
Never use OverwriteTarget -> All without asking the user. It replaces skill directories that the deployment does not own and discards any changes in them.
Step 5: Install the server
DeployAgentTools, DeployedAgentTools, and AgentToolsDeployment are built-in symbols, so they need no context prefix:
# The client's default toolset, at user level
wolframscript -code 'DeployAgentTools["ClaudeCode"]'
# A specific toolset, at project level (the project's MCP configuration and skills directory)
wolframscript -code 'DeployAgentTools[{"ClaudeCode", "/path/to/project"}, "WolframLanguage"]'
# Only the MCP server, as a tracked deployment
wolframscript -code 'DeployAgentTools["ClaudeCode", "WolframLanguage", "SkillsDirectory" -> None]'
# Replace the Wolfram toolset already deployed for this client and location
wolframscript -code 'DeployAgentTools["ClaudeCode", "Wolfram", OverwriteTarget -> True]'
- Result: an
AgentToolsDeployment[...]. The first run can take a few minutes while the context tools download their search indexes, so use a generous command timeout. - Clients without agent skills support (Claude Desktop, LM Studio, Amazon Q Developer) get only the MCP server.
- Project level without project MCP support: the client gets only the project skills, with an
MCPServersNotDeployedwarning. Add the server at user level withInstallMCPServer. DeploymentExists: a Wolfram toolset is already deployed for that client and location. UseOverwriteTarget -> Trueto replace it.DeployAgentTools[All]deploys to every supported client, installed or not. Do not use it unless the user asks.- Removing:
DeleteObject /@ Select[DeployedAgentTools["ClaudeCode"], #["Scope"] === "Global" && #["Toolset"] === "WolframLanguage" &]removes the user-level deployment. For a project deployment, match#["Scope"] === File["/path/to/project"](the absolute project path) instead; without a scope test, every project's deployment of that toolset is removed too. Skills that another deployment still uses, that were modified, or that existed before the deployment are kept.
InstallMCPServer needs the full context name:
wolframscript -code 'Wolfram`AgentTools`InstallMCPServer["ClaudeCode", "WolframLanguage"]'
wolframscript -code 'Wolfram`AgentTools`InstallMCPServer[{"ClaudeCode", "/path/to/project"}, "WolframLanguage"]'
wolframscript -code 'Wolfram`AgentTools`UninstallMCPServer["ClaudeCode", "WolframLanguage"]'
InstallMCPServer is not tracked by DeployedAgentTools. It replaces whatever Wolfram server is already configured under the key Wolfram.
Both functions accept these options:
"ToolOptions" -> <|"WolframLanguageEvaluator" -> <|"TimeConstraint" -> 120|>|>: per-tool settings."SubmitUsageData" -> False: opts out of usage data collection, which the built-in servers do by default."MCPServerName" -> "WolframDev": uses a different configuration key, so that two Wolfram toolsets can be installed side by side.
Step 6: Restart the client
Ask the user to restart or reload the client. The tools then appear under the server name Wolfram, for example mcp__Wolfram__WolframLanguageEvaluator in Claude Code. When they are available, use them instead of the bundled scripts.
Supported Clients
| Client | Name | Project MCP | User skills directory | Project skills directory |
|---|---|---|---|---|
| Amazon Q Developer | "AmazonQ" | yes | — | — |
| Antigravity | "Antigravity" | yes | ~/.gemini/config/skills (before migration: ~/.gemini/antigravity/skills) | .agents/skills |
| Augment Code | "AugmentCode" | no | ~/.augment/skills | .augment/skills |
| Augment Code IDE | "AugmentCodeIDE" | no | ~/.augment/skills | .augment/skills |
| Claude Code | "ClaudeCode" | yes | ~/.claude/skills | .claude/skills |
| Claude Desktop (macOS, Windows) | "ClaudeDesktop" | no | — | — |
| Cline | "Cline" | no | ~/.cline/skills | .cline/skills |
| Codex CLI | "Codex" | yes | ~/.agents/skills | .agents/skills |
| Continue | "Continue" | yes | ~/.continue/skills | .continue/skills |
| Copilot CLI | "CopilotCLI" | no | ~/.copilot/skills | .github/skills |
| Cursor | "Cursor" | no | ~/.cursor/skills | .cursor/skills |
| Gemini CLI | "GeminiCLI" | no | ~/.gemini/skills | .gemini/skills |
| Goose | "Goose" | no | ~/.agents/skills | .agents/skills |
| Junie | "Junie" | yes | ~/.junie/skills | .junie/skills |
| Kimi Code | "KimiCode" | no | ~/.kimi/skills | .kimi/skills |
| Kiro | "Kiro" | yes | ~/.kiro/skills | .kiro/skills |
| LM Studio | "LMStudio" | no | — | — |
| OpenCode | "OpenCode" | yes | ~/.config/opencode/skills | .opencode/skills |
| Qwen Code | "QwenCode" | yes | ~/.qwen/skills | .qwen/skills |
| Visual Studio Code | "VisualStudioCode" | yes | ~/.copilot/skills | .github/skills |
| Windsurf | "Windsurf" | no | ~/.codeium/windsurf/skills | .windsurf/skills |
| Zed | "Zed" | yes | ~/.agents/skills | .agents/skills |
- Paths:
~is the user's home directory on every operating system. Project skills directories are relative to the project directory. - Aliases are accepted, such as
"Claude"(Claude Desktop),"VSCode","Copilot"(Copilot CLI), and"Gemini"(Gemini CLI). - Shared skills directories: several clients share one. AgentTools tracks which deployments use each skill, so removing one deployment never deletes skills that another deployment still uses.
- Non-standard configuration file: pass
File["/path/to/config.json"]as the target. Add"ApplicationName" -> "<Name>"if the path does not identify the client. WithDeployAgentTools, also pass"SkillsDirectory" -> File["/path/to/skills"], unless the file is the client's standard global or project configuration file.
Local Server in Other Clients: Manual Configuration
Any MCP client that can launch local (stdio) servers can run the local Wolfram server, even if it is not in the Supported Clients table. To print the exact configuration for this machine, run this command with the toolset you want:
wolframscript -code 'Wolfram`AgentTools`MCPServerObject["WolframLanguage"]["JSONConfiguration"]'
Example output on Linux, shown with / instead of the \/ escapes that the real output contains (both are valid JSON):
{
"mcpServers": {
"WolframLanguage": {
"type": "stdio",
"command": "/usr/local/Wolfram/Wolfram/15.0/Executables/wolfram",
"args": [
"-run",
"PacletSymbol[\"Wolfram/AgentTools\",\"Wolfram`AgentTools`StartMCPServer\"][]",
"-noinit",
"-noprompt"
],
"env": {
"MCP_SERVER_NAME": "WolframLanguage",
"WOLFRAM_BASE": "/usr/share/Wolfram",
"WOLFRAM_LOCALBASE": "/home/user/.Wolfram/Objects",
"WOLFRAM_USERBASE": "/home/user/.Wolfram"
}
}
}
}
If the client uses this common mcpServers JSON format, AgentTools can write the entry (under the key Wolfram) for you: Wolfram`AgentTools`InstallMCPServer[File["/path/to/config.json"], "WolframLanguage"] writes only the server, and DeployAgentTools[File["/path/to/config.json"], "WolframLanguage", "SkillsDirectory" -> File["/path/to/skills"]] also installs the skills. Otherwise, copy the values into the client's own format; any server name works.
Command: the Wolfram kernel executable wolfram, not wolframscript.
| OS | Command |
|---|---|
| Windows | $InstallationDirectory\wolfram.exe |
| macOS | $InstallationDirectory/MacOS/wolfram |
| Linux | $InstallationDirectory/Executables/wolfram |
Arguments: four separate arguments, given to the client exactly as in the printed "args":
-run, followed byPacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"][]. This loads the newest installed AgentTools and starts the stdio server.-noinit: skips the user's init files.-noprompt: keeps kernel prompts off standard output, which must carry only MCP messages.
As a single shell command line:
/path/to/wolfram -run 'PacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"][]' -noinit -noprompt
If the client cannot set environment variables, name the toolset in the argument instead: PacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"]["WolframLanguage"].
Environment variables:
| Variable | Needed | Purpose |
|---|---|---|
MCP_SERVER_NAME | Recommended | The toolset to run: Wolfram (the default when unset), WolframAlpha, WolframLanguage, WolframPacletDevelopment, or the name of another server known to AgentTools |
WOLFRAM_USERBASE | Recommended | $UserBaseDirectory. It must be the directory where AgentTools was installed; otherwise the kernel may load the older built-in copy |
WOLFRAM_BASE | Recommended | $BaseDirectory |
WOLFRAM_LOCALBASE | Recommended | $LocalBase (storage for LocalObject) |
APPDATA | Windows | The user's application data directory, from which Windows derives the default $UserBaseDirectory |
MCP_TOOL_OPTIONS | Optional | Per-tool options as compact JSON, e.g. {"WolframLanguageEvaluator":{"TimeConstraint":120}} |
SUBMIT_USAGE_DATA | Optional | false opts out of usage data collection |
MCP_APPS_ENABLED | Optional | false disables MCP Apps (interactive UI resources) |
LLMKIT_ENABLED | Optional | false makes the context tools behave as if there were no LLMKit subscription, without warnings |
The printed configuration already holds this machine's values for the directory variables. Keep them, because the client may start servers with a reduced environment.
Option 2: Wolfram Cloud MCP
Wolfram Cloud MCP is a hosted Wolfram MCP server. It is free and needs no subscription, API key, or local installation.
- URL:
https://agenttools.wolfram.com/mcp - Transport: Streamable HTTP, with no authentication
| Tool | Description |
|---|---|
WolframContext | Semantic search over Wolfram|Alpha and Wolfram Language resources |
WolframLanguageEvaluator | Evaluates Wolfram Language code |
WolframAlpha | Sends natural language queries to Wolfram|Alpha |
Differences from the local server:
- Stateless evaluation:
WolframLanguageEvaluatordoes not carry definitions over between calls. Its default time constraint is 60 seconds per call, which itstimeConstraintargument can change. - No other tools: there are no notebook, symbol definition, code inspection, test, or paclet tools. The
wolfram-notebooksandwolfram-pacletsskills still needwolframscriptfor their scripts. - Manual setup only:
DeployAgentToolsandInstallMCPServerconfigure only the local server.
Configure your client
Clients that support remote servers (some spell it differently: Cline adds "type": "streamableHttp", Antigravity uses "serverUrl"; the support article below has steps for many clients):
{ "mcpServers": { "wolfram": { "url": "https://agenttools.wolfram.com/mcp" } } }
Claude Code (add --scope user to make it available in all projects):
claude mcp add --transport http wolfram https://agenttools.wolfram.com/mcp
Visual Studio Code (the user mcp.json or the workspace's .vscode/mcp.json):
{ "servers": { "wolfram": { "type": "http", "url": "https://agenttools.wolfram.com/mcp" } } }
Claude Desktop: in Customize → Connectors, search for Wolfram and click +.
Clients that only support local (stdio) servers can use the mcp-remote bridge, which requires Node.js:
{ "mcpServers": { "wolfram": { "command": "npx", "args": ["-y", "mcp-remote@latest", "https://agenttools.wolfram.com/mcp"] } } }
The local Wolfram toolset already provides all three of these tools, so don't add the cloud server next to it. Next to another local toolset (for example WolframLanguage, which has no WolframAlpha tool), the cloud server can supply the missing tools under its own key, such as wolfram. Then ask the user to restart or reload the client.
Troubleshooting
LLMKitRequired: the localWolframAlphatoolset needs LLMKit. Use theWolframtoolset or Wolfram Cloud MCP instead.DeploymentExists: a Wolfram toolset is already deployed for that client and location. UseOverwriteTarget -> Trueto replace it.AgentSkillNotInstalled(warning): a different skill with the same name already exists. Everything else was installed. Keep the existing skill, or ask the user before usingOverwriteTarget -> All.UnknownInstallLocation: the client has no known configuration file on this operating system (for example, Claude Desktop on Linux). Use aFile[...]target.- The tools do not appear after a restart: check the configuration file that was written (
dep["ConfigFile"]for a deployment, or the"Location"of theInstallMCPServerresult), then the server log at$UserBaseDirectory/ApplicationData/Wolfram/AgentTools/Servers/<Toolset>/Log.wl. Also make sure the kernel is activated (wolframscript -code '1+1'prints2).
More Information
- Wolfram Local MCP: https://www.wolfram.com/artificial-intelligence/mcp/local/wolfram-mcp-local/
- Wolfram Cloud MCP: https://www.wolfram.com/artificial-intelligence/mcp/cloud/wolfram-mcp-cloud
- Connecting Wolfram Cloud MCP to an AI application: https://support.wolfram.com/75237
- AgentTools paclet: https://resources.wolframcloud.com/PacletRepository/resources/Wolfram/AgentTools/
Testing: VerificationTest, TestReport, MUnit
How to run test files and read the results compactly, what the outcome and failure-type values really are, which file
problems make tests silently disappear, how the test harness evaluates a test, how to re-run or reproduce one failing
test, and how to find order dependence. Read it when a test fails, passes only alone (or only in the suite), or a test
run reports suspiciously few tests. Behavior was checked with Wolfram 15.0 (MCP Local, wolframscript, the TestReport MCP
tool, fresh MCP Session and Local servers and the remote MCP server where stated; see Environments.md).
Which tool for which question
| question | first choice | section |
|---|---|---|
| run a test file | TestReport MCP tool (one file, timeConstraint) | Run tests with the TestReport MCP tool |
| which tests failed and why, compactly | tr["Results"] filtered + selected properties; WolframDebugging`TestFailureSummary[tr] | Read a TestReportObject compactly |
| "Total Tests: 0" or fewer tests than expected | syntax error / malformed test / top-level abort: static check; WolframDebugging`CheckTestFile[file] | Silent whole-file failures |
| test fails only on its messages | expected-message rules | Expected messages |
| re-run one test (with its setup tests) | VerificationTest filter in Internal`InheritedBlock; WolframDebugging`RunTestsByID[file, id] | Re-run one test |
| where does the failing input go wrong? | stack at the first message; IntermediateTest; WolframDebugging`ReproduceTest[t] | Reproduce a failing input |
| passes alone, fails in the suite | run alone in a fresh kernel, per-test state snapshots | Order dependence |
| passes locally, fails in CI | MX build: ReadProtected symbols | CI-only failures |
Helpers are in scripts/WolframDebugging.wl (load it with Get in its own call, call them fully qualified; options and
outputs: HelperFunctions.md; WolframDebugging`TestSource[file, idPattern] gives a test's source lines without
evaluating anything). Everything below works without them.
The examples use small test files in testDir (testDir = "/abs/path/to/tests";). Demo.wlt:
VerificationTest[1 + 1, 2, TestID -> "Pass"]
VerificationTest[StringJoin["a", "b"], "ba", TestID -> "WrongResult"]
VerificationTest[1/0, ComplexInfinity, TestID -> "UnexpectedMessage"]
VerificationTest[1/0, ComplexInfinity, {Power::infy}, TestID -> "ExpectedMessageOK"]
VerificationTest[1/2, 1/2, {Power::infy}, TestID -> "ExpectedMessageMissing"]
VerificationTest[Failure["Boom", <|"MessageTemplate" -> "boom"|>], 1, TestID -> "FailureResult"]
VerificationTest[Throw[42, "tag"], 42, TestID -> "UncaughtThrow"]
VerificationTest[Pause[3]; 1, 1, TimeConstraint -> 1, TestID -> "TimeOut"]
VerificationTest[Table[1/0, 5]; 7, 7, TestID -> "GeneralStop"]
VerificationTest[StringLength[ToString[1/0]], 14, TestID -> "WrongAndMessage"]
Run tests with the TestReport MCP tool
- Each call starts a fresh
wolfram -scriptkernel with-noinit(several seconds of startup); all files of one call (a comma list or a directory) run in that one kernel, so state leaks from file to file. (newKernel: falseruns them in the MCP server's own kernel instead, and their state stays there.) timeConstraintis the default limit per test (not per file); there is no overall limit, so a hanging test without it hangs the tool call. Pass it.- Trace records nothing inside these tests. A test that prints its environment showed
{First[$ContextPath], $Context, Trace[1 + 1] =!= {}, MemberQ[$CommandLine, "-noinit"], Internal`TimeRemaining[]}={"MUnit`", "Global`", False, True, 29.999894}withtimeConstraint: 30. - Output: a Markdown summary (Overall Result, Total Tests, Passed, Failed), then per failed test its Input, Expected and Actual Output and Messages (about 400–700 bytes per failure). Passing tests and the failure type are not listed.
- Anything printed outside the tests (messages from top-level code,
VerificationTest::nonopt, syntax errors,Print) appears above# Test Results Summary. Read it. - Always check "Total Tests": a file with a syntax error reports
Overall Result: SuccesswithTotal Tests: 0, and a file with a top-levelAbort[]returns no output at all (next section).
Read a TestReportObject compactly
In the evaluator or wolframscript, never return the TestReportObject or a TestObject itself (ByteCount of the
10-test report below: 51 KB; every TestObject carries its inputs, outputs and timing). Select what you need:
tstReport = TestReport[FileNameJoin[{testDir, "Demo.wlt"}], ProgressReporting -> False, TimeConstraint -> 30];
{tstReport["TestsSucceededCount"], tstReport["TestsFailedCount"],
#[{"TestID", "Outcome", "FailureType"}] & /@ Select[tstReport["Results"], #["Outcome"] =!= "Success" &]}
(* {2, 8, {<|"TestID" -> "WrongResult", "Outcome" -> "Failure", "FailureType" -> "SameTestFailure"|>,
<|"TestID" -> "UnexpectedMessage", "Outcome" -> "MessagesFailure", "FailureType" -> "SameMessagesFailure"|>,
<|"TestID" -> "ExpectedMessageMissing", "Outcome" -> "MessagesFailure", "FailureType" -> "SameMessagesFailure"|>,
<|"TestID" -> "FailureResult", "Outcome" -> "Failure", "FailureType" -> "SameTestFailure"|>,
<|"TestID" -> "UncaughtThrow", "Outcome" -> "Failure", "FailureType" -> "UncaughtThrowFailure"|>,
<|"TestID" -> "TimeOut", "Outcome" -> "Failure", "FailureType" -> "TimeConstrainedFailure"|>,
<|"TestID" -> "GeneralStop", "Outcome" -> "MessagesFailure", "FailureType" -> "SameMessagesFailure"|>,
<|"TestID" -> "WrongAndMessage", "Outcome" -> "Failure", "FailureType" -> "SameTestFailure"|>}} *)
One line per failure, with the actual value and the message names (tstReport from above):
StringRiffle[Function[t, StringJoin[t["TestID"], " [", t["Outcome"], "/", ToString[t["FailureType"]], "] act: ",
StringTake[ToString[t["ActualOutput"], InputForm], UpTo[60]], " msgs: ",
StringTake[ToString[Replace[t["ActualMessages"], HoldForm[Message[m_, ___]] :> HoldForm[m], {1}], InputForm], UpTo[80]]]] /@
Select[tstReport["Results"], #["Outcome"] =!= "Success" &], "\n"]
WrongResult [Failure/SameTestFailure] act: HoldForm["ab"] msgs: {}
UnexpectedMessage [MessagesFailure/SameMessagesFailure] act: HoldForm[ComplexInfinity] msgs: {HoldForm[Power::infy]}
ExpectedMessageMissing [MessagesFailure/SameMessagesFailure] act: HoldForm[1/2] msgs: {}
FailureResult [Failure/SameTestFailure] act: HoldForm[Failure["Boom", <|"MessageTemplate" -> "boom"|>]] msgs: {}
UncaughtThrow [Failure/UncaughtThrowFailure] act: Hold[Throw[42, "tag"]] msgs: {}
TimeOut [Failure/TimeConstrainedFailure] act: HoldForm[Failure["TimeConstrained", <|"MessageTemplate" :> T msgs: {}
GeneralStop [MessagesFailure/SameMessagesFailure] act: HoldForm[7] msgs: {HoldForm[Power::infy], HoldForm[Power::infy], HoldForm[Power::infy], HoldForm[G
WrongAndMessage [Failure/SameTestFailure] act: HoldForm[15] msgs: {HoldForm[Power::infy]}
Helper: WolframDebugging`TestFailureSummary[tstReport] (input, expected, actual, message texts,
failed IntermediateTest steps, within a byte budget).
Outcomes, failure types, value formats
| situation | "Outcome" | "FailureType" |
|---|---|---|
| passed | "Success" | None |
wrong value (also a returned Failure[...] or an unevaluated f[3]) | "Failure" | "SameTestFailure" |
SameTest function returned a non-Boolean | "Failure" | "SameTestUnevaluated" |
| unexpected, missing or different messages | "MessagesFailure" | "SameMessagesFailure" |
uncaught Throw | "Failure" | "UncaughtThrowFailure" |
Abort[] in the input | "Failure" | "EvaluationAbortedFailure" |
TimeConstraint / MemoryConstraint exceeded | "Failure" | "TimeConstrainedFailure" / "MemoryConstrainedFailure" |
an IntermediateTest step failed | "Failure" | "IntermediateTestFailure" |
created with TestCreate but not run | "NotEvaluated" | None |
The documentation's "MessageFailure", "TimeConstraintFailure" and "MemoryConstraintFailure" do not occur; compare
against the strings above. A wrong value wins over messages: WrongAndMessage is "Failure" although it also issued
Power::infy, so look at "ActualMessages" for every failure.
Values are held, not evaluated; never ReleaseHold them (that re-runs the input):
{ToString[#, InputForm] & /@ First[tstReport["ResultsByTestID"]["UnexpectedMessage"]][
{"Input", "ExpectedOutput", "ActualOutput", "ExpectedMessages", "ActualMessages"}],
First[tstReport["ResultsByTestID"]["UncaughtThrow"]]["ActualOutput"],
First[tstReport["ResultsByTestID"]["ExpectedMessageOK"]]["ExpectedMessages"]}
(* {<|"Input" -> "HoldForm[1/0]", "ExpectedOutput" -> "HoldForm[ComplexInfinity]", "ActualOutput" -> "HoldForm[ComplexInfinity]",
"ExpectedMessages" -> "HoldForm[{}]", "ActualMessages" -> "{HoldForm[Message[Power::infy, HoldCompleteForm[0^(-1)]]]}"|>,
Hold[Throw[42, "tag"]], HoldForm[{Power::infy}]} *)
"Input"/"ExpectedOutput"/"ActualOutput" are HoldForm[...] (a Throw or Abort[] gives Hold[...]),
"ExpectedMessages" is one HoldForm around the list, "ActualMessages" a list of HoldForm[Message[...]] whose
kernel-issued arguments are HoldCompleteForm[...] in 15.0 (older versions: HoldForm). Strip with patterns such as
Replace[v, (HoldForm | Hold)[e_] :> ToString[Unevaluated[e], InputForm]].
tr["Properties"] lists only some of the properties that work; the legacy groups are useful too:
{tstReport["Properties"], Keys[tstReport["TestsFailed"]], Length /@ tstReport["ResultsByOutcome"]}
(* {{"Title", "Results", "ResultsDataset", "ResultsByOutcome", "ResultsByTestFileName", "ResultsByTestID", "RuntimeFailures",
"ReportSucceeded", "MemoryUsed", "CPUTimeUsed", "AbsoluteTimeUsed"},
{"TestsFailedWrongResults", "TestsFailedWithMessages", "TestsFailedWithErrors"},
<|"Success" -> 2, "MessagesFailure" -> 3, "Failure" -> 5, "NotEvaluated" -> 0|>} *)
"TestsSucceededCount", "TestsFailedCount", "TestsFailedWrongResults" (every "Failure", including throws, aborts and
time-outs) and "TestsFailedWithMessages" work although they are not listed; "TestsFailedWithErrors" is always empty.
"ResultsByTestID" maps each ID to a list (IDs can repeat). Unknown property names return Missing["KeyAbsent", ...]
without a message.
Silent whole-file failures
Three file problems lose tests without a failing outcome (Syntax.wlt: a test VerificationTest[1 +, 2, ...] between
two good ones; Dropped.wlt: a good test and one with a fourth positional argument; TopAbort.wlt: Abort[]; between
two tests):
{With[{r = TestReport[FileNameJoin[{testDir, "Syntax.wlt"}], ProgressReporting -> False]},
{Length[r["Results"]], r["TestsSucceededCount"], r["RuntimeFailures"]}],
Length[TestReport[FileNameJoin[{testDir, "Dropped.wlt"}], ProgressReporting -> False]["Results"]],
CheckAbort[TestReport[FileNameJoin[{testDir, "TopAbort.wlt"}], ProgressReporting -> False], "aborted"]}
Read::readt: Invalid input found when reading VerificationTest[1 +, 2, TestID -> "S-Broken"] from .../Syntax.wlt.
TestReport::rnterr: Syntax error reading: VerificationTest[1 +, 2, TestID -> "S-Broken"].
VerificationTest::nonopt: Options expected (instead of {extra}) beyond position 3 in VerificationTest[...]. An option must be a rule or a list of rules.
{{0, 0, {Failure["TestReportFailure", <|"MessageTemplate" :> TestReport::rnterr, "MessageParameters" -> {"Syntax error reading: ..."}, "Level" -> "Fatal"|>]}},
1, "aborted"}
- A syntax error anywhere runs no test at all, not even the ones before it (the whole file is syntax-checked
before the first test runs). The TestReport MCP tool then says
Overall Result: Success,Total Tests: 0(with the messages andAgentTools::NoTestsInFileabove the summary). - A
VerificationTestwith more than three positional arguments (e.g. a stray second message list) issuesVerificationTest::nonoptand is dropped from the report; the tool counts 1 test forDropped.wlt. - A top-level
Abort[](outside any test) aborts the wholeTestReport; an uncaught top-levelThrowescapes it. The TestReport MCP tool returns no output at all. - MUnit's
BeginTestSection[name, False]skips the tests of its section, and a top-levelTestIgnore[True]every later test of the file (a laterTestIgnore[False]does not undo it), without listing them.
Check files statically before trusting a count: the CodeInspector MCP tool (finds syntax errors, not malformed tests),
WolframDebugging`CheckTestFile[file] (syntax errors, top-level Abort/Throw/Exit/Quit, malformed tests, missing
or duplicate TestIDs), or CodeParser directly:
Block[{$ContextPath}, Needs["CodeParser`"]];
Table[{FileNameTake[file],
Cases[CodeParser`CodeParse[File[file]], (h : CodeParser`SyntaxErrorNode | CodeParser`ErrorNode |
CodeParser`UnterminatedGroupNode | CodeParser`GroupMissingCloserNode)[tag_, _, KeyValuePattern[CodeParser`Source -> src_]] :>
{SymbolName[h], tag, src}, Infinity],
Cases[CodeParser`CodeParse[File[file]], CodeParser`CallNode[CodeParser`LeafNode[Symbol, "VerificationTest", _], args_,
KeyValuePattern[CodeParser`Source -> src_]] /;
Count[args, Except[CodeParser`CallNode[CodeParser`LeafNode[Symbol, "Rule" | "RuleDelayed", _], ___]]] > 3 :>
{"MoreThan3PositionalArgs", src}, Infinity]},
{file, FileNameJoin[{testDir, #}] & /@ {"Syntax.wlt", "Dropped.wlt", "Demo.wlt"}}]
(* {{"Syntax.wlt", {{"ErrorNode", Token`Error`ExpectedOperand, {{2, 21}, {2, 21}}}}, {}},
{"Dropped.wlt", {}, {{"MoreThan3PositionalArgs", {{2, 1}, {2, 95}}}}},
{"Demo.wlt", {}, {}}} -- sources are {{line, column}, {line, column}} *)
How the harness evaluates a test
Knowing this explains most surprises:
- The file is read one expression at a time, each parsed after the previous one ran. A
Get/Needsin an earlier test (or top-level line) makes later short names resolve; aGetand a use of its symbols inside one test do not work (the whole test was parsed first).Load.wltloadsShadowDemo.wl(exportingshFn[x_] := x^2) in its first test and usesshFnin both:
{#["TestID"], #["Outcome"], #["ActualOutput"], #["ActualMessages"]} & /@
TestReport[FileNameJoin[{testDir, "Load.wlt"}], ProgressReporting -> False]["Results"]
(* {{"L-GetAndUseSameTest", "Failure", HoldForm[Global`shFn[3]], {HoldForm[Message[shFn::shdw, ...]]}},
{"L-UseInLaterTest", "Success", HoldForm[9], {}}}
(MCP evaluator: Sessions`<id>`shFn instead of Global`shFn) *)
Load packages in a separate setup test (a common convention is tests with IDs like "GetDefinitions"/"LoadContext").
- Each test runs inside
Block[{$Messages = {}, $MessageList = {}}]: test messages are not printed, and theGeneral::stopcount starts again for every test. Messages are recorded by a"MessageTextFilter"handler, so only messages that would really print count (quieted ones,Offones and the occurrences thatGeneral::stopsuppresses do not;General::stopitself does).Checkdoes not hide a message. - The input runs under
StackBegin(a stack taken inside a test starts at the test input) andCheckAll, which turnsThrowandAbort[]into failures;TimeConstraint/MemoryConstraint(per test, orTestReport's option as the default) wrap it. - The expected output is evaluated after the input, and
MUnit`is first on$ContextPathwhile a file runs:
ClearAll[tsOrder];
{VerificationTest[tsOrder = 5; tsOrder, tsOrder]["Outcome"],
#["ActualMessages"] & /@ {VerificationTest[Table[1/0, 2]; 1, 1, {Power::infy ..}], VerificationTest[Table[1/0, 2]; 1, 1, {Power::infy ..}]}}
(* {"Success", {{HoldForm[Message[Power::infy, HoldCompleteForm[0^(-1)]]], HoldForm[Message[Power::infy, HoldCompleteForm[0^(-1)]]]},
{HoldForm[Message[Power::infy, HoldCompleteForm[0^(-1)]]], HoldForm[Message[Power::infy, HoldCompleteForm[0^(-1)]]]}}}
-- both tests record two Power::infy: the count restarts per test (shared counting would give General::stop in the second) *)
Printinside a test is not captured: it goes to the output of the evaluator call, wolframscript's stdout, or the top of the TestReport tool's output.
Expected messages
The third argument is matched against the ordered list of recorded messages, with exact multiplicity:
#["Outcome"] & /@ {
VerificationTest[1/0, ComplexInfinity, {Power::infy}],
VerificationTest[Table[1/0, 2], {ComplexInfinity, ComplexInfinity}, {Power::infy}],
VerificationTest[Table[1/0, 2], {ComplexInfinity, ComplexInfinity}, {Power::infy ..}],
VerificationTest[Table[1/0, 5]; 7, 7, {Power::infy .., General::stop}],
VerificationTest[1/0, ComplexInfinity, {Message[Power::infy, HoldForm[1/0]]}],
VerificationTest[1/0, ComplexInfinity, {Message[Power::infy, _]}],
VerificationTest[Check[1/0, "chk"], "chk", {Power::infy}],
VerificationTest[Quiet[1/0], ComplexInfinity]}
(* {"Success", "MessagesFailure", "Success", "Success", "MessagesFailure", "Success", "Success", "Success"} *)
- List names in issue order with the exact count;
name ..means one or more. A message issued more than three times in a test is recorded three times plusGeneral::stop:{Power::infy .., General::stop}. - Do not write message arguments: 15.0 records kernel message arguments as
HoldCompleteForm[0^(-1)], so an older-styleMessage[Power::infy, HoldForm[1/0]]fails. Use_or copy the form verbatim from"ActualMessages". - The expected symbol must match exactly (
General::nodefdoes not match a message issued asf::nodef). - An outer
Quietinverts message outcomes: unexpected messages pass, expected ones fail. The remote MCP server evaluates every input underQuiet, so there wrap tests inQuiet[..., None, All]:
{Quiet[VerificationTest[1/0, ComplexInfinity]]["Outcome"],
Quiet[VerificationTest[1/0, ComplexInfinity, {Power::infy}]]["Outcome"],
Quiet[Quiet[VerificationTest[1/0, ComplexInfinity, {Power::infy}], None, All]]["Outcome"]}
(* {"Success", "MessagesFailure", "Success"} -- the first two are wrong; on the remote MCP server the plain tests give the same
wrong results, and Quiet[VerificationTest[...], None, All] gives the correct ones *)
Re-run one test
TestEvaluate[t] re-runs a TestObject (side effects happen again); TestReport[{t}] only re-reports it:
ClearAll[tsCount]; tsCount = 0;
With[{t = VerificationTest[++tsCount, 1]}, {t["Outcome"], TestEvaluate[t]["Outcome"], TestReport[{t}]["TestsSucceededCount"], tsCount}]
(* {"Success", "Failure", 1, 2} -- TestEvaluate ran the input again (tsCount 2), TestReport[{t}] did not *)
To run only some tests of a file, skip the others with a rule prepended to VerificationTest inside
Internal`InheritedBlock (top-level code and the tests you keep, e.g. setup tests, still run). TestReport's
TestEvaluationFunction option has no effect on files. OrderDep.wlt is
odMode = "fast" ("OD-Setup"), odMode = "slow" ("OD-ChangesMode"), and a test expecting odMode to be "fast"
("OD-ReadsMode", which fails in the full file):
Needs["MUnit`"]; (* first: VerificationTest is an autoload stub until MUnit is loaded *)
Internal`InheritedBlock[{VerificationTest},
Unprotect[VerificationTest];
PrependTo[DownValues[VerificationTest], HoldPattern[VerificationTest[___, TestID -> id_, ___]] /;
! StringMatchQ[First[StringSplit[id, "@@"]], "OD-Setup" | "OD-ReadsMode"] :> Null];
Protect[VerificationTest];
#["TestID"] -> #["Outcome"] & /@ TestReport[FileNameJoin[{testDir, "OrderDep.wlt"}], ProgressReporting -> False]["Results"]]
(* {"OD-Setup" -> "Success", "OD-ReadsMode" -> "Success"} *)
- Load MUnit first: if it autoloads inside the block, its definitions replace the filter and every test runs.
- Some projects append the source location to TestIDs (
"GetDefinitions@@Tests/YAML.wlt:4,1-9,2"= lines 4–9); match the part before@@, and use the suffix to find the source. - Helpers:
WolframDebugging`RunTestsByID[file, "MyTest"](with an option for setup tests; summary of the selected tests),WolframDebugging`TestSource[file, "MyTest"](the test's code and lines). - In a fresh kernel from the shell (no state from earlier runs), put the same code in a
-fscript and runtimeout -s KILL 300 wolframscript -f rerun.wls < /dev/null.
Reproduce a failing input with a stack
Take the held input from the TestObject and run it under a message handler that throws the stack at the first message
(the Replace keeps the input unevaluated until it runs inside the handler):
Module[{t = First[tstReport["ResultsByTestID"]["GeneralStop"]], tag, st},
st = Replace[t["Input"], HoldForm[in_] :> Catch[
Internal`HandlerBlock[{"Message", Replace[#, Hold[Message[_, ___], True] :> Throw[Stack[_], tag]] &},
StackBegin[StackComplete[in]]], tag]];
If[ListQ[st], Replace[st, _[e_] :> ToString[Unevaluated[e], InputForm, TotalWidth -> 100], {1}], st]]
(* {"StackComplete[Table[1/0, 5]; 7]", "Table[1/0, 5]; 7", "Table[1/0, 5]", "1/0", "0^(-1)",
"Message[Power::infy, HoldCompleteForm[0^(-1)]]", <3 frames of the handler>}
(the message is printed once here: outside the harness, $Messages is not blocked) *)
- A
Catchin the code under test can eat theThrow; then use a recording handler instead (seeMessagesAndStacks.md) orWolframDebugging`ReproduceTest[t](mirrors the harness: messages counted like the test, stack at the first one, nothing thrown). - For a wrong value, apply the other references' tools to the input (
UnevaluatedCalls.md,OverridesAndWatchpoints.md,TracingAndPerformance.md). Trace works in MCP Local and wolframscript, not inside the TestReport MCP tool. - Localize the wrong step inside one long test with
IntermediateTest:
With[{t = VerificationTest[Module[{a, b}, a = IntermediateTest[StringLength["abc"], 3, TestID -> "step-a"];
b = IntermediateTest[a + 1, 5, TestID -> "step-b"]; b*2], 8, TestID -> "multi-step"]},
{t["Outcome"], t["FailureType"], #[{"TestID", "Outcome", "ActualOutput"}] & /@ t["IntermediateTests"]}]
(* {"Failure", "IntermediateTestFailure", {<|"TestID" -> "step-a", "Outcome" -> "Success", "ActualOutput" -> HoldForm[3]|>,
<|"TestID" -> "step-b", "Outcome" -> "Failure", "ActualOutput" -> HoldForm[4]|>}} *)
Order dependence: passes alone, fails in the suite (or the reverse)
- Run the failing test alone with its setup tests in a fresh kernel (the filter recipe above in a wolframscript
file, or
RunTestsByID). Passes alone → an earlier test, or an earlier file in the same TestReport tool call, leaves state behind. Fails alone → it depends on state from an earlier test: add that test to the setup or make the test self-contained. - Find the culprit: record which symbols each test changed, using the
"FileStarted"and"TestEvaluated"events ofTestReport(hashes ofOwnValues/DownValuesof the user contexts and$ContextPath):
Module[{snap, before, changes = Internal`Bag[]},
snap[] := Join[<|"$ContextPath" -> Hash[$ContextPath]|>,
Association @ Map[# -> Hash[ToExpression[#, InputForm, Function[s, {OwnValues[s], DownValues[s]}, HoldAllComplete]]] &,
Select[Flatten[Function[c, c <> StringDelete[#, ___ ~~ "`"] & /@ Names[c <> "*"]] /@ DeleteDuplicates[{"Global`", $Context}]],
StringFreeQ["$" ~~ DigitCharacter ..]]]];
TestReport[FileNameJoin[{testDir, "OrderDep.wlt"}], ProgressReporting -> False,
HandlerFunctions -> <|"FileStarted" -> ((before = snap[]) &), "TestEvaluated" -> Function[Module[{now = snap[]},
Internal`StuffBag[changes, #TestObject["TestID"] -> Select[Keys[now], now[#] =!= Lookup[before, #] &]]; before = now]]|>];
Internal`BagPart[changes, All]]
(* wolframscript: {"OD-Setup" -> {"Global`odMode"}, "OD-ChangesMode" -> {"Global`odMode"}, "OD-ReadsMode" -> {}}
MCP evaluator (where an earlier run had left odMode = "fast"): {"OD-Setup" -> {}, "OD-ChangesMode" -> {"Sessions`<id>`odMode"}, "OD-ReadsMode" -> {}} *)
"OD-ChangesMode" changed odMode, which "OD-ReadsMode" reads. Run this in a fresh kernel: assigning a value a
symbol already had is not a change (the MCP evaluator result). Add your package's contexts to the list, and watch other
channels when needed (Hold[Messages[sym]] for Off[sym::tag], Options[f] for SetOptions). Note the parentheses
in ((before = snap[]) &): before = snap[] & would assign the function itself.
3. Or bisect: re-run the failing test with growing sets of the preceding tests, each in a fresh kernel.
Typical leak channels: values and definitions of shared symbols, Off[...], SetOptions, $ContextPath, handlers,
package-private flags and caches.
TestReport in the evaluator, in wolframscript and in the tool
| TestReport MCP tool | TestReport in MCP Local | in MCP Session | wolframscript | |
|---|---|---|---|---|
| kernel | fresh per call (-noinit) | the shared subkernel | the MCP server kernel | fresh per run |
$Context of test code | Global` | Sessions`<id>` | Sessions`<id>` | Global` |
| Trace inside tests | no | yes | no | yes |
| test messages in the output | hidden | hidden | shown (Chatbook's handler ignores the harness) + General::messages | hidden |
| evaluator time limit | none (per-test timeConstraint) | not enforced (see below) | not enforced | none |
| state left behind | none | yes, for every session | yes, in the server | none |
- The evaluator's time limit does not stop
TestReport. When it fires, the running (possibly passing) test fails with"EvaluationAbortedFailure"(both methods) and the remaining tests keep running past the limit (four 2-second tests under a 5-second limit took 7 s, the third one "failed", and the call returned its normal result). PassTimeConstraint -> ntoTestReportand treat such a failure as possibly caused by the tool limit. In MCP Local a call that is still running about 20 s after its limit gets the shared subkernel restarted, which loses every session's state (fifteen 2-second tests under a 5-second limit: only the time-out Failure, after 22 s). - Never run a project's whole test files in the MCP evaluator: their setup code (
PacletDirectoryLoad,Off[...],SetOptions, global flags) changes the shared kernel or the server. Use the TestReport tool or wolframscript; use the evaluator to reproduce single inputs. - wolframscript, compact (prints
{2, 8}forDemo.wlt):timeout -s KILL 300 wolframscript -code 'tr = TestReport["/abs/Foo.wlt", ProgressReporting -> False, TimeConstraint -> 30]; ToString[{tr["TestsSucceededCount"], tr["TestsFailedCount"]}, InputForm]' - In MCP Session, messages raised inside tests appear in the tool output (they are not failures of your call); read the outcomes instead.
CI-only failures: MX builds and ReadProtected
CI pipelines often test the built paclet, where an MX build may set ReadProtected on all package symbols. Code (or
tests) that read definitions with Definition, FullDefinition or Language`ExtendedFullDefinition then see
nothing, while DownValues still works. Emulate it locally before running the tests:
ClearAll[mxDemo`mean]; mxDemo`mean[l_List] := Total[l]/Length[l];
{ToString[Definition[mxDemo`mean], InputForm],
SetAttributes[Evaluate @ Names["mxDemo`*"], ReadProtected]; ToString[Definition[mxDemo`mean], InputForm],
Length[DownValues[mxDemo`mean]]}
(* {"mxDemo`mean[l_List] := Total[l]/Length[l]", "Attributes[mxDemo`mean] = {ReadProtected}", 1} *)
Use DownValues (or clear ReadProtected inside Internal`InheritedBlock, see DefinitionsAndSource.md) in code that
inspects definitions. Also check that the build under test is current: a stale build directory can shadow the source
(PackageLoading.md).
Gotchas
- Check "Total Tests" (or
Length[tr["Results"]]) against the number of tests in the file; read the text above the tool's summary. - Outcome strings are
"MessagesFailure","TimeConstrainedFailure","MemoryConstrainedFailure"(not the documented names); a wrong value hides messages in the outcome. - Never
ReleaseHoldtest values; never return report objects. Getand use in one test fails; load in an earlier test.- Expected messages: order and count matter,
General::stopcounts, no literal arguments; an outerQuiet(and the remote MCP server) inverts message outcomes. Needs["MUnit`"]before overridingVerificationTest;TestEvaluationFunctiondoes nothing for files.- Files of one TestReport tool call share a kernel; the evaluator time limit does not bound
TestReport. - MCP evaluator: tests run in
Sessions`<id>`, where your typed definitions are.
Tracing and performance
How to use Trace, TraceScan and their options without drowning in output, what to do where Trace is disabled
(MCP Session, the cloud), how to find where the time goes and where an evaluation is stuck with a stack
sampler, and what time limits can and cannot interrupt. Read it for "which code path ran", "why is this slow" and
"why does this hang or time out". Behavior was checked with Wolfram 15.0 in the environments named in Environments.md.
The examples use these definitions:
ClearAll[fib, hlp];
hlp[x_] := x^2;
fib[0] = 0; fib[1] = 1; fib[n_] := fib[n - 1] + hlp[fib[n - 2]];
Which tool for which question
| question | first choice | works where Trace is disabled |
|---|---|---|
which calls of f happened, with which arguments? | Trace[expr, _f]; rule form with early exit; WolframDebugging`TraceCalls[expr, _f, n] | no: use an Internal`InheritedBlock spy (OverridesAndWatchpoints.md) |
| how often is each function called? | Counts over Trace[expr, _f | _g]; WolframDebugging`CountCalls[expr, _f | _g] | WolframDebugging`TimeCalls[expr, {f, g}] |
| what does a system function call internally? | Trace[expr, form, TraceInternal -> True] | spy on the internal function |
| where does the time go? | stack sampler; WolframDebugging`SampleStacks[expr, maxSeconds] | yes |
| exact count and time per function | WolframDebugging`TimeCalls[expr, {f, g}] | yes |
| where is it stuck? | stack sampler (last samples); WolframDebugging`FindHang[expr, maxSteps] (Trace only) | sampler: yes |
| why is this numeric solver slow or diverging? | EvaluationMonitor, StepMonitor | yes |
| why did the call time out? | "Time limits" below | yes |
Helpers are in scripts/WolframDebugging.wl (load it with Get in its own call, call them fully qualified; options and
outputs: HelperFunctions.md). Every recipe below works without them.
Is Trace available here?
{Trace[1 + 2*3], CloudEvaluate[Trace[1 + 2*3]]}
(* {{{HoldCompleteForm[2*3], HoldCompleteForm[6]}, HoldCompleteForm[1 + 6], HoldCompleteForm[7]}, {}} *)
Trace, TraceScan, TracePrint and On[sym] work in MCP Local and wolframscript (notebooks: not checked here). They
silently record nothing in MCP Session (the default method of installed local servers), wolfram -script, CloudEvaluate, deployed
APIs and the remote MCP server: Trace returns {} and the TraceScan function is never called, so a TraceScan
step limiter never fires and an infinite loop runs into the tool's time limit. Check with Trace[1 + 1] =!= {}
(WolframDebugging`TraceAvailableQ[]) before relying on it. Where it is {}, use the workarounds below or the
Trace-free tools: message handlers with Stack (MessagesAndStacks.md), Internal`InheritedBlock spies and value
monitors (OverridesAndWatchpoints.md), and the stack sampler (below). (CloudEvaluate also works from MCP Local.)
Trace forms
Each item of a trace is wrapped in HoldCompleteForm in 15.0 (older versions: HoldForm). Match items with _[e_]
or (HoldCompleteForm | HoldForm)[e_]; never unwrap them with First, [[1]] or ReleaseHold, which re-evaluates
the item. Outputs in this section drop the wrappers for readability:
Trace[fib[3], _fib] (* calls that match, arguments already evaluated *)
Trace[fib[2], fib] (* bare symbol: each rewrite done by fib's own rules *)
Trace[fib[3], hlp[x_] :> {"arg", x}] (* rule: the rhs is evaluated at each match and replaces the item *)
Trace[fib[3], TraceDepth -> 1] (* only the top-level rewrite chain *)
(* {fib[3], {fib[2], {fib[1]}, {{fib[0]}}}, {{fib[1]}}}
{fib[2], fib[2 - 1] + hlp[fib[2 - 2]], {fib[1], 1}, {{fib[0], 0}}}
{{{{"arg", 0}}}, {{"arg", 1}}}
{fib[3], fib[3 - 1] + hlp[fib[3 - 2]], 1 + 1, 2} *)
Flatten[Trace[...]]gives the items in chronological order (Flattendoes not enterHoldCompleteForm).- A bare symbol
fas the form means "rewrites done by f's rules",_fmeans "expressions with head f". - In the rule form
lhs :> rhsthe rhs is evaluated at every match: use it as a callback (next section).
Options
Trace[fib[3], _hlp, TraceAbove -> True] (* who called it: the enclosing evaluation chains *)
Trace[fib[3], _hlp, TraceForward -> True] (* what each match evaluated to *)
Trace[fib[3], _Power, TraceBackward -> All] (* what produced each match *)
Trace[fib[2], _fib, TraceOriginal -> True] (* also the forms before their arguments were evaluated *)
Trace[fib[3], TraceOn -> _hlp] (* trace only inside hlp[...] evaluations *)
Trace[(1 + 1) + fib[3], TraceOff -> _fib] (* do not trace inside fib[...] evaluations *)
(* {fib[3], {fib[2], {hlp[0], 0}, 1}, {hlp[1], 1}, 2}
{{{hlp[0], 0}}, {hlp[1], 1}}
{{{hlp[0], 0^2}}, {hlp[1], 1^2}}
{fib[2], {fib[2 - 1], fib[1]}, {{fib[2 - 2], fib[0]}}}
{{{hlp[0], 0^2, 0}}, {hlp[1], 1^2, 1}}
{{1 + 1, 2}, {fib[3], 2}, 2 + 2, 4} *)
TraceForward -> All and TraceBackward -> True also exist; MatchLocalNames -> False stops a form x from
matching Module locals x$123. TraceOff also makes a trace faster (it skips the subcomputations), TraceDepth -> 1
is the cheapest "what did it rewrite to".
TraceInternal -> True: see inside system functions
ClearAll[key]; key[x_] := -x;
{Length[Flatten[Trace[SortBy[{3, 1, 2}, key], _key]]], Length[Flatten[Trace[SortBy[{3, 1, 2}, key], _key, TraceInternal -> True]]]}
Trace[URLParse["http://a.com/b?q=1"], _URLQueryDecode, TraceInternal -> True]
(* {0, 3}
{{{{{{{{{HoldCompleteForm[URLQueryDecode["q=1"]], {HoldCompleteForm[URLQueryDecode[{"q=1"}]]}}}}}}}}}} (the default finds nothing) *)
Without it, a trace does not show evaluations made by kernel code on your behalf: the key functions of SortBy,
GatherBy, MaximalBy, AssociationMap, Plot sample points, callbacks of compiled code, and helpers that system
packages (URLParse, DateString, ...) call internally. Calls made by Map, Select, Table, Fold, Nest,
GroupBy, Cases conditions, Dataset queries and NIntegrate (sample points of a _?NumericQ integrand) are
visible by default. With TraceInternal -> True an internal call can appear twice (before and after its arguments were
evaluated); use a form like f[_String, ___] to keep only evaluated calls.
Find the HTTP requests made by a high-level function (network access):
Cases[Flatten[Trace[ResourceUpdate["Gettysburg Address"], _URLFetch | _URLRead, TraceInternal -> True]],
_[(h : URLFetch | URLRead)[u_, ___]] :> ToString[Unevaluated[h[u]], InputForm]]
(* ResourceObject::newest: The most recent version of resource ... is already downloaded.
{"URLFetch[\"https://www.wolframcloud.com/obj/resourcesystem/api/1.0/AcquireResource\"]", (the same again)}
MCP Local shows URLFetch[CloudObject["https://.../AcquireResource"]] *)
Here the default TraceInternal -> Automatic finds the same two items (the request is made by top-level package code),
but TraceInternal -> True is the safe choice when you trace into system functions. The spy in
OverridesAndWatchpoints.md finds the same requests where Trace is disabled.
Streaming traces: stop early, count, keep the output small
The rule form is a callback that runs at each match; a Throw from it stops the evaluation. This collects the first
five calls of hlp as strings and stops:
Module[{bag = Internal`Bag[], k = 0, tag},
Catch[
Trace[fib[10], e : _hlp :> (Internal`StuffBag[bag, ToString[Unevaluated[e], InputForm]]; If[++k >= 5, Throw[Null, tag]])],
tag];
Internal`BagPart[bag, All]]
(* {"hlp[0]", "hlp[1]", "hlp[0]", "hlp[1]", "hlp[0]"} *)
Count calls per function:
Counts[Cases[Flatten[Trace[fib[10], _fib | _hlp]], _[h_Symbol[___]] :> SymbolName[Unevaluated[h]]]]
{Block[{c = 0}, TraceScan[c++ &, fib[10], _fib]; c], Block[{c = 0}, TraceScan[c++ &, fib[10], fib[_Integer]]; c]}
(* <|"fib" -> 177, "hlp" -> 88|>
{353, 177} *)
TraceScan (and TracePrint) report each call twice, before and after its arguments are evaluated (fib[10 - 1] and
fib[9]): count with Trace, or use a pattern such as fib[_Integer] that only matches evaluated arguments. A pattern
test does not help, because it evaluates its argument: fib[_?NumberQ] matches fib[10 - 1] too (353 again).
WolframDebugging`TraceCalls[expr, form, n] and WolframDebugging`CountCalls[expr, form] do both (they return
Failure["TraceUnavailable", ...] where Trace is disabled).
Collect with Internal`Bag and a Module-local tag, not with Sow or a plain tag:
ClearAll[usesReap, catchesAll];
usesReap[] := First[Reap[hlp[3]; 7]];
catchesAll[] := Catch[hlp[3]; "finished anyway", _];
{Reap[TraceScan[Sow[#, "mine"] &, usesReap[], _hlp], "mine"],
Module[{bag = Internal`Bag[]}, TraceScan[Internal`StuffBag[bag, #] &, usesReap[], _hlp]; Internal`BagPart[bag, All]],
Catch[Trace[catchesAll[], _hlp :> Throw["found", "mine"]], "mine"],
CheckAbort[TraceScan[Abort[] &, catchesAll[], _hlp], "stopped by Abort"]}
(* {{7, {}}, {HoldCompleteForm[hlp[3]]}, {}, "stopped by Abort"} *)
- An untagged
Reapinside the traced code swallows yourSow, even a tagged one ({7, {}}); the bag sees the call. - A
Catch[..., _](orCheckAll,EvaluationData) inside the traced code eats yourThrow: the evaluation goes on and you get its normal result ({}here). Real package code contains such catch-alls. Record without throwing, or stop withAbort[]insideCheckAbort. - Never return a raw trace or stack: a few hundred items are tens of kilobytes.
Shortdoes not shorten anything in MCP or wolframscript output; convert items withToString[Unevaluated[e], InputForm, TotalWidth -> n](see "Output budget" inEnvironments.md). Symbols whose context is not on$ContextPathprint with it: put"Global`"and$Contexton$ContextPathwhile formatting (the hang locator below does).
What Trace cannot show, and what it costs
- Built-in functions show only input and result (
Trace[Sort[{3, 1, 2}]]has two items). - Compiled code shows no inner steps, and the whole
CompiledFunctionorCompiledCodeFunctionexpression appears in the trace (large). ReadProtecteddoes not hide anything from Trace, but functions that are bothLockedandReadProtectedare opaque, even withTraceInternal -> True.- The first call of a function in a fresh kernel traces all the package loading it triggers: one
Trace[ExportString[<|"a" -> 1|>, "JSON"]]in a fresh wolframscript kernel had 15,467 items (118 MB), the second 995 items. Evaluate once before tracing unless the loading is what you investigate. - Cost (
fib[20]in wolframscript):Tracewith a narrow form took about 3.5 times the plain time,TraceScanabout 7 times (it streams, so memory stays flat: 7.5 KB); a fullTrace(about 33,000 calls) kept 17 MB. Narrow the form, useTraceOff, and stop early. TracePrintprints one line per item (a lot of output);TraceDialogenters aDialog[]: never use it in MCP.- The MCP evaluator's own code does not appear in traces made in MCP Local.
Where Trace is disabled: three workarounds
- A fresh local kernel with your definitions transferred (MCP Session, about 9 s; not available in MCP Local, which is protected mode, or in the cloud):
ClearAll[sq]; sq[x_] := x^2 + 1;
With[{defs = Language`ExtendedFullDefinition[sq]},
LocalEvaluate[Language`ExtendedFullDefinition[] = defs; ToString[Trace[sq[2]], InputForm]]]
(* "{HoldCompleteForm[sq[2]], HoldCompleteForm[2^2 + 1], {HoldCompleteForm[2^2], HoldCompleteForm[4]}, HoldCompleteForm[4 + 1], HoldCompleteForm[5]}" *)
Language`ExtendedFullDefinition includes the definitions sq depends on, including package contexts, but silently
drops ReadProtected symbols. For package code, Get the package inside the LocalEvaluate instead.
- A parallel subkernel traces even when the main kernel cannot (MCP Session; the call took about 9 s):
ClearAll[sq]; sq[x_] := x^2 + 1;
Module[{k = LaunchKernels[1]},
WithCleanup[DistributeDefinitions[sq]; First[ParallelEvaluate[ToString[Trace[sq[2]], InputForm], k]], CloseKernels[k]]]
(* "{HoldCompleteForm[Sessions`<id>`sq[2]], HoldCompleteForm[2^2 + 1], ..., HoldCompleteForm[5]}" *)
- Run the code in wolframscript from the shell (each run is a fresh kernel; see
Environments.md):
cat > "${TMPDIR:-/tmp}/trace_me.wls" <<'WL'
sq[x_] := x^2 + 1;
Print[ToString[Trace[sq[2]], InputForm]]
WL
timeout -s KILL 120 wolframscript -f "${TMPDIR:-/tmp}/trace_me.wls"
# {HoldCompleteForm[sq[2]], HoldCompleteForm[2^2 + 1], {HoldCompleteForm[2^2], HoldCompleteForm[4]}, HoldCompleteForm[4 + 1], HoldCompleteForm[5]}
Where does the time go?
Quick measurements:
{AbsoluteTiming[Pause[0.2]], Timing[Pause[0.2]], MaxMemoryUsed[Range[10^6];]}
EchoTiming[Pause[0.2]; 7]
GeneralUtilities`EchoPerformance[Total[Range[10^6]]]
(* {{0.200249, Null}, {0.003324, Null}, 8000264}
>> 0.201199 (prints, returns 7)
>> Total {0.001908 s, 8000760 B} (prints, returns 500000500000) *)
Timing is the CPU time of this kernel only (it excludes Pause, waiting for the network and other processes): use
AbsoluteTiming for wall-clock time and RepeatedTiming for short operations. Headless, Monitor only issues
FrontEndObject::notavail, PrintTemporary prints like Print, and GeneralUtilities`MonitoredMap prints raw box
junk: return measurements as values instead.
Sampling profiler (works everywhere)
A repeating ScheduledTask preempts the running evaluation and Stack[_] evaluated in the task sees the main
evaluation's stack. The share of samples in which a function is on the stack is its share of the (inclusive) time:
ClearAll[slowA, slowB, driver];
slowA[n_] := Module[{s = 0.}, Do[s += Sin[N[i]]^2, {i, n}]; s];
slowB[n_] := Module[{s = 0.}, Do[s += Cos[N[i]], {i, n}]; s];
driver[k_] := Table[slowA[60000] + slowB[20000], {k}];
Module[{bag = Internal`Bag[], task, samples},
task = SessionSubmit[ScheduledTask[Internal`StuffBag[bag, Stack[_]], {0.01, 2000}]];
TimeConstrained[StackBegin[StackComplete[driver[5]]], 10];
Quiet[TaskRemove[task]];
samples = Internal`BagPart[bag, All];
{Length[samples], Round[100. Counts[Flatten[Union[Cases[#, _[h_Symbol[___]] /; MemberQ[{"Global`", $Context}, Context[h]] :>
SymbolName[Unevaluated[h]], {1}]] & /@ samples]] / Length[samples]]}]
(* wolframscript: {56, <|"driver" -> 100, "slowA" -> 82, "slowB" -> 18|>}
MCP Local: {82, <|"driver" -> 100, "slowA" -> 80, "slowB" -> 20|>} *)
StackCompleteis required: without it every call of your functions is replaced on the stack by its right-hand side (driver[5]byTable[...]) and never shows up.StackBegindrops the frames of the environment's wrapper code.- The filter
MemberQ[{"Global`", $Context}, Context[h]]keeps your own functions in every environment (typed code is inSessions`<id>`in the MCP evaluator and inGlobal`in wolframscript); use a package context to profile a package. - Always give the task a repetition count and remove it: if the MCP tool limit fires first, the
TaskRemovenever runs, and in MCP Session a leftover task keeps sampling the server's own stack during later calls. - Return strings or counts, as above, never the samples: 50 samples of this profile were 370 KB.
WolframDebugging`SampleStacks[expr, maxSeconds]adds the innermost function, builtin shares and the last frames;WolframDebugging`TimeCalls[expr, {f, g}]gives exact call counts and inclusive seconds per function (it wraps the functions withInternal`InheritedBlock, so it works everywhere, but it misses calls answered by literal rules such asfib[0] = 0).
Packed-array unpacking
GeneralUtilities`TraceUnpacking[Total[Append[RandomReal[1, 10^5], "a"]]]
(* <|HoldCompleteForm[{100000}] -> 1|> dimensions of the arrays that were unpacked, and how often *)
It works everywhere (it uses a message handler with On["Packing"], not Trace) and returns the statistics, not the
result. To find where an array is unpacked, record Developer`FromPackedArray::punpack1 messages with their stacks
(MessagesAndStacks.md) inside WithCleanup[On["Packing"], expr, Off["Packing"]].
Profilers that do not work headless
RuntimeTools`Profile and the other RuntimeTools` functions belong to the notebook debugger: headless they stay
unevaluated or return no data, and RuntimeTools`SetExecutionState[{"RuntimeAnalysisTools" -> True}] crashes the
kernel (segmentation fault), as does Package`PackageInformation[]. Never probe unknown internals in a shared MCP
kernel; try them in a throwaway wolframscript. For per-line profiles and coverage of a package's source, see
"Instrumentation" in HeadlessAndCrashes.md.
Where is it stuck?
The same sampler locates a hang: run the code under an inner TimeConstrained and look at the last sample.
ClearAll[collatzLen];
collatzLen[n_] := Module[{k = 0, m = n}, While[m != 1, m = If[EvenQ[m], m/2, 3 m - 1]; k++]; k]; (* bug: 3 m - 1 *)
Module[{bag = Internal`Bag[], task, res},
task = SessionSubmit[ScheduledTask[Internal`StuffBag[bag, Stack[_]], {0.2, 20}]]; (* ALWAYS bound the repeat count *)
res = TimeConstrained[StackBegin[StackComplete[collatzLen[5]]], 2, $TimedOut]; (* stay below the tool limit *)
Quiet[TaskRemove[task]];
{res, Internal`BagLength[bag], Block[{$ContextPath = Join[{"Global`", $Context}, $ContextPath]},
Replace[TakeWhile[Internal`BagPart[bag, -1], FreeQ[#, HoldPattern[bag]] &],
_[e_] :> ToString[Unevaluated[e], InputForm, TotalWidth -> 70], {1}]]}]
(* {$TimedOut, 9, {"StackComplete[collatzLen[5]]", "collatzLen[5]", "Module[{k = 0, m = 5}, While[m != 1, m = <<1>>; k++]; k]",
"While[m$16877 != 1, m$16877 = If[<<3>>]; k$16877++]; k$16877", ..., "m$16877 = If[EvenQ[m$16877], m$16877/2, 3*m$16877 - 1]", "5"}} *)
It gave the same answer in MCP Local, MCP Session, wolframscript, wolfram -script, CloudEvaluate and on the remote
MCP server, as did the profiler above. TakeWhile[..., FreeQ[#, HoldPattern[bag]] &] drops the task's own frames. If
only about one sample arrived during the whole wait, the code is inside a call that cannot be interrupted (see "Time
limits").
TimeConstrained[expr, t, Stack[_]] does not work: the fail expression runs after the stack has unwound.
Where Trace works, a step limiter shows the last evaluation steps, including live values:
Module[{steps = 0, last = Internal`Bag[], tag},
If[Trace[1 + 1] === {}, "Trace is disabled here",
Catch[
TraceScan[
Function[item, Internal`StuffBag[last, Replace[item, _[e_] :> ToString[Unevaluated[e], InputForm, TotalWidth -> 60]]];
If[++steps >= 2000, Throw[Internal`BagPart[last, -4 ;; -1], tag]]],
collatzLen[5], _[___]];
"finished", tag]]]
(* {"m$16788 != 1", "7 != 1", "m$16788 = If[EvenQ[m$16788], <<2>>]; k$16788++", "m$16788 = If[EvenQ[m$16788], m$16788/2, 3*m$16788 - 1]"}
MCP Session: "Trace is disabled here" *)
The guard matters: without it the step counter never fires where Trace is disabled and the loop runs into the tool
limit. WolframDebugging`FindHang[expr, maxSteps] keeps a ring buffer and also reports the stack heads.
Runaway recursion: Block[{$RecursionLimit = 200, $IterationLimit = 1000}, expr] fails fast instead of at depth 1024 or
4096 iterations (in MCP Local first let the subkernel print an ordinary message; Environments.md); a stack at the $RecursionLimit::reclim message shows the recursion (MessagesAndStacks.md), and
res = Catch[..., _TerminatedEvaluation, ...]; ... contains the overflow (in the MCP evaluator a Catch that is the
whole input or sits directly inside If or With does not; Environments.md). While, FixedPoint and
NestWhile have no built-in limit: give them a maximum (FixedPoint[f, x, 1000]) or a TimeConstrained.
Numeric solvers: monitors
Block[{x}, Catch[FindRoot[Exp[x] == 0, {x, 1}, EvaluationMonitor :> If[x < -20, Throw[{"diverging", x}, "fr"]]], "fr"]]
Block[{x, n = 0}, {NIntegrate[1/Sqrt[x], {x, 0, 1}, EvaluationMonitor :> n++], n}]
Block[{x}, Last[Reap[FindRoot[Cos[x] == x, {x, 1}, StepMonitor :> Sow[x]]]]]
(* {"diverging", -21.}
{2.000000000000003, 131}
{{0.7503638678402439, 0.7391128909113617, 0.739085133385284, 0.7390851332151607}} *)
EvaluationMonitor runs at every function evaluation, StepMonitor at every accepted step (FindRoot, FindMinimum,
NMinimize, NDSolve, NIntegrate, ...). Some methods have no monitor support (NMinimize::noopmon): choose an
iterative Method. Localize the variable: after an earlier call had left x = Range[500], an unlocalized
FindRoot[..., {x, 1}] returned {{1, 2, ..., 500} -> 0.739...}. Do not return {x -> value} from Block[{x}, ...]:
the result is evaluated again after Block restores the outer x.
Time limits: what they can interrupt
With[{data = RandomReal[1, 2*10^7]},
{AbsoluteTiming[TimeConstrained[Pause[5], 0.5, "stopped"]],
AbsoluteTiming[TimeConstrained[Length[Sort[data]], 0.5, "stopped"]]}]
(* {{0.500411, "stopped"}, {1.697772, "stopped"}} MCP Local: {{0.500776, "stopped"}, {2.45265, "stopped"}} *)
TimeConstrained (and the MCP tool limit) | behavior |
|---|---|
Pause, loops, waiting URLRead/URLFetch, RunProcess (the child is killed), ReadLine on a process | stopped on time |
one long primitive (Sort of a huge list, Eigenvalues of 2500x2500: 8 s for a 2 s limit, N[Pi, 10^7]: 6.5 s for 1 s) | stopped only when it returns |
AbortProtect and WithCleanup setup and cleanup code | finishes first, then the abort happens |
Run[...], a blocked stdin read (InputString) | runs to its end (Run["sleep 3"] under a 1 s limit: 3 s, normal result) |
MemoryConstrained[expr, bytes, fail] | aborts after the allocation that crosses the limit (Range[10^8] under 1 MB still took 800 MB) |
URLRead and URLFetch have no default time-out. 10.255.255.1 below is an address that never answers:
{AbsoluteTiming[URLRead["http://10.255.255.1/", TimeConstraint -> 2]],
AbsoluteTiming[TimeConstrained[URLRead["http://10.255.255.1/"], 2, $TimedOut]],
AbsoluteTiming[TimeConstrained[URLRead["http://10.255.255.1/", TimeConstraint -> <|"Connecting" -> 1|>], 4, $TimedOut]],
AbsoluteTiming[TimeConstrained[URLRead["http://10.255.255.1/", TimeConstraint -> <|"Connect" -> 1|>], 4, $TimedOut]]}
(* URLRead::invhttp: Connection timed out after 2000 milliseconds.
URLRead::invhttp: Connection timed out after 1000 milliseconds.
MCP Local: {{2.110298, Failure["ConnectionFailure", <|"MessageTemplate" :> URLRead::iurl, ...|>]}, {2.112629, $TimedOut},
{1.111145, Failure["ConnectionFailure", ...]}, {4.115872, $TimedOut}} *)
The association form of TimeConstraint takes the keys "Connecting" and "Reading"; an unknown key such as
"Connect" is silently ignored (the outer limit stopped that call after 4 s). For URLFetch use
"ConnectTimeout" -> 5, "ReadTimeout" -> 10. wolframscript also prints Connecting… | Elapsed time 1s progress lines
while it waits. Import of a URL inside TimeConstrained turns the time-out into an abort of the whole evaluation
(a wolframscript script stops there); contain it with CheckAbort:
{CheckAbort[TimeConstrained[Import["http://10.255.255.1/", "String"], 2, $TimedOut], "aborted"], "next"}
(* {"aborted", "next"} *)
The MCP tool time limit
{Internal`TimeRemaining[], TimeConstrained[Internal`TimeRemaining[], 5]}
(* MCP Local: {59.999937, 4.999999} MCP Session: {59.999929, 4.999986} wolframscript: {Infinity, 4.999999} *)
Internal`TimeRemaining[] gives the seconds left of the innermost time limit, including the evaluator's (60 s by
default; the remote MCP server about 60 s, CloudEvaluate and deployed APIs 300 s). Wrap experiments in an inner
TimeConstrained[expr, t, $TimedOut] with t well below it, so that your own code returns the diagnostics:
- The limit covers the whole tool call. A normal time-out returns
Out[n]= Failure["EvaluationTimeExceeded", ...]with the Print output so far, skips the remaining inputs of the call and keeps the session's state (both methods). - MCP Local: if the code is inside a call that cannot be interrupted, the subkernel is killed about 20 s after the limit
and restarted (a 3 s limit returned after 22 s, a 10 s limit after 28 s): the Failure then arrives without
Out[n]=and all definitions (of every session) are gone. Check{$ProcessID, SessionTime[]}in the next call. - MCP Session: a call that cannot be interrupted blocks the server until it finishes.
AbortProtect[Pause[9]]with a 3 s limit then returned the Failure (after 9 s, state kept);Run["sleep 8"]with a 5 s limit returned its normal result after 8 s, and the later inputs of the call still ran. - A
ScheduledTaskyou started keeps running after a time-out; remove it (TaskRemove) or give it a repeat count. TestReportinside the evaluator: the evaluator's limit is absorbed by the test harness (an innocent test fails with"EvaluationAbortedFailure"in both methods) and the remaining tests run unbounded. PassTimeConstraint -> ntoTestReport(seeTesting.md).
More on hard hangs, Run versus RunProcess and killing stuck wolframscript kernels: HeadlessAndCrashes.md.
Unevaluated calls and the wrong rule firing
Why f[args] comes back unchanged, or a different definition than expected fires: checks that need no Trace (so they
work in every environment), the order in which rules are tried, and a catalog of verified causes with fixes. Read it
when a result contains calls such as f[2.5] that should have evaluated, or when a function returns a fallback value.
Behavior was checked with Wolfram 15.0 in MCP Local and wolframscript (MCP Session where stated).
Unevaluated, or failed?
- An unevaluated call means no rule matched (or a rule that only checks arguments declined, usually with a message
such as
f::argx). Nothing went "wrong" insidef; look at the patterns. $Failed,Failure[...]orMissing[...]means a rule matched and decided to fail: look at the messages and theFailureproperties (MessagesAndStacks.md).
FailureQ /@ {$Failed, Failure["x", <||>], Missing["NotFound"], sq[2.5]}
(* {True, True, False, False} *)
Find the stuck calls in a large result
Calls of your own functions that survive in a result are stuck. List them with whether the head has any definitions
(False: typo, wrong context, file not loaded; True: rules exist but none matched):
area[r_?NumericQ] := Pi r^2;
stuckRes = {area["4"], area[2], helpr[5], Lenght[{1}]};
Counts @ Cases[stuckRes, (s_Symbol)[___] /; MemberQ[{"Global`", $Context}, Context[s]] :>
{SymbolName[Unevaluated[s]], System`Private`HasAnyEvaluationsQ[s]}, {0, Infinity}]
(* <|{"area", True} -> 1, {"helpr", False} -> 1, {"Lenght", False} -> 1|> *)
Add your package contexts to the list. WolframDebugging`StuckCalls[result] gives counts per head, the shortest example
and hints such as similar names or the same name defined in another context.
Checks that work everywhere (no Trace)
price[x_Integer] := 10 x; price[x_Real /; x > 100] := "bulk"; price[s_String] := "parse " <> s;
price[20.]
(* price[20.] *)
{Keys @ DownValues[price],
Flatten @ Position[Keys @ DownValues[price], lhs_ /; MatchQ[Unevaluated @ price[20.], lhs], {1}, Heads -> False],
MatchQ[20., _Integer],
Replace[Unevaluated @ price[20.], {HoldPattern[price[x_Real]] :> {x > 100}, _ :> "no match"}],
{Context[price], Attributes[price], System`Private`HasAnyEvaluationsQ[price]},
Select[Names["*`price"], ToExpression[#, InputForm, System`Private`HasAnyEvaluationsQ] &]}
{{HoldPattern[price[x_Integer]], HoldPattern[price[x_Real /; x > 100]], HoldPattern[price[s_String]]}, rules in try order
{}, positions of the left-hand sides (with their tests and conditions) that match: none
False, one argument against one pattern
{False}, the condition's value for this call
{"Global`", {}, True}, context ("Sessions`<id>`" in the MCP evaluator), attributes, has definitions
{"price"}} every "price" that has definitions (a second one means shadowing); names in
$Context come without context
- Run the checks on the arguments as the function receives them (already evaluated, unless
fhas a Hold attribute). MatchQwith aDownValueskey checks the left-hand side only; conditions written on the right-hand side (f[x_] := body /; test) are not tested, and no rule body runs.- Always give
Replace[Unevaluated[f[...]], rules]a catch-all rule: when nothing matches,Replacereturns the call, which then evaluates (Replace[Unevaluated[1 + 1], x_Integer :> "int"]gives2). WolframDebugging`WhyNoMatch[f[args]]explains every rule (which argument fails which pattern, the value each test and condition returned, rules shadowed by earlier ones, similar names, other contexts) without evaluating any rule body and without changing definitions. It works whereTracerecords nothing.Trace[f[args]](only where it works: MCP Local, wolframscript) shows the conditions that ran, but not which pattern failed structurally.
The order in which rules are tried
ord[x_?NumericQ] := "numeric"; ord[x_Integer] := "integer"; ord[0] = "zero";
ord2[x_] := "any"; ord2[x_Integer] := "integer";
{Keys[DownValues[ord]], ord[0], ord[1], Keys[DownValues[ord2]], ord2[1]}
(* {{HoldPattern[ord[0]], HoldPattern[ord[(x_)?NumericQ]], HoldPattern[ord[x_Integer]]}, "zero", "numeric",
{HoldPattern[ord2[x_Integer]], HoldPattern[ord2[x_]]}, "integer"} *)
DownValues[f]lists the rules in the order they are tried.- Literal rules (
f[0] = ..., memoized values) come first. - Pattern rules are sorted by specificity when the kernel can compare them (
x_Integerbeforex_); otherwise they keep definition order (x_?NumericQstays beforex_Integer, soord[1]gives"numeric"). - UpValues of the arguments are tried before any DownValue, even a literal one:
lt[up[1]] = "literal DownValue"; up /: lt[up[x_]] := "UpValue";
lt[up[1]]
(* "UpValue" *)
- Assigning the list keeps your order (use this to force a rule first, or
Prependa rule insideInternal`InheritedBlockfor a temporary probe, seeMessagesAndStacks.md):
DownValues[ord2] = Reverse[DownValues[ord2]];
{Keys[DownValues[ord2]], ord2[1]}
(* {{HoldPattern[ord2[x_]], HoldPattern[ord2[x_Integer]]}, "any"} *)
f[a][b]usesSubValues[f](afterf[a]itself failed to evaluate);HoldAllCompletefunctions ignore UpValues.
Catalog of causes
Each example was evaluated as written; "stays" means the call is returned unevaluated.
| cause | example | result | fix |
|---|---|---|---|
| Integer pattern, Real or Rational argument | sq[x_Integer] := x^2; {sq[2.5], sq[1/2]} | both stay | x_?NumericQ, x_Real, or convert first |
NumberQ is False for exact constants | nq[x_?NumberQ] := N[x]; nq[Pi] | stays | _?NumericQ |
test does not return exactly True | pos[x_?(# > 0 &)] := x; pos[a]; isPos[x_?(If[# > 0, 1, 0] &)] := x; isPos[5] | both stay (a > 0 and 1 are not True) | tests must return True/False (TrueQ) |
| condition uses a symbol with no value | big[x_] /; x > cutoff := "big"; big[3] | stays (3 > cutoff); "big" once cutoff = 1 | define or pass the value |
options without OptionsPattern[] | opt1[x_] := x; opt1[1, "Verbose" -> True] | stays | opt1[x_, OptionsPattern[]] |
| positional argument after the options start | Options[opt2] = {"A" -> 1}; opt2[x_, OptionsPattern[]] := {x, OptionValue["A"]}; opt2[1, 2, "A" -> 3] | stays | add a pattern for it |
| unknown option name | opt2[1, "B" -> 2] | matches anyway: {1, 1} + OptionValue::nodef | fix the name |
| a list where a sequence is expected | pair[x_, y_] := {x, y}; pair[{1, 2}] | stays | pair @@ {1, 2} |
y_. without a Default | dflt[x_, y_.] := {x, y}; dflt[1] | stays | y_ : 0 |
| a typed default is not checked | td[x_, y_Integer : 1.5] := {x, y}; td[1] | {1, 1.5} | check inside the body |
| repeated pattern name needs identical values | same[x_, x_] := x; same[1, 1.] | stays (1 and 1. are not SameQ) | same[x_, y_] /; x == y |
| Hold attribute plus a typed pattern | SetAttributes[hl, HoldAll]; hl[x_Integer] := x; hl[1 + 1] | stays (1 + 1 is a Plus) | hl[Evaluate[1 + 1]] → 2, or test inside |
_List given an Association or SparseArray (atomic objects) | len[x_List] := Length[x]; len[Association["a" -> 1]], len[SparseArray[{1, 0, 2}]] | both stay | _Association; len[Normal[SparseArray[{1, 0, 2}]]] → 3 |
| string pattern in an ordinary pattern | url[s : ("http" ~~ ___)] := s; url["http://x"] | stays | url[s_String /; StringStartsQ[s, "http"]] |
= (Set) evaluated the right-hand side once | rad = 5; area2[rad_] = Pi rad^2; Clear[rad]; {area2[1], area2[7]} | {25 Pi, 25 Pi} | := |
| stale memoized values after redefining | memo[x_] := memo[x] = x^2; memo[3]; memo[x_] := memo[x] = x^3; memo[3] | 9 (old literal rule wins) | Clear[memo] before redefining |
| same left-hand side defined again | dup[x_] := "first"; dup[y_] := "second"; dup[1] | "second", one rule left (pattern names do not matter) | add a condition or a different pattern |
| typo in a lower-case name | totalCost[x_] := 2 x; totalcost[3] | stays, no warning | (the MCP evaluator warns only for undefined upper-case names) |
| general rule tried first | kind[x_?NumericQ] := "numeric"; kind[x_Integer] := "integer"; kind[1] | "numeric" | define the specific rule first, or add conditions |
KeyValuePattern with an outer condition | kv[KeyValuePattern[{"ok" -> True, "url" -> u_String}]] /; StringStartsQ[u, "http"] := u; kv[_] := "fallback", called with an association whose "url" is "https://x" | "fallback" | see the next section |
| inner condition uses a sibling variable | sib[x_, y_ /; y > x] := {x, y}; sib[1, 5] | stays (x is not bound inside y_ /; ...) | sib[x_, y_] /; y > x |
OptionValue["A"] in a left-hand-side condition | ov[x_, OptionsPattern[]] /; OptionValue["A"] > 1 := "big A"; ov[x_, OptionsPattern[]] := "small A"; ov[1, "A" -> 2] (with Options[ov] = {"A" -> 1}) | "small A" | see "Conditions" below |
/; inside If, Enclose, Catch, Quiet, ... | ce[x_] := Enclose[x /; x > 0]; ce[-1]; ifc[x_] := If[x > 0, "pos" /; True, "neg"]; ifc[1] | -1 /; -1 > 0, "pos" /; True (the rule fired) | put the condition on the left-hand side, or directly in the body of Module/With/Block |
Flat head matches a subsequence | SetAttributes[fl, Flat]; fl[x_Integer, y_Integer] := x + y; fl[1, 2, 3] | 6 | expected for Flat |
Orderless sorts the arguments first | SetAttributes[ol, Orderless]; ol[a_, b_] := {a, b}; ol[2, 1] | {1, 2} | expected for Orderless |
Listable with unequal lengths | SetAttributes[ls, Listable]; ls[x_, y_] := x + y; ls[{1, 2}, {1, 2, 3}] | Thread::tdlen, then the rule runs on the lists: {1, 2} + {1, 2, 3} | fix the lengths |
SubValues argument mismatch | sv[a_Integer][b_String] := {a, b}; sv[1][2] | stays | |
UpValue ignored by HoldAllComplete | SetAttributes[hac, HoldAllComplete]; up2 /: hac[up2[x_]] := "up"; hac[up2[1]] | stays | define a DownValue for hac |
| pure function with the wrong arity | fn = Function[{x, y}, x + y]; fn[1]; fs = #1 + #2 &; fs[1] | stays + Function::fpct; 1 + #2 + Function::slotn | |
| built-in called with the wrong arguments | StringTake["abc"] | stays + StringTake::argr | Lookup[SyntaxInformation[StringTake], "ArgumentsPattern"] → {_, _} |
KeyValuePattern with an outer condition
When an outer /; (on the left-hand side or the right-hand side) uses a variable bound in the second or a later element
of a KeyValuePattern, the condition is first evaluated with that variable missing (Sequence[]), and the rule only
applies if that evaluation also returns True:
kvSeen = {};
kvTest[v___] := (AppendTo[kvSeen, {v}]; MatchQ[{v}, {_Integer}]);
kv5[KeyValuePattern[{"a" -> 1, "b" -> v_}]] /; kvTest[v] := {"hit", v};
kv5[_] := "fallback";
{kv5[<|"a" -> 1, "b" -> 2|>], kvSeen}
(* {"fallback", {{}}} -- the condition ran once, with no argument *)
So v > 0 happens to work (Greater[0] is True), StringStartsQ[u, "http"] fails silently (it becomes the operator
form StringStartsQ["http"]), and IntegerQ[v] fails with IntegerQ::argx. Trace shows the condition called without
the argument (kvTest[]), or nothing when that form is inert. Variables bound in the first element work. Fixes:
kv2[KeyValuePattern[{"ok" -> True, "url" -> u_String /; StringStartsQ[u, "http"]}]] := u;
kv3[(KeyValuePattern[{"ok" -> True, "url" -> u_String}] /; StringStartsQ[u, "http"])] := u;
kv4[json : KeyValuePattern[{"ok" -> True}]] /; StringStartsQ[Lookup[json, "url", ""], "http"] := json["url"];
With[{a = <|"ok" -> True, "url" -> "https://x"|>}, {kv2[a], kv3[a], kv4[a]}]
(* {"https://x", "https://x", "https://x"} *)
ReplaceList has a related problem: it binds only the first element's variables.
{ReplaceList[<|"a" -> 1, "b" -> 2|>, KeyValuePattern[{"a" -> w_, "b" -> v_}] :> {w, v}],
Replace[<|"a" -> 1, "b" -> 2|>, KeyValuePattern[{"a" -> w_, "b" -> v_}] :> {w, v}]}
(* {{{1}}, {1, 2}} *)
Conditions on the right-hand side, and OptionValue
body /; testis a rule condition only directly on the right-hand side, as the last statement of aCompoundExpression, or directly in the body ofModule,WithorBlock(also nested,With[..., Module[..., body /; test]]). There the scoping initializers run first:mod[x_] := Module[{y = x^2}, "big" /; y > 10]; mod[x_] := "small"gives{mod[2], mod[5]}→{"small", "big"}. InsideIf,Enclose,Catch,Quiet,Check,WithCleanupor aFunctionthe rule fires and returns a literala /; b.OptionValue["A"](short form) is not resolved inside a left-hand-side condition. Name the options or move the condition to the right-hand side:
Options[ov2] = {"A" -> 1};
ov2[x_, opts : OptionsPattern[]] /; OptionValue[ov2, {opts}, "A"] > 1 := "big A";
ov2[x_, OptionsPattern[]] := "small A";
ov3[x_, OptionsPattern[]] := "big A" /; OptionValue["A"] > 1;
ov3[x_, OptionsPattern[]] := "small A";
Options[ov3] = {"A" -> 1};
{ov2[1, "A" -> 2], ov3[1, "A" -> 2], ov3[1]}
(* {"big A", "big A", "small A"} *)
The call refers to a different symbol (contexts)
The head you call is not the symbol you defined. Context[f] and the Names check above reveal it.
- Same input as the load:
Get["ShadowDemo.wl"]; {pkgFn[1], Context[pkgFn]}as one input (one line of a tool call or-ffile, or one-codestring) gives{Global`pkgFn[1], "Global`"}(Sessions`<id>`in the MCP evaluator) andpkgFn::shdw: the input is parsed beforeGetruns, sopkgFnwas created in your context. Load on its own line: later lines, also later lines of the same tool call, are parsed after the load and reachShadowDemo`pkgFn({pkgFn[1], Context[pkgFn]}→{2, "ShadowDemo`"}). The leftover symbol in your context can be removed withRemove["Global`pkgFn"](Remove[Evaluate[$Context <> "pkgFn"]]in the MCP evaluator). - Another evaluator session: each MCP evaluator session has its own
Sessions`<id>`. A definition made in another session is invisible (sessF[1]stayed unevaluated; the definition wasSessions`<other id>`sessF). Reuse the session id. - Private package functions:
Pkg`Private`helperis not reachable ashelper; call it by its full name (ShadowDemo`Private`pkgHelper[1]→2, whilepkgHelper[1]stays). - Typos: the MCP evaluator (both methods) warns about undefined upper-case symbols of your session before evaluating
(
Symbol::undefined: Warning: Global symbol Lenght is undefined.), never about lower-case ones, and not about symbols defined or localized in the same input.
Built-ins and argument checks of your own
Kernel functions have no inspectable rules: read the message (::argx, ::argr, ::argt, ::argb for argument counts,
::nonopt, ::optx for options) and Lookup[SyntaxInformation[f], "ArgumentsPattern"]. System packages report wrong
argument counts with a rule that issues a message in its condition and then fails, so the call stays unevaluated with an
explanation; you can do the same:
chk[args___] := Null /; (CheckArguments[chk[args], 1]; False);
chk[x_Integer] := x^2;
{chk[3], chk[1, 2], chk[2.5]}
(* chk::argx: chk called with 2 arguments; 1 argument is expected.
{9, chk[1, 2], chk[2.5]} *)
Compiled code
cf = Compile[{{x, _Real}}, x^2 + 1]:cf[1, 2]stays unevaluated withCompiledFunction::cfct;cf["a"]issuesCompiledFunction::cfsaand falls back to uncompiled evaluation, returning1 + "a"^2(not an unevaluated call).fc = FunctionCompile[Function[Typed[x, "MachineInteger"], x + 1]]:fc[2.5]returnsFailure["ArgumentType", ...]withCompiledCodeFunction::argtype,fc[1, 2]returnsFailure["ArgumentCount", ...]withCompiledCodeFunction::argx(the firstFunctionCompilein a kernel took about 10 s).- Calling a
Failureobject (for example a failedFunctionCompileresult) givesMissing["NotAvailable", arg]:Failure["TypeError", <||>][1]→Missing["NotAvailable", 1].
Getting the Wolfram Engine
The bundled scripts in this skill require wolframscript, the command-line interface to the Wolfram Language. This guide covers installation on each platform.
Check If Already Installed
Run the following in your terminal:
wolframscript -code '1+1'
If it prints 2, you're ready to go — no further setup needed.
macOS
Via Homebrew (recommended)
brew install --cask wolfram-engine
After installation, wolframscript should be available on your PATH automatically.
Manual Download
- Download the Wolfram Engine from https://www.wolfram.com/engine/.
- Open the
.dmgand drag Wolfram Engine to Applications. - Run the app once to complete activation.
wolframscriptis installed at/usr/local/bin/wolframscript.
Linux
- Download the
.shinstaller from https://www.wolfram.com/engine/. - Run:
sudo bash WolframEngine_*_Linux.sh - Follow the prompts and activate when complete.
After installation, wolframscript is typically at /usr/bin/wolframscript.
Windows
- Download the installer from https://www.wolfram.com/engine/.
- Run the
.exeinstaller and follow the prompts. - Activate when prompted.
wolframscript.exeis added to your PATH automatically. If not, the default location is:C:\Program Files\Wolfram Research\WolframScript\wolframscript.exe
Activation
The Wolfram Engine is free for development use but requires activation with a Wolfram Account. If you don't have one, create an account at https://account.wolfram.com.
When you first run wolframscript, it will prompt for activation. You can also activate manually:
wolframscript -activate
Troubleshooting
wolframscriptnot found — Ensure the install directory is on your PATH. You can check the location withwhich wolframscript(macOS/Linux) orwhere wolframscript(Windows).- Activation fails — Check your internet connection and verify your Wolfram Account credentials at https://account.wolfram.com.
- License issues — The free Wolfram Engine license covers non-production development use. For production or commercial use, see https://www.wolfram.com/engine/commercial-options/.
More Information
- Wolfram Engine: https://www.wolfram.com/engine/
- Wolfram Account: https://account.wolfram.com
Script Reference
Auto-generated reference for bundled scripts. Pass --usage to any
script for the latest argument documentation.
WolframLanguageContext.wls
Uses semantic search to retrieve information from various sources that can be used to help write Wolfram Language code. Always use this tool at the start of new conversations or if the topic changes to ensure you have up-to-date relevant information. This uses semantic search, so the context argument should be written in natural language (not a search query) and contain as much detail as possible.
Usage:
wolframscript -f scripts/WolframLanguageContext.wls <context>
Arguments:
| Argument | Required | Description |
|---|---|---|
context | Yes | A detailed summary of what the user is trying to achieve or learn about. |
WolframLanguageEvaluator.wls
Evaluates Wolfram Language code for the user in a Wolfram Language kernel. Do not ask permission to evaluate code. You have read access to local files. Always use the Wolfram context tool before using this tool to make sure you have the most up-to-date information.
Use \[FreeformPrompt]["query"] to parse natural language into Wolfram Language expressions (like ctrl+= in notebooks). Always use this for Quantity, Entity, EntityClass, etc. It composes freely: ColorNegate[\[FreeformPrompt]["picture of a cat"]].
Examples:
\[FreeformPrompt]["France population"] (* Entity property value *)
\[FreeformPrompt]["123 terawatt hours"] (* Quantity *)
The argument MUST be a string literal -- it parses before evaluation, so runtime construction will not work.
Usage:
wolframscript -f scripts/WolframLanguageEvaluator.wls <code> [--timeConstraint value] [--session value]
Arguments:
| Argument | Required | Description |
|---|---|---|
code | Yes | The Wolfram Language code to evaluate. |
--timeConstraint | No | The time constraint for the evaluation. Uses the server's configured default if not specified. |
--session | No | An opaque session ID returned by a previous call to this tool. Pass it to continue that conversation's isolated session (its definitions, line numbers, and history). Omit it to start a new session; the response returns a new ID that you should reuse on subsequent calls in this conversation. |
SymbolDefinition.wls
Retrieves the definitions of one or more Wolfram Language symbols and returns them in a readable markdown format. The tool generates clean, formatted definition strings by intelligently managing the context path to minimize fully qualified symbol names.
Use fully qualified symbol names (e.g., SystemPlus, WolframAgentTools`CreateMCPServer) if the context is known.
Multiple symbols can be requested by separating them with commas.
Usage:
wolframscript -f scripts/SymbolDefinition.wls <symbols> [--includeContextDetails value] [--maxLength value]
Arguments:
| Argument | Required | Description |
|---|---|---|
symbols | Yes | The symbol name (or multiple names, comma separated). |
--includeContextDetails | No | Whether to include a JSON map showing which symbols belong to which contexts (default: false). |
--maxLength | No | Maximum character length for output before truncation (default: 10000). |
TestReport.wls
Runs Wolfram Language test files (.wlt) and returns a report of the results
Usage:
wolframscript -f scripts/TestReport.wls <paths> [--timeConstraint value] [--memoryConstraint value] [--newKernel value]
Arguments:
| Argument | Required | Description |
|---|---|---|
paths | Yes | Comma separated list of paths to Wolfram Language test files (.wlt) or directories of test files |
--timeConstraint | No | An optional time constraint (in seconds) for each test file |
--memoryConstraint | No | An optional memory constraint (in bytes) for each test file |
--newKernel | No | Whether to use a fresh kernel for running tests (default is true) |
CodeInspector.wls
Inspects Wolfram Language code using the CodeInspector package and returns a formatted report of issues found. The tool supports inspecting code strings, individual files, or entire directories of Wolfram Language source files.
Usage:
wolframscript -f scripts/CodeInspector.wls [--code value] [--file value] [--tagExclusions value] [--severityExclusions value] [--confidenceLevel value] [--limit value]
Arguments:
| Argument | Required | Description |
|---|---|---|
--code | No | Wolfram Language code string to inspect. |
--file | No | File or directory path to inspect. For directories, recursively inspects all .wl, .m, and .wls files. |
--tagExclusions | No | Comma-separated list of tags to exclude (e.g., "UnusedVariable,SuspiciousSessionSymbol"). |
--severityExclusions | No | Comma-separated list of severities to exclude. Default: "Formatting,Scoping". Available: Fatal, Error, Warning, Scoping, Remark, Formatting. |
--confidenceLevel | No | Minimum confidence level (0.0 to 1.0). Default: 0.75. Issues below this confidence are excluded. |
--limit | No | Maximum number of issues to display. Default: 100. |
Setting Up the Wolfram MCP Server
This guide explains how to connect your client to a Wolfram MCP server. With an MCP server you call the Wolfram tools directly instead of running the bundled scripts. A local server also keeps one Wolfram Language session alive between calls (definitions persist, and no kernel has to start for each call) and provides more tools.
There are two options:
| Wolfram Local MCP | Wolfram Cloud MCP | |
|---|---|---|
| Requires | A local Wolfram installation (Wolfram Engine, Wolfram, or Mathematica) | Nothing: free, no subscription or API key |
| Tools | Depends on the toolset (Step 3) | WolframContext, WolframLanguageEvaluator, WolframAlpha |
| Evaluation | Persistent session | Stateless, 60-second default time limit |
| Agent skills | DeployAgentTools installs them with the server | Not included |
Use the local server for coding agents and for anything that needs heavy computation, notebooks, tests, or paclet tools. Use Wolfram Cloud MCP when there is no local Wolfram installation and the user does not want to install one.
Both options change the user's client configuration, so ask the user before setting either one up. Also ask which toolset they want if the context does not make it clear. New MCP servers appear only after the client is restarted or reloaded, so the tools will not show up in your current session.
Option 1: Wolfram Local MCP
Step 1: Check for wolframscript
wolframscript -code '$VersionNumber'
If wolframscript is not found, read GetWolframEngine.md (in this references/ directory) or use Option 2. Current versions of AgentTools require Wolfram 15.0 or later.
The commands below are written for a POSIX shell. On Windows, shell quoting can mangle the double quotes in the code. To avoid that, put the code in a .wls file, wrap each result in Print[...], and run wolframscript -f file.wls.
Step 2: Install or update the AgentTools paclet
wolframscript -code 'PacletInstall["Wolfram/AgentTools", UpdatePacletSites -> True]["Version"]'
wolframscript -code 'Wolfram`AgentTools`AgentToolsObject["WolframLanguage"]["AgentSkillNames"]'
Wolfram 15 includes an older built-in copy of AgentTools. The first command installs the latest version, and Wolfram uses that version from then on. The second command should print {wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging}. If it prints {}, or the expression comes back unevaluated, the installed AgentTools cannot install agent skills. In that case use InstallMCPServer (Step 5).
Step 3: Choose a toolset
| Toolset | MCP tools | Agent skills installed by DeployAgentTools |
|---|---|---|
Wolfram | WolframContext, WolframLanguageEvaluator, WolframAlpha | wolfram-language, wolfram-alpha, wolfram-debugging |
WolframAlpha | WolframAlphaContext, WolframAlpha | wolfram-alpha |
WolframLanguage | WolframLanguageContext, WolframLanguageEvaluator, ReadNotebook, WriteNotebook, SymbolDefinition, CodeInspector, TestReport | wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging |
WolframPacletDevelopment | The WolframLanguage tools plus CreateSymbolDoc, EditSymbolDoc, EditSymbolDocExamples, CheckPaclet, BuildPaclet, SubmitPaclet | wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging |
- Use cases:
Wolframis for general computation and knowledge,WolframAlphafor Wolfram|Alpha queries only, andWolframLanguagefor Wolfram Language development.WolframPacletDevelopmentadds tools for writing documentation pages and for checking, building, and submitting paclets. - Tools: the
*Contexttools are semantic search (WolframAlphaContextover Wolfram|Alpha,WolframLanguageContextover Wolfram Language documentation and resources,WolframContextover both).ReadNotebook/WriteNotebookconvert notebooks (.nb) to and from markdown,SymbolDefinitionretrieves symbol definitions,CodeInspectorreports code issues, andTestReportruns.wlttest files. - Default toolset: without a toolset argument, the client's default is used:
Wolframfor Claude Desktop, Goose, and LM Studio, andWolframLanguagefor every other client. - One toolset per client: all four toolsets use the MCP configuration key
Wolfram, so a client (at a given user or project level) has only one of them. Switch withOverwriteTarget -> True, or use"MCPServerName"(Step 5) to install two side by side. - LLMKit: the context tools work best with an LLMKit subscription.
WolframAlphaContextrequires one, so installing theWolframAlphatoolset fails withLLMKitRequiredunless the kernel is connected to the Wolfram Cloud with an account that has LLMKit (useWolframinstead). For the other toolsets, anLLMKitSuggestedwarning is informational only.
Step 4: Choose DeployAgentTools or InstallMCPServer
DeployAgentTools is the recommended way. It installs the toolset's MCP server and its agent skills as one tracked deployment, which DeleteObject can remove again. InstallMCPServer writes only the MCP server configuration. Use it only when the MCP server is all that should be installed.
You are reading this from a Wolfram skill that is already installed, so check two things first:
- Existing deployments: run
wolframscript -code 'DeployedAgentTools[]'. If your client and location already have a deployment, the server is already configured. Ask the user to restart the client, or redeploy withOverwriteTarget -> Trueto switch toolsets or to add the skills that an older AgentTools did not install. - Where this skill is installed: this is the directory that contains this
references/folder. Compare its parent directory with the skills directory thatDeployAgentToolswill use (Supported Clients).
Use DeployAgentTools when this skill is already in that directory (same client, same user or project scope), or when no Wolfram skills are installed yet. It handles existing skills safely:
- An identical copy is adopted as is, and
DeleteObjectnever deletes a skill directory that existed before the deployment. - A copy with different content (installed by hand or by another tool, or a deployed copy that the user modified) is left untouched. The MCP server and the other skills are still installed, and the warning
DeployAgentTools::AgentSkillNotInstallednames the skipped skill. - Copies installed by an earlier deployment are updated to the current AgentTools version automatically; a newer copy that another deployment still uses is never downgraded. (Replacing a deployment for the same client and location still needs
OverwriteTarget -> True.)
Use InstallMCPServer, or DeployAgentTools with "SkillsDirectory" -> None (only the MCP server, still tracked as a deployment), when:
- The user only wants the MCP server, or Step 2 showed that the installed AgentTools has no agent skills.
- The Wolfram skills are installed somewhere that
DeployAgentToolsdoes not manage, but that your client also reads.DeployAgentToolswould add a second copy, and the client would see each skill twice. Examples: a Claude Code plugin (a path under~/.claude/plugins/); another skills directory that your client loads, such as~/.agents/skillsor~/.claude/skillsfor a client that also reads those; or the project's skills directory while you deploy at user level (a project-level deployment also works there if the client supports project MCP configuration).
Never use OverwriteTarget -> All without asking the user. It replaces skill directories that the deployment does not own and discards any changes in them.
Step 5: Install the server
DeployAgentTools, DeployedAgentTools, and AgentToolsDeployment are built-in symbols, so they need no context prefix:
# The client's default toolset, at user level
wolframscript -code 'DeployAgentTools["ClaudeCode"]'
# A specific toolset, at project level (the project's MCP configuration and skills directory)
wolframscript -code 'DeployAgentTools[{"ClaudeCode", "/path/to/project"}, "WolframLanguage"]'
# Only the MCP server, as a tracked deployment
wolframscript -code 'DeployAgentTools["ClaudeCode", "WolframLanguage", "SkillsDirectory" -> None]'
# Replace the Wolfram toolset already deployed for this client and location
wolframscript -code 'DeployAgentTools["ClaudeCode", "Wolfram", OverwriteTarget -> True]'
- Result: an
AgentToolsDeployment[...]. The first run can take a few minutes while the context tools download their search indexes, so use a generous command timeout. - Clients without agent skills support (Claude Desktop, LM Studio, Amazon Q Developer) get only the MCP server.
- Project level without project MCP support: the client gets only the project skills, with an
MCPServersNotDeployedwarning. Add the server at user level withInstallMCPServer. DeploymentExists: a Wolfram toolset is already deployed for that client and location. UseOverwriteTarget -> Trueto replace it.DeployAgentTools[All]deploys to every supported client, installed or not. Do not use it unless the user asks.- Removing:
DeleteObject /@ Select[DeployedAgentTools["ClaudeCode"], #["Scope"] === "Global" && #["Toolset"] === "WolframLanguage" &]removes the user-level deployment. For a project deployment, match#["Scope"] === File["/path/to/project"](the absolute project path) instead; without a scope test, every project's deployment of that toolset is removed too. Skills that another deployment still uses, that were modified, or that existed before the deployment are kept.
InstallMCPServer needs the full context name:
wolframscript -code 'Wolfram`AgentTools`InstallMCPServer["ClaudeCode", "WolframLanguage"]'
wolframscript -code 'Wolfram`AgentTools`InstallMCPServer[{"ClaudeCode", "/path/to/project"}, "WolframLanguage"]'
wolframscript -code 'Wolfram`AgentTools`UninstallMCPServer["ClaudeCode", "WolframLanguage"]'
InstallMCPServer is not tracked by DeployedAgentTools. It replaces whatever Wolfram server is already configured under the key Wolfram.
Both functions accept these options:
"ToolOptions" -> <|"WolframLanguageEvaluator" -> <|"TimeConstraint" -> 120|>|>: per-tool settings."SubmitUsageData" -> False: opts out of usage data collection, which the built-in servers do by default."MCPServerName" -> "WolframDev": uses a different configuration key, so that two Wolfram toolsets can be installed side by side.
Step 6: Restart the client
Ask the user to restart or reload the client. The tools then appear under the server name Wolfram, for example mcp__Wolfram__WolframLanguageEvaluator in Claude Code. When they are available, use them instead of the bundled scripts.
Supported Clients
| Client | Name | Project MCP | User skills directory | Project skills directory |
|---|---|---|---|---|
| Amazon Q Developer | "AmazonQ" | yes | — | — |
| Antigravity | "Antigravity" | yes | ~/.gemini/config/skills (before migration: ~/.gemini/antigravity/skills) | .agents/skills |
| Augment Code | "AugmentCode" | no | ~/.augment/skills | .augment/skills |
| Augment Code IDE | "AugmentCodeIDE" | no | ~/.augment/skills | .augment/skills |
| Claude Code | "ClaudeCode" | yes | ~/.claude/skills | .claude/skills |
| Claude Desktop (macOS, Windows) | "ClaudeDesktop" | no | — | — |
| Cline | "Cline" | no | ~/.cline/skills | .cline/skills |
| Codex CLI | "Codex" | yes | ~/.agents/skills | .agents/skills |
| Continue | "Continue" | yes | ~/.continue/skills | .continue/skills |
| Copilot CLI | "CopilotCLI" | no | ~/.copilot/skills | .github/skills |
| Cursor | "Cursor" | no | ~/.cursor/skills | .cursor/skills |
| Gemini CLI | "GeminiCLI" | no | ~/.gemini/skills | .gemini/skills |
| Goose | "Goose" | no | ~/.agents/skills | .agents/skills |
| Junie | "Junie" | yes | ~/.junie/skills | .junie/skills |
| Kimi Code | "KimiCode" | no | ~/.kimi/skills | .kimi/skills |
| Kiro | "Kiro" | yes | ~/.kiro/skills | .kiro/skills |
| LM Studio | "LMStudio" | no | — | — |
| OpenCode | "OpenCode" | yes | ~/.config/opencode/skills | .opencode/skills |
| Qwen Code | "QwenCode" | yes | ~/.qwen/skills | .qwen/skills |
| Visual Studio Code | "VisualStudioCode" | yes | ~/.copilot/skills | .github/skills |
| Windsurf | "Windsurf" | no | ~/.codeium/windsurf/skills | .windsurf/skills |
| Zed | "Zed" | yes | ~/.agents/skills | .agents/skills |
- Paths:
~is the user's home directory on every operating system. Project skills directories are relative to the project directory. - Aliases are accepted, such as
"Claude"(Claude Desktop),"VSCode","Copilot"(Copilot CLI), and"Gemini"(Gemini CLI). - Shared skills directories: several clients share one. AgentTools tracks which deployments use each skill, so removing one deployment never deletes skills that another deployment still uses.
- Non-standard configuration file: pass
File["/path/to/config.json"]as the target. Add"ApplicationName" -> "<Name>"if the path does not identify the client. WithDeployAgentTools, also pass"SkillsDirectory" -> File["/path/to/skills"], unless the file is the client's standard global or project configuration file.
Local Server in Other Clients: Manual Configuration
Any MCP client that can launch local (stdio) servers can run the local Wolfram server, even if it is not in the Supported Clients table. To print the exact configuration for this machine, run this command with the toolset you want:
wolframscript -code 'Wolfram`AgentTools`MCPServerObject["WolframLanguage"]["JSONConfiguration"]'
Example output on Linux, shown with / instead of the \/ escapes that the real output contains (both are valid JSON):
{
"mcpServers": {
"WolframLanguage": {
"type": "stdio",
"command": "/usr/local/Wolfram/Wolfram/15.0/Executables/wolfram",
"args": [
"-run",
"PacletSymbol[\"Wolfram/AgentTools\",\"Wolfram`AgentTools`StartMCPServer\"][]",
"-noinit",
"-noprompt"
],
"env": {
"MCP_SERVER_NAME": "WolframLanguage",
"WOLFRAM_BASE": "/usr/share/Wolfram",
"WOLFRAM_LOCALBASE": "/home/user/.Wolfram/Objects",
"WOLFRAM_USERBASE": "/home/user/.Wolfram"
}
}
}
}
If the client uses this common mcpServers JSON format, AgentTools can write the entry (under the key Wolfram) for you: Wolfram`AgentTools`InstallMCPServer[File["/path/to/config.json"], "WolframLanguage"] writes only the server, and DeployAgentTools[File["/path/to/config.json"], "WolframLanguage", "SkillsDirectory" -> File["/path/to/skills"]] also installs the skills. Otherwise, copy the values into the client's own format; any server name works.
Command: the Wolfram kernel executable wolfram, not wolframscript.
| OS | Command |
|---|---|
| Windows | $InstallationDirectory\wolfram.exe |
| macOS | $InstallationDirectory/MacOS/wolfram |
| Linux | $InstallationDirectory/Executables/wolfram |
Arguments: four separate arguments, given to the client exactly as in the printed "args":
-run, followed byPacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"][]. This loads the newest installed AgentTools and starts the stdio server.-noinit: skips the user's init files.-noprompt: keeps kernel prompts off standard output, which must carry only MCP messages.
As a single shell command line:
/path/to/wolfram -run 'PacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"][]' -noinit -noprompt
If the client cannot set environment variables, name the toolset in the argument instead: PacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"]["WolframLanguage"].
Environment variables:
| Variable | Needed | Purpose |
|---|---|---|
MCP_SERVER_NAME | Recommended | The toolset to run: Wolfram (the default when unset), WolframAlpha, WolframLanguage, WolframPacletDevelopment, or the name of another server known to AgentTools |
WOLFRAM_USERBASE | Recommended | $UserBaseDirectory. It must be the directory where AgentTools was installed; otherwise the kernel may load the older built-in copy |
WOLFRAM_BASE | Recommended | $BaseDirectory |
WOLFRAM_LOCALBASE | Recommended | $LocalBase (storage for LocalObject) |
APPDATA | Windows | The user's application data directory, from which Windows derives the default $UserBaseDirectory |
MCP_TOOL_OPTIONS | Optional | Per-tool options as compact JSON, e.g. {"WolframLanguageEvaluator":{"TimeConstraint":120}} |
SUBMIT_USAGE_DATA | Optional | false opts out of usage data collection |
MCP_APPS_ENABLED | Optional | false disables MCP Apps (interactive UI resources) |
LLMKIT_ENABLED | Optional | false makes the context tools behave as if there were no LLMKit subscription, without warnings |
The printed configuration already holds this machine's values for the directory variables. Keep them, because the client may start servers with a reduced environment.
Option 2: Wolfram Cloud MCP
Wolfram Cloud MCP is a hosted Wolfram MCP server. It is free and needs no subscription, API key, or local installation.
- URL:
https://agenttools.wolfram.com/mcp - Transport: Streamable HTTP, with no authentication
| Tool | Description |
|---|---|
WolframContext | Semantic search over Wolfram|Alpha and Wolfram Language resources |
WolframLanguageEvaluator | Evaluates Wolfram Language code |
WolframAlpha | Sends natural language queries to Wolfram|Alpha |
Differences from the local server:
- Stateless evaluation:
WolframLanguageEvaluatordoes not carry definitions over between calls. Its default time constraint is 60 seconds per call, which itstimeConstraintargument can change. - No other tools: there are no notebook, symbol definition, code inspection, test, or paclet tools. The
wolfram-notebooksandwolfram-pacletsskills still needwolframscriptfor their scripts. - Manual setup only:
DeployAgentToolsandInstallMCPServerconfigure only the local server.
Configure your client
Clients that support remote servers (some spell it differently: Cline adds "type": "streamableHttp", Antigravity uses "serverUrl"; the support article below has steps for many clients):
{ "mcpServers": { "wolfram": { "url": "https://agenttools.wolfram.com/mcp" } } }
Claude Code (add --scope user to make it available in all projects):
claude mcp add --transport http wolfram https://agenttools.wolfram.com/mcp
Visual Studio Code (the user mcp.json or the workspace's .vscode/mcp.json):
{ "servers": { "wolfram": { "type": "http", "url": "https://agenttools.wolfram.com/mcp" } } }
Claude Desktop: in Customize → Connectors, search for Wolfram and click +.
Clients that only support local (stdio) servers can use the mcp-remote bridge, which requires Node.js:
{ "mcpServers": { "wolfram": { "command": "npx", "args": ["-y", "mcp-remote@latest", "https://agenttools.wolfram.com/mcp"] } } }
The local Wolfram toolset already provides all three of these tools, so don't add the cloud server next to it. Next to another local toolset (for example WolframLanguage, which has no WolframAlpha tool), the cloud server can supply the missing tools under its own key, such as wolfram. Then ask the user to restart or reload the client.
Troubleshooting
LLMKitRequired: the localWolframAlphatoolset needs LLMKit. Use theWolframtoolset or Wolfram Cloud MCP instead.DeploymentExists: a Wolfram toolset is already deployed for that client and location. UseOverwriteTarget -> Trueto replace it.AgentSkillNotInstalled(warning): a different skill with the same name already exists. Everything else was installed. Keep the existing skill, or ask the user before usingOverwriteTarget -> All.UnknownInstallLocation: the client has no known configuration file on this operating system (for example, Claude Desktop on Linux). Use aFile[...]target.- The tools do not appear after a restart: check the configuration file that was written (
dep["ConfigFile"]for a deployment, or the"Location"of theInstallMCPServerresult), then the server log at$UserBaseDirectory/ApplicationData/Wolfram/AgentTools/Servers/<Toolset>/Log.wl. Also make sure the kernel is activated (wolframscript -code '1+1'prints2).
More Information
- Wolfram Local MCP: https://www.wolfram.com/artificial-intelligence/mcp/local/wolfram-mcp-local/
- Wolfram Cloud MCP: https://www.wolfram.com/artificial-intelligence/mcp/cloud/wolfram-mcp-cloud
- Connecting Wolfram Cloud MCP to an AI application: https://support.wolfram.com/75237
- AgentTools paclet: https://resources.wolframcloud.com/PacletRepository/resources/Wolfram/AgentTools/
Getting the Wolfram Engine
The bundled scripts in this skill require wolframscript, the command-line interface to the Wolfram Language. This guide covers installation on each platform.
Check If Already Installed
Run the following in your terminal:
wolframscript -code '1+1'
If it prints 2, you're ready to go — no further setup needed.
macOS
Via Homebrew (recommended)
brew install --cask wolfram-engine
After installation, wolframscript should be available on your PATH automatically.
Manual Download
- Download the Wolfram Engine from https://www.wolfram.com/engine/.
- Open the
.dmgand drag Wolfram Engine to Applications. - Run the app once to complete activation.
wolframscriptis installed at/usr/local/bin/wolframscript.
Linux
- Download the
.shinstaller from https://www.wolfram.com/engine/. - Run:
sudo bash WolframEngine_*_Linux.sh - Follow the prompts and activate when complete.
After installation, wolframscript is typically at /usr/bin/wolframscript.
Windows
- Download the installer from https://www.wolfram.com/engine/.
- Run the
.exeinstaller and follow the prompts. - Activate when prompted.
wolframscript.exeis added to your PATH automatically. If not, the default location is:C:\Program Files\Wolfram Research\WolframScript\wolframscript.exe
Activation
The Wolfram Engine is free for development use but requires activation with a Wolfram Account. If you don't have one, create an account at https://account.wolfram.com.
When you first run wolframscript, it will prompt for activation. You can also activate manually:
wolframscript -activate
Troubleshooting
wolframscriptnot found — Ensure the install directory is on your PATH. You can check the location withwhich wolframscript(macOS/Linux) orwhere wolframscript(Windows).- Activation fails — Check your internet connection and verify your Wolfram Account credentials at https://account.wolfram.com.
- License issues — The free Wolfram Engine license covers non-production development use. For production or commercial use, see https://www.wolfram.com/engine/commercial-options/.
More Information
- Wolfram Engine: https://www.wolfram.com/engine/
- Wolfram Account: https://account.wolfram.com
Script Reference
Auto-generated reference for bundled scripts. Pass --usage to any
script for the latest argument documentation.
ReadNotebook.wls
Reads the contents of a Wolfram notebook (.nb) as markdown text.
Usage:
wolframscript -f scripts/ReadNotebook.wls <notebook>
Arguments:
| Argument | Required | Description |
|---|---|---|
notebook | Yes | The Wolfram notebook to read, specified as a file path, URL, or a NotebookObject[...] |
WriteNotebook.wls
Converts markdown text to a Wolfram notebook and saves it to a file.
Usage:
wolframscript -f scripts/WriteNotebook.wls <file> <markdown> [--overwrite value]
Arguments:
| Argument | Required | Description |
|---|---|---|
file | Yes | The file to write the notebook to (must end in .nb). Any missing parent directories are created automatically. |
markdown | Yes | The markdown text to write to a notebook. |
--overwrite | No | Whether to overwrite an existing file (default is False). |
Setting Up the Wolfram MCP Server
This guide explains how to connect your client to a Wolfram MCP server. With an MCP server you call the Wolfram tools directly instead of running the bundled scripts. A local server also keeps one Wolfram Language session alive between calls (definitions persist, and no kernel has to start for each call) and provides more tools.
There are two options:
| Wolfram Local MCP | Wolfram Cloud MCP | |
|---|---|---|
| Requires | A local Wolfram installation (Wolfram Engine, Wolfram, or Mathematica) | Nothing: free, no subscription or API key |
| Tools | Depends on the toolset (Step 3) | WolframContext, WolframLanguageEvaluator, WolframAlpha |
| Evaluation | Persistent session | Stateless, 60-second default time limit |
| Agent skills | DeployAgentTools installs them with the server | Not included |
Use the local server for coding agents and for anything that needs heavy computation, notebooks, tests, or paclet tools. Use Wolfram Cloud MCP when there is no local Wolfram installation and the user does not want to install one.
Both options change the user's client configuration, so ask the user before setting either one up. Also ask which toolset they want if the context does not make it clear. New MCP servers appear only after the client is restarted or reloaded, so the tools will not show up in your current session.
Option 1: Wolfram Local MCP
Step 1: Check for wolframscript
wolframscript -code '$VersionNumber'
If wolframscript is not found, read GetWolframEngine.md (in this references/ directory) or use Option 2. Current versions of AgentTools require Wolfram 15.0 or later.
The commands below are written for a POSIX shell. On Windows, shell quoting can mangle the double quotes in the code. To avoid that, put the code in a .wls file, wrap each result in Print[...], and run wolframscript -f file.wls.
Step 2: Install or update the AgentTools paclet
wolframscript -code 'PacletInstall["Wolfram/AgentTools", UpdatePacletSites -> True]["Version"]'
wolframscript -code 'Wolfram`AgentTools`AgentToolsObject["WolframLanguage"]["AgentSkillNames"]'
Wolfram 15 includes an older built-in copy of AgentTools. The first command installs the latest version, and Wolfram uses that version from then on. The second command should print {wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging}. If it prints {}, or the expression comes back unevaluated, the installed AgentTools cannot install agent skills. In that case use InstallMCPServer (Step 5).
Step 3: Choose a toolset
| Toolset | MCP tools | Agent skills installed by DeployAgentTools |
|---|---|---|
Wolfram | WolframContext, WolframLanguageEvaluator, WolframAlpha | wolfram-language, wolfram-alpha, wolfram-debugging |
WolframAlpha | WolframAlphaContext, WolframAlpha | wolfram-alpha |
WolframLanguage | WolframLanguageContext, WolframLanguageEvaluator, ReadNotebook, WriteNotebook, SymbolDefinition, CodeInspector, TestReport | wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging |
WolframPacletDevelopment | The WolframLanguage tools plus CreateSymbolDoc, EditSymbolDoc, EditSymbolDocExamples, CheckPaclet, BuildPaclet, SubmitPaclet | wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging |
- Use cases:
Wolframis for general computation and knowledge,WolframAlphafor Wolfram|Alpha queries only, andWolframLanguagefor Wolfram Language development.WolframPacletDevelopmentadds tools for writing documentation pages and for checking, building, and submitting paclets. - Tools: the
*Contexttools are semantic search (WolframAlphaContextover Wolfram|Alpha,WolframLanguageContextover Wolfram Language documentation and resources,WolframContextover both).ReadNotebook/WriteNotebookconvert notebooks (.nb) to and from markdown,SymbolDefinitionretrieves symbol definitions,CodeInspectorreports code issues, andTestReportruns.wlttest files. - Default toolset: without a toolset argument, the client's default is used:
Wolframfor Claude Desktop, Goose, and LM Studio, andWolframLanguagefor every other client. - One toolset per client: all four toolsets use the MCP configuration key
Wolfram, so a client (at a given user or project level) has only one of them. Switch withOverwriteTarget -> True, or use"MCPServerName"(Step 5) to install two side by side. - LLMKit: the context tools work best with an LLMKit subscription.
WolframAlphaContextrequires one, so installing theWolframAlphatoolset fails withLLMKitRequiredunless the kernel is connected to the Wolfram Cloud with an account that has LLMKit (useWolframinstead). For the other toolsets, anLLMKitSuggestedwarning is informational only.
Step 4: Choose DeployAgentTools or InstallMCPServer
DeployAgentTools is the recommended way. It installs the toolset's MCP server and its agent skills as one tracked deployment, which DeleteObject can remove again. InstallMCPServer writes only the MCP server configuration. Use it only when the MCP server is all that should be installed.
You are reading this from a Wolfram skill that is already installed, so check two things first:
- Existing deployments: run
wolframscript -code 'DeployedAgentTools[]'. If your client and location already have a deployment, the server is already configured. Ask the user to restart the client, or redeploy withOverwriteTarget -> Trueto switch toolsets or to add the skills that an older AgentTools did not install. - Where this skill is installed: this is the directory that contains this
references/folder. Compare its parent directory with the skills directory thatDeployAgentToolswill use (Supported Clients).
Use DeployAgentTools when this skill is already in that directory (same client, same user or project scope), or when no Wolfram skills are installed yet. It handles existing skills safely:
- An identical copy is adopted as is, and
DeleteObjectnever deletes a skill directory that existed before the deployment. - A copy with different content (installed by hand or by another tool, or a deployed copy that the user modified) is left untouched. The MCP server and the other skills are still installed, and the warning
DeployAgentTools::AgentSkillNotInstallednames the skipped skill. - Copies installed by an earlier deployment are updated to the current AgentTools version automatically; a newer copy that another deployment still uses is never downgraded. (Replacing a deployment for the same client and location still needs
OverwriteTarget -> True.)
Use InstallMCPServer, or DeployAgentTools with "SkillsDirectory" -> None (only the MCP server, still tracked as a deployment), when:
- The user only wants the MCP server, or Step 2 showed that the installed AgentTools has no agent skills.
- The Wolfram skills are installed somewhere that
DeployAgentToolsdoes not manage, but that your client also reads.DeployAgentToolswould add a second copy, and the client would see each skill twice. Examples: a Claude Code plugin (a path under~/.claude/plugins/); another skills directory that your client loads, such as~/.agents/skillsor~/.claude/skillsfor a client that also reads those; or the project's skills directory while you deploy at user level (a project-level deployment also works there if the client supports project MCP configuration).
Never use OverwriteTarget -> All without asking the user. It replaces skill directories that the deployment does not own and discards any changes in them.
Step 5: Install the server
DeployAgentTools, DeployedAgentTools, and AgentToolsDeployment are built-in symbols, so they need no context prefix:
# The client's default toolset, at user level
wolframscript -code 'DeployAgentTools["ClaudeCode"]'
# A specific toolset, at project level (the project's MCP configuration and skills directory)
wolframscript -code 'DeployAgentTools[{"ClaudeCode", "/path/to/project"}, "WolframLanguage"]'
# Only the MCP server, as a tracked deployment
wolframscript -code 'DeployAgentTools["ClaudeCode", "WolframLanguage", "SkillsDirectory" -> None]'
# Replace the Wolfram toolset already deployed for this client and location
wolframscript -code 'DeployAgentTools["ClaudeCode", "Wolfram", OverwriteTarget -> True]'
- Result: an
AgentToolsDeployment[...]. The first run can take a few minutes while the context tools download their search indexes, so use a generous command timeout. - Clients without agent skills support (Claude Desktop, LM Studio, Amazon Q Developer) get only the MCP server.
- Project level without project MCP support: the client gets only the project skills, with an
MCPServersNotDeployedwarning. Add the server at user level withInstallMCPServer. DeploymentExists: a Wolfram toolset is already deployed for that client and location. UseOverwriteTarget -> Trueto replace it.DeployAgentTools[All]deploys to every supported client, installed or not. Do not use it unless the user asks.- Removing:
DeleteObject /@ Select[DeployedAgentTools["ClaudeCode"], #["Scope"] === "Global" && #["Toolset"] === "WolframLanguage" &]removes the user-level deployment. For a project deployment, match#["Scope"] === File["/path/to/project"](the absolute project path) instead; without a scope test, every project's deployment of that toolset is removed too. Skills that another deployment still uses, that were modified, or that existed before the deployment are kept.
InstallMCPServer needs the full context name:
wolframscript -code 'Wolfram`AgentTools`InstallMCPServer["ClaudeCode", "WolframLanguage"]'
wolframscript -code 'Wolfram`AgentTools`InstallMCPServer[{"ClaudeCode", "/path/to/project"}, "WolframLanguage"]'
wolframscript -code 'Wolfram`AgentTools`UninstallMCPServer["ClaudeCode", "WolframLanguage"]'
InstallMCPServer is not tracked by DeployedAgentTools. It replaces whatever Wolfram server is already configured under the key Wolfram.
Both functions accept these options:
"ToolOptions" -> <|"WolframLanguageEvaluator" -> <|"TimeConstraint" -> 120|>|>: per-tool settings."SubmitUsageData" -> False: opts out of usage data collection, which the built-in servers do by default."MCPServerName" -> "WolframDev": uses a different configuration key, so that two Wolfram toolsets can be installed side by side.
Step 6: Restart the client
Ask the user to restart or reload the client. The tools then appear under the server name Wolfram, for example mcp__Wolfram__WolframLanguageEvaluator in Claude Code. When they are available, use them instead of the bundled scripts.
Supported Clients
| Client | Name | Project MCP | User skills directory | Project skills directory |
|---|---|---|---|---|
| Amazon Q Developer | "AmazonQ" | yes | — | — |
| Antigravity | "Antigravity" | yes | ~/.gemini/config/skills (before migration: ~/.gemini/antigravity/skills) | .agents/skills |
| Augment Code | "AugmentCode" | no | ~/.augment/skills | .augment/skills |
| Augment Code IDE | "AugmentCodeIDE" | no | ~/.augment/skills | .augment/skills |
| Claude Code | "ClaudeCode" | yes | ~/.claude/skills | .claude/skills |
| Claude Desktop (macOS, Windows) | "ClaudeDesktop" | no | — | — |
| Cline | "Cline" | no | ~/.cline/skills | .cline/skills |
| Codex CLI | "Codex" | yes | ~/.agents/skills | .agents/skills |
| Continue | "Continue" | yes | ~/.continue/skills | .continue/skills |
| Copilot CLI | "CopilotCLI" | no | ~/.copilot/skills | .github/skills |
| Cursor | "Cursor" | no | ~/.cursor/skills | .cursor/skills |
| Gemini CLI | "GeminiCLI" | no | ~/.gemini/skills | .gemini/skills |
| Goose | "Goose" | no | ~/.agents/skills | .agents/skills |
| Junie | "Junie" | yes | ~/.junie/skills | .junie/skills |
| Kimi Code | "KimiCode" | no | ~/.kimi/skills | .kimi/skills |
| Kiro | "Kiro" | yes | ~/.kiro/skills | .kiro/skills |
| LM Studio | "LMStudio" | no | — | — |
| OpenCode | "OpenCode" | yes | ~/.config/opencode/skills | .opencode/skills |
| Qwen Code | "QwenCode" | yes | ~/.qwen/skills | .qwen/skills |
| Visual Studio Code | "VisualStudioCode" | yes | ~/.copilot/skills | .github/skills |
| Windsurf | "Windsurf" | no | ~/.codeium/windsurf/skills | .windsurf/skills |
| Zed | "Zed" | yes | ~/.agents/skills | .agents/skills |
- Paths:
~is the user's home directory on every operating system. Project skills directories are relative to the project directory. - Aliases are accepted, such as
"Claude"(Claude Desktop),"VSCode","Copilot"(Copilot CLI), and"Gemini"(Gemini CLI). - Shared skills directories: several clients share one. AgentTools tracks which deployments use each skill, so removing one deployment never deletes skills that another deployment still uses.
- Non-standard configuration file: pass
File["/path/to/config.json"]as the target. Add"ApplicationName" -> "<Name>"if the path does not identify the client. WithDeployAgentTools, also pass"SkillsDirectory" -> File["/path/to/skills"], unless the file is the client's standard global or project configuration file.
Local Server in Other Clients: Manual Configuration
Any MCP client that can launch local (stdio) servers can run the local Wolfram server, even if it is not in the Supported Clients table. To print the exact configuration for this machine, run this command with the toolset you want:
wolframscript -code 'Wolfram`AgentTools`MCPServerObject["WolframLanguage"]["JSONConfiguration"]'
Example output on Linux, shown with / instead of the \/ escapes that the real output contains (both are valid JSON):
{
"mcpServers": {
"WolframLanguage": {
"type": "stdio",
"command": "/usr/local/Wolfram/Wolfram/15.0/Executables/wolfram",
"args": [
"-run",
"PacletSymbol[\"Wolfram/AgentTools\",\"Wolfram`AgentTools`StartMCPServer\"][]",
"-noinit",
"-noprompt"
],
"env": {
"MCP_SERVER_NAME": "WolframLanguage",
"WOLFRAM_BASE": "/usr/share/Wolfram",
"WOLFRAM_LOCALBASE": "/home/user/.Wolfram/Objects",
"WOLFRAM_USERBASE": "/home/user/.Wolfram"
}
}
}
}
If the client uses this common mcpServers JSON format, AgentTools can write the entry (under the key Wolfram) for you: Wolfram`AgentTools`InstallMCPServer[File["/path/to/config.json"], "WolframLanguage"] writes only the server, and DeployAgentTools[File["/path/to/config.json"], "WolframLanguage", "SkillsDirectory" -> File["/path/to/skills"]] also installs the skills. Otherwise, copy the values into the client's own format; any server name works.
Command: the Wolfram kernel executable wolfram, not wolframscript.
| OS | Command |
|---|---|
| Windows | $InstallationDirectory\wolfram.exe |
| macOS | $InstallationDirectory/MacOS/wolfram |
| Linux | $InstallationDirectory/Executables/wolfram |
Arguments: four separate arguments, given to the client exactly as in the printed "args":
-run, followed byPacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"][]. This loads the newest installed AgentTools and starts the stdio server.-noinit: skips the user's init files.-noprompt: keeps kernel prompts off standard output, which must carry only MCP messages.
As a single shell command line:
/path/to/wolfram -run 'PacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"][]' -noinit -noprompt
If the client cannot set environment variables, name the toolset in the argument instead: PacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"]["WolframLanguage"].
Environment variables:
| Variable | Needed | Purpose |
|---|---|---|
MCP_SERVER_NAME | Recommended | The toolset to run: Wolfram (the default when unset), WolframAlpha, WolframLanguage, WolframPacletDevelopment, or the name of another server known to AgentTools |
WOLFRAM_USERBASE | Recommended | $UserBaseDirectory. It must be the directory where AgentTools was installed; otherwise the kernel may load the older built-in copy |
WOLFRAM_BASE | Recommended | $BaseDirectory |
WOLFRAM_LOCALBASE | Recommended | $LocalBase (storage for LocalObject) |
APPDATA | Windows | The user's application data directory, from which Windows derives the default $UserBaseDirectory |
MCP_TOOL_OPTIONS | Optional | Per-tool options as compact JSON, e.g. {"WolframLanguageEvaluator":{"TimeConstraint":120}} |
SUBMIT_USAGE_DATA | Optional | false opts out of usage data collection |
MCP_APPS_ENABLED | Optional | false disables MCP Apps (interactive UI resources) |
LLMKIT_ENABLED | Optional | false makes the context tools behave as if there were no LLMKit subscription, without warnings |
The printed configuration already holds this machine's values for the directory variables. Keep them, because the client may start servers with a reduced environment.
Option 2: Wolfram Cloud MCP
Wolfram Cloud MCP is a hosted Wolfram MCP server. It is free and needs no subscription, API key, or local installation.
- URL:
https://agenttools.wolfram.com/mcp - Transport: Streamable HTTP, with no authentication
| Tool | Description |
|---|---|
WolframContext | Semantic search over Wolfram|Alpha and Wolfram Language resources |
WolframLanguageEvaluator | Evaluates Wolfram Language code |
WolframAlpha | Sends natural language queries to Wolfram|Alpha |
Differences from the local server:
- Stateless evaluation:
WolframLanguageEvaluatordoes not carry definitions over between calls. Its default time constraint is 60 seconds per call, which itstimeConstraintargument can change. - No other tools: there are no notebook, symbol definition, code inspection, test, or paclet tools. The
wolfram-notebooksandwolfram-pacletsskills still needwolframscriptfor their scripts. - Manual setup only:
DeployAgentToolsandInstallMCPServerconfigure only the local server.
Configure your client
Clients that support remote servers (some spell it differently: Cline adds "type": "streamableHttp", Antigravity uses "serverUrl"; the support article below has steps for many clients):
{ "mcpServers": { "wolfram": { "url": "https://agenttools.wolfram.com/mcp" } } }
Claude Code (add --scope user to make it available in all projects):
claude mcp add --transport http wolfram https://agenttools.wolfram.com/mcp
Visual Studio Code (the user mcp.json or the workspace's .vscode/mcp.json):
{ "servers": { "wolfram": { "type": "http", "url": "https://agenttools.wolfram.com/mcp" } } }
Claude Desktop: in Customize → Connectors, search for Wolfram and click +.
Clients that only support local (stdio) servers can use the mcp-remote bridge, which requires Node.js:
{ "mcpServers": { "wolfram": { "command": "npx", "args": ["-y", "mcp-remote@latest", "https://agenttools.wolfram.com/mcp"] } } }
The local Wolfram toolset already provides all three of these tools, so don't add the cloud server next to it. Next to another local toolset (for example WolframLanguage, which has no WolframAlpha tool), the cloud server can supply the missing tools under its own key, such as wolfram. Then ask the user to restart or reload the client.
Troubleshooting
LLMKitRequired: the localWolframAlphatoolset needs LLMKit. Use theWolframtoolset or Wolfram Cloud MCP instead.DeploymentExists: a Wolfram toolset is already deployed for that client and location. UseOverwriteTarget -> Trueto replace it.AgentSkillNotInstalled(warning): a different skill with the same name already exists. Everything else was installed. Keep the existing skill, or ask the user before usingOverwriteTarget -> All.UnknownInstallLocation: the client has no known configuration file on this operating system (for example, Claude Desktop on Linux). Use aFile[...]target.- The tools do not appear after a restart: check the configuration file that was written (
dep["ConfigFile"]for a deployment, or the"Location"of theInstallMCPServerresult), then the server log at$UserBaseDirectory/ApplicationData/Wolfram/AgentTools/Servers/<Toolset>/Log.wl. Also make sure the kernel is activated (wolframscript -code '1+1'prints2).
More Information
- Wolfram Local MCP: https://www.wolfram.com/artificial-intelligence/mcp/local/wolfram-mcp-local/
- Wolfram Cloud MCP: https://www.wolfram.com/artificial-intelligence/mcp/cloud/wolfram-mcp-cloud
- Connecting Wolfram Cloud MCP to an AI application: https://support.wolfram.com/75237
- AgentTools paclet: https://resources.wolframcloud.com/PacletRepository/resources/Wolfram/AgentTools/
Getting the Wolfram Engine
The bundled scripts in this skill require wolframscript, the command-line interface to the Wolfram Language. This guide covers installation on each platform.
Check If Already Installed
Run the following in your terminal:
wolframscript -code '1+1'
If it prints 2, you're ready to go — no further setup needed.
macOS
Via Homebrew (recommended)
brew install --cask wolfram-engine
After installation, wolframscript should be available on your PATH automatically.
Manual Download
- Download the Wolfram Engine from https://www.wolfram.com/engine/.
- Open the
.dmgand drag Wolfram Engine to Applications. - Run the app once to complete activation.
wolframscriptis installed at/usr/local/bin/wolframscript.
Linux
- Download the
.shinstaller from https://www.wolfram.com/engine/. - Run:
sudo bash WolframEngine_*_Linux.sh - Follow the prompts and activate when complete.
After installation, wolframscript is typically at /usr/bin/wolframscript.
Windows
- Download the installer from https://www.wolfram.com/engine/.
- Run the
.exeinstaller and follow the prompts. - Activate when prompted.
wolframscript.exeis added to your PATH automatically. If not, the default location is:C:\Program Files\Wolfram Research\WolframScript\wolframscript.exe
Activation
The Wolfram Engine is free for development use but requires activation with a Wolfram Account. If you don't have one, create an account at https://account.wolfram.com.
When you first run wolframscript, it will prompt for activation. You can also activate manually:
wolframscript -activate
Troubleshooting
wolframscriptnot found — Ensure the install directory is on your PATH. You can check the location withwhich wolframscript(macOS/Linux) orwhere wolframscript(Windows).- Activation fails — Check your internet connection and verify your Wolfram Account credentials at https://account.wolfram.com.
- License issues — The free Wolfram Engine license covers non-production development use. For production or commercial use, see https://www.wolfram.com/engine/commercial-options/.
More Information
- Wolfram Engine: https://www.wolfram.com/engine/
- Wolfram Account: https://account.wolfram.com
Script Reference
Auto-generated reference for bundled scripts. Pass --usage to any
script for the latest argument documentation.
CheckPaclet.wls
Checks a Wolfram Language paclet for issues such as missing metadata, invalid structure, or other problems that would prevent successful building or submission. Returns a summary of issues organized by severity (Error, Warning, Suggestion). Use this tool before BuildPaclet or SubmitPaclet to identify and fix problems early. The path should be an absolute path to either the paclet root directory or the definition notebook (.nb) file.
Usage:
wolframscript -f scripts/CheckPaclet.wls <path>
Arguments:
| Argument | Required | Description |
|---|---|---|
path | Yes | Absolute path to the paclet directory or definition notebook (.nb) file. |
BuildPaclet.wls
Builds a Wolfram Language paclet, producing a .paclet archive file. This can be a long-running operation, especially for paclets with extensive documentation. Optionally runs CheckPaclet first to validate the paclet before building. The path should be an absolute path to either the paclet root directory or the definition notebook (.nb) file.
Usage:
wolframscript -f scripts/BuildPaclet.wls <path> [--check value]
Arguments:
| Argument | Required | Description |
|---|---|---|
path | Yes | Absolute path to the paclet directory or definition notebook (.nb) file. |
--check | No | Whether to run CheckPaclet before building (default: false). |
SubmitPaclet.wls
Submits a Wolfram Language paclet to the Wolfram Language Paclet Repository (paclets.com). This builds the paclet and then submits it for review. Requires prior authentication via $PublisherID or an active Wolfram Cloud connection. Use CheckPaclet first to verify the paclet is ready for submission. This is a long-running operation that involves building and uploading. The path should be an absolute path to either the paclet root directory or the definition notebook (.nb) file.
Usage:
wolframscript -f scripts/SubmitPaclet.wls <path>
Arguments:
| Argument | Required | Description |
|---|---|---|
path | Yes | Absolute path to the paclet directory or definition notebook (.nb) file. |
Setting Up the Wolfram MCP Server
This guide explains how to connect your client to a Wolfram MCP server. With an MCP server you call the Wolfram tools directly instead of running the bundled scripts. A local server also keeps one Wolfram Language session alive between calls (definitions persist, and no kernel has to start for each call) and provides more tools.
There are two options:
| Wolfram Local MCP | Wolfram Cloud MCP | |
|---|---|---|
| Requires | A local Wolfram installation (Wolfram Engine, Wolfram, or Mathematica) | Nothing: free, no subscription or API key |
| Tools | Depends on the toolset (Step 3) | WolframContext, WolframLanguageEvaluator, WolframAlpha |
| Evaluation | Persistent session | Stateless, 60-second default time limit |
| Agent skills | DeployAgentTools installs them with the server | Not included |
Use the local server for coding agents and for anything that needs heavy computation, notebooks, tests, or paclet tools. Use Wolfram Cloud MCP when there is no local Wolfram installation and the user does not want to install one.
Both options change the user's client configuration, so ask the user before setting either one up. Also ask which toolset they want if the context does not make it clear. New MCP servers appear only after the client is restarted or reloaded, so the tools will not show up in your current session.
Option 1: Wolfram Local MCP
Step 1: Check for wolframscript
wolframscript -code '$VersionNumber'
If wolframscript is not found, read GetWolframEngine.md (in this references/ directory) or use Option 2. Current versions of AgentTools require Wolfram 15.0 or later.
The commands below are written for a POSIX shell. On Windows, shell quoting can mangle the double quotes in the code. To avoid that, put the code in a .wls file, wrap each result in Print[...], and run wolframscript -f file.wls.
Step 2: Install or update the AgentTools paclet
wolframscript -code 'PacletInstall["Wolfram/AgentTools", UpdatePacletSites -> True]["Version"]'
wolframscript -code 'Wolfram`AgentTools`AgentToolsObject["WolframLanguage"]["AgentSkillNames"]'
Wolfram 15 includes an older built-in copy of AgentTools. The first command installs the latest version, and Wolfram uses that version from then on. The second command should print {wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging}. If it prints {}, or the expression comes back unevaluated, the installed AgentTools cannot install agent skills. In that case use InstallMCPServer (Step 5).
Step 3: Choose a toolset
| Toolset | MCP tools | Agent skills installed by DeployAgentTools |
|---|---|---|
Wolfram | WolframContext, WolframLanguageEvaluator, WolframAlpha | wolfram-language, wolfram-alpha, wolfram-debugging |
WolframAlpha | WolframAlphaContext, WolframAlpha | wolfram-alpha |
WolframLanguage | WolframLanguageContext, WolframLanguageEvaluator, ReadNotebook, WriteNotebook, SymbolDefinition, CodeInspector, TestReport | wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging |
WolframPacletDevelopment | The WolframLanguage tools plus CreateSymbolDoc, EditSymbolDoc, EditSymbolDocExamples, CheckPaclet, BuildPaclet, SubmitPaclet | wolfram-language, wolfram-notebooks, wolfram-paclets, wolfram-debugging |
- Use cases:
Wolframis for general computation and knowledge,WolframAlphafor Wolfram|Alpha queries only, andWolframLanguagefor Wolfram Language development.WolframPacletDevelopmentadds tools for writing documentation pages and for checking, building, and submitting paclets. - Tools: the
*Contexttools are semantic search (WolframAlphaContextover Wolfram|Alpha,WolframLanguageContextover Wolfram Language documentation and resources,WolframContextover both).ReadNotebook/WriteNotebookconvert notebooks (.nb) to and from markdown,SymbolDefinitionretrieves symbol definitions,CodeInspectorreports code issues, andTestReportruns.wlttest files. - Default toolset: without a toolset argument, the client's default is used:
Wolframfor Claude Desktop, Goose, and LM Studio, andWolframLanguagefor every other client. - One toolset per client: all four toolsets use the MCP configuration key
Wolfram, so a client (at a given user or project level) has only one of them. Switch withOverwriteTarget -> True, or use"MCPServerName"(Step 5) to install two side by side. - LLMKit: the context tools work best with an LLMKit subscription.
WolframAlphaContextrequires one, so installing theWolframAlphatoolset fails withLLMKitRequiredunless the kernel is connected to the Wolfram Cloud with an account that has LLMKit (useWolframinstead). For the other toolsets, anLLMKitSuggestedwarning is informational only.
Step 4: Choose DeployAgentTools or InstallMCPServer
DeployAgentTools is the recommended way. It installs the toolset's MCP server and its agent skills as one tracked deployment, which DeleteObject can remove again. InstallMCPServer writes only the MCP server configuration. Use it only when the MCP server is all that should be installed.
You are reading this from a Wolfram skill that is already installed, so check two things first:
- Existing deployments: run
wolframscript -code 'DeployedAgentTools[]'. If your client and location already have a deployment, the server is already configured. Ask the user to restart the client, or redeploy withOverwriteTarget -> Trueto switch toolsets or to add the skills that an older AgentTools did not install. - Where this skill is installed: this is the directory that contains this
references/folder. Compare its parent directory with the skills directory thatDeployAgentToolswill use (Supported Clients).
Use DeployAgentTools when this skill is already in that directory (same client, same user or project scope), or when no Wolfram skills are installed yet. It handles existing skills safely:
- An identical copy is adopted as is, and
DeleteObjectnever deletes a skill directory that existed before the deployment. - A copy with different content (installed by hand or by another tool, or a deployed copy that the user modified) is left untouched. The MCP server and the other skills are still installed, and the warning
DeployAgentTools::AgentSkillNotInstallednames the skipped skill. - Copies installed by an earlier deployment are updated to the current AgentTools version automatically; a newer copy that another deployment still uses is never downgraded. (Replacing a deployment for the same client and location still needs
OverwriteTarget -> True.)
Use InstallMCPServer, or DeployAgentTools with "SkillsDirectory" -> None (only the MCP server, still tracked as a deployment), when:
- The user only wants the MCP server, or Step 2 showed that the installed AgentTools has no agent skills.
- The Wolfram skills are installed somewhere that
DeployAgentToolsdoes not manage, but that your client also reads.DeployAgentToolswould add a second copy, and the client would see each skill twice. Examples: a Claude Code plugin (a path under~/.claude/plugins/); another skills directory that your client loads, such as~/.agents/skillsor~/.claude/skillsfor a client that also reads those; or the project's skills directory while you deploy at user level (a project-level deployment also works there if the client supports project MCP configuration).
Never use OverwriteTarget -> All without asking the user. It replaces skill directories that the deployment does not own and discards any changes in them.
Step 5: Install the server
DeployAgentTools, DeployedAgentTools, and AgentToolsDeployment are built-in symbols, so they need no context prefix:
# The client's default toolset, at user level
wolframscript -code 'DeployAgentTools["ClaudeCode"]'
# A specific toolset, at project level (the project's MCP configuration and skills directory)
wolframscript -code 'DeployAgentTools[{"ClaudeCode", "/path/to/project"}, "WolframLanguage"]'
# Only the MCP server, as a tracked deployment
wolframscript -code 'DeployAgentTools["ClaudeCode", "WolframLanguage", "SkillsDirectory" -> None]'
# Replace the Wolfram toolset already deployed for this client and location
wolframscript -code 'DeployAgentTools["ClaudeCode", "Wolfram", OverwriteTarget -> True]'
- Result: an
AgentToolsDeployment[...]. The first run can take a few minutes while the context tools download their search indexes, so use a generous command timeout. - Clients without agent skills support (Claude Desktop, LM Studio, Amazon Q Developer) get only the MCP server.
- Project level without project MCP support: the client gets only the project skills, with an
MCPServersNotDeployedwarning. Add the server at user level withInstallMCPServer. DeploymentExists: a Wolfram toolset is already deployed for that client and location. UseOverwriteTarget -> Trueto replace it.DeployAgentTools[All]deploys to every supported client, installed or not. Do not use it unless the user asks.- Removing:
DeleteObject /@ Select[DeployedAgentTools["ClaudeCode"], #["Scope"] === "Global" && #["Toolset"] === "WolframLanguage" &]removes the user-level deployment. For a project deployment, match#["Scope"] === File["/path/to/project"](the absolute project path) instead; without a scope test, every project's deployment of that toolset is removed too. Skills that another deployment still uses, that were modified, or that existed before the deployment are kept.
InstallMCPServer needs the full context name:
wolframscript -code 'Wolfram`AgentTools`InstallMCPServer["ClaudeCode", "WolframLanguage"]'
wolframscript -code 'Wolfram`AgentTools`InstallMCPServer[{"ClaudeCode", "/path/to/project"}, "WolframLanguage"]'
wolframscript -code 'Wolfram`AgentTools`UninstallMCPServer["ClaudeCode", "WolframLanguage"]'
InstallMCPServer is not tracked by DeployedAgentTools. It replaces whatever Wolfram server is already configured under the key Wolfram.
Both functions accept these options:
"ToolOptions" -> <|"WolframLanguageEvaluator" -> <|"TimeConstraint" -> 120|>|>: per-tool settings."SubmitUsageData" -> False: opts out of usage data collection, which the built-in servers do by default."MCPServerName" -> "WolframDev": uses a different configuration key, so that two Wolfram toolsets can be installed side by side.
Step 6: Restart the client
Ask the user to restart or reload the client. The tools then appear under the server name Wolfram, for example mcp__Wolfram__WolframLanguageEvaluator in Claude Code. When they are available, use them instead of the bundled scripts.
Supported Clients
| Client | Name | Project MCP | User skills directory | Project skills directory |
|---|---|---|---|---|
| Amazon Q Developer | "AmazonQ" | yes | — | — |
| Antigravity | "Antigravity" | yes | ~/.gemini/config/skills (before migration: ~/.gemini/antigravity/skills) | .agents/skills |
| Augment Code | "AugmentCode" | no | ~/.augment/skills | .augment/skills |
| Augment Code IDE | "AugmentCodeIDE" | no | ~/.augment/skills | .augment/skills |
| Claude Code | "ClaudeCode" | yes | ~/.claude/skills | .claude/skills |
| Claude Desktop (macOS, Windows) | "ClaudeDesktop" | no | — | — |
| Cline | "Cline" | no | ~/.cline/skills | .cline/skills |
| Codex CLI | "Codex" | yes | ~/.agents/skills | .agents/skills |
| Continue | "Continue" | yes | ~/.continue/skills | .continue/skills |
| Copilot CLI | "CopilotCLI" | no | ~/.copilot/skills | .github/skills |
| Cursor | "Cursor" | no | ~/.cursor/skills | .cursor/skills |
| Gemini CLI | "GeminiCLI" | no | ~/.gemini/skills | .gemini/skills |
| Goose | "Goose" | no | ~/.agents/skills | .agents/skills |
| Junie | "Junie" | yes | ~/.junie/skills | .junie/skills |
| Kimi Code | "KimiCode" | no | ~/.kimi/skills | .kimi/skills |
| Kiro | "Kiro" | yes | ~/.kiro/skills | .kiro/skills |
| LM Studio | "LMStudio" | no | — | — |
| OpenCode | "OpenCode" | yes | ~/.config/opencode/skills | .opencode/skills |
| Qwen Code | "QwenCode" | yes | ~/.qwen/skills | .qwen/skills |
| Visual Studio Code | "VisualStudioCode" | yes | ~/.copilot/skills | .github/skills |
| Windsurf | "Windsurf" | no | ~/.codeium/windsurf/skills | .windsurf/skills |
| Zed | "Zed" | yes | ~/.agents/skills | .agents/skills |
- Paths:
~is the user's home directory on every operating system. Project skills directories are relative to the project directory. - Aliases are accepted, such as
"Claude"(Claude Desktop),"VSCode","Copilot"(Copilot CLI), and"Gemini"(Gemini CLI). - Shared skills directories: several clients share one. AgentTools tracks which deployments use each skill, so removing one deployment never deletes skills that another deployment still uses.
- Non-standard configuration file: pass
File["/path/to/config.json"]as the target. Add"ApplicationName" -> "<Name>"if the path does not identify the client. WithDeployAgentTools, also pass"SkillsDirectory" -> File["/path/to/skills"], unless the file is the client's standard global or project configuration file.
Local Server in Other Clients: Manual Configuration
Any MCP client that can launch local (stdio) servers can run the local Wolfram server, even if it is not in the Supported Clients table. To print the exact configuration for this machine, run this command with the toolset you want:
wolframscript -code 'Wolfram`AgentTools`MCPServerObject["WolframLanguage"]["JSONConfiguration"]'
Example output on Linux, shown with / instead of the \/ escapes that the real output contains (both are valid JSON):
{
"mcpServers": {
"WolframLanguage": {
"type": "stdio",
"command": "/usr/local/Wolfram/Wolfram/15.0/Executables/wolfram",
"args": [
"-run",
"PacletSymbol[\"Wolfram/AgentTools\",\"Wolfram`AgentTools`StartMCPServer\"][]",
"-noinit",
"-noprompt"
],
"env": {
"MCP_SERVER_NAME": "WolframLanguage",
"WOLFRAM_BASE": "/usr/share/Wolfram",
"WOLFRAM_LOCALBASE": "/home/user/.Wolfram/Objects",
"WOLFRAM_USERBASE": "/home/user/.Wolfram"
}
}
}
}
If the client uses this common mcpServers JSON format, AgentTools can write the entry (under the key Wolfram) for you: Wolfram`AgentTools`InstallMCPServer[File["/path/to/config.json"], "WolframLanguage"] writes only the server, and DeployAgentTools[File["/path/to/config.json"], "WolframLanguage", "SkillsDirectory" -> File["/path/to/skills"]] also installs the skills. Otherwise, copy the values into the client's own format; any server name works.
Command: the Wolfram kernel executable wolfram, not wolframscript.
| OS | Command |
|---|---|
| Windows | $InstallationDirectory\wolfram.exe |
| macOS | $InstallationDirectory/MacOS/wolfram |
| Linux | $InstallationDirectory/Executables/wolfram |
Arguments: four separate arguments, given to the client exactly as in the printed "args":
-run, followed byPacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"][]. This loads the newest installed AgentTools and starts the stdio server.-noinit: skips the user's init files.-noprompt: keeps kernel prompts off standard output, which must carry only MCP messages.
As a single shell command line:
/path/to/wolfram -run 'PacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"][]' -noinit -noprompt
If the client cannot set environment variables, name the toolset in the argument instead: PacletSymbol["Wolfram/AgentTools","Wolfram`AgentTools`StartMCPServer"]["WolframLanguage"].
Environment variables:
| Variable | Needed | Purpose |
|---|---|---|
MCP_SERVER_NAME | Recommended | The toolset to run: Wolfram (the default when unset), WolframAlpha, WolframLanguage, WolframPacletDevelopment, or the name of another server known to AgentTools |
WOLFRAM_USERBASE | Recommended | $UserBaseDirectory. It must be the directory where AgentTools was installed; otherwise the kernel may load the older built-in copy |
WOLFRAM_BASE | Recommended | $BaseDirectory |
WOLFRAM_LOCALBASE | Recommended | $LocalBase (storage for LocalObject) |
APPDATA | Windows | The user's application data directory, from which Windows derives the default $UserBaseDirectory |
MCP_TOOL_OPTIONS | Optional | Per-tool options as compact JSON, e.g. {"WolframLanguageEvaluator":{"TimeConstraint":120}} |
SUBMIT_USAGE_DATA | Optional | false opts out of usage data collection |
MCP_APPS_ENABLED | Optional | false disables MCP Apps (interactive UI resources) |
LLMKIT_ENABLED | Optional | false makes the context tools behave as if there were no LLMKit subscription, without warnings |
The printed configuration already holds this machine's values for the directory variables. Keep them, because the client may start servers with a reduced environment.
Option 2: Wolfram Cloud MCP
Wolfram Cloud MCP is a hosted Wolfram MCP server. It is free and needs no subscription, API key, or local installation.
- URL:
https://agenttools.wolfram.com/mcp - Transport: Streamable HTTP, with no authentication
| Tool | Description |
|---|---|
WolframContext | Semantic search over Wolfram|Alpha and Wolfram Language resources |
WolframLanguageEvaluator | Evaluates Wolfram Language code |
WolframAlpha | Sends natural language queries to Wolfram|Alpha |
Differences from the local server:
- Stateless evaluation:
WolframLanguageEvaluatordoes not carry definitions over between calls. Its default time constraint is 60 seconds per call, which itstimeConstraintargument can change. - No other tools: there are no notebook, symbol definition, code inspection, test, or paclet tools. The
wolfram-notebooksandwolfram-pacletsskills still needwolframscriptfor their scripts. - Manual setup only:
DeployAgentToolsandInstallMCPServerconfigure only the local server.
Configure your client
Clients that support remote servers (some spell it differently: Cline adds "type": "streamableHttp", Antigravity uses "serverUrl"; the support article below has steps for many clients):
{ "mcpServers": { "wolfram": { "url": "https://agenttools.wolfram.com/mcp" } } }
Claude Code (add --scope user to make it available in all projects):
claude mcp add --transport http wolfram https://agenttools.wolfram.com/mcp
Visual Studio Code (the user mcp.json or the workspace's .vscode/mcp.json):
{ "servers": { "wolfram": { "type": "http", "url": "https://agenttools.wolfram.com/mcp" } } }
Claude Desktop: in Customize → Connectors, search for Wolfram and click +.
Clients that only support local (stdio) servers can use the mcp-remote bridge, which requires Node.js:
{ "mcpServers": { "wolfram": { "command": "npx", "args": ["-y", "mcp-remote@latest", "https://agenttools.wolfram.com/mcp"] } } }
The local Wolfram toolset already provides all three of these tools, so don't add the cloud server next to it. Next to another local toolset (for example WolframLanguage, which has no WolframAlpha tool), the cloud server can supply the missing tools under its own key, such as wolfram. Then ask the user to restart or reload the client.
Troubleshooting
LLMKitRequired: the localWolframAlphatoolset needs LLMKit. Use theWolframtoolset or Wolfram Cloud MCP instead.DeploymentExists: a Wolfram toolset is already deployed for that client and location. UseOverwriteTarget -> Trueto replace it.AgentSkillNotInstalled(warning): a different skill with the same name already exists. Everything else was installed. Keep the existing skill, or ask the user before usingOverwriteTarget -> All.UnknownInstallLocation: the client has no known configuration file on this operating system (for example, Claude Desktop on Linux). Use aFile[...]target.- The tools do not appear after a restart: check the configuration file that was written (
dep["ConfigFile"]for a deployment, or the"Location"of theInstallMCPServerresult), then the server log at$UserBaseDirectory/ApplicationData/Wolfram/AgentTools/Servers/<Toolset>/Log.wl. Also make sure the kernel is activated (wolframscript -code '1+1'prints2).
More Information
- Wolfram Local MCP: https://www.wolfram.com/artificial-intelligence/mcp/local/wolfram-mcp-local/
- Wolfram Cloud MCP: https://www.wolfram.com/artificial-intelligence/mcp/cloud/wolfram-mcp-cloud
- Connecting Wolfram Cloud MCP to an AI application: https://support.wolfram.com/75237
- AgentTools paclet: https://resources.wolframcloud.com/PacletRepository/resources/Wolfram/AgentTools/
Sponsors
Details
- Marketplace
- WolframResearch/AgentTools
- Source
- Assets/AgentSkills
- Category
- Community