Skip to content

Add zero-dependency Model Context Protocol (MCP) server (mathics3-mcp) - #2134

Open
KarataevDmitry wants to merge 5 commits into
Mathics3:masterfrom
AI-Guiders:feat/mcp-server
Open

KarataevDmitry wants to merge 5 commits into
Mathics3:masterfrom
AI-Guiders:feat/mcp-server

Conversation

@KarataevDmitry

Copy link
Copy Markdown

Summary

Extracted from #2133 into its own standalone, self-contained PR so it can be reviewed and tested independently of the Projective Calculus builtins.

This PR adds a lightweight, zero-dependency Model Context Protocol (MCP) JSON-RPC 2.0 stdio server (mathics3-mcp CLI entrypoint or python -m mathics.mcp_server) that allows AI coding & research agents (Claude Desktop, Cursor, OpenCode, Windsurf, etc.) to evaluate Wolfram Language expressions in a persistent MathicsSession without requiring a proprietary Wolfram Engine license.

Exposed MCP Tools

  1. wolfram_eval: Evaluate any Wolfram Language expression in the persistent MathicsSession, returning InputForm text, optional TeXForm (LaTeX), and any printed/warning messages.
  2. wolfram_integrate: Compute indefinite, definite, or improper integrals (Integrate[expr, var] or Integrate[expr, {var, lower, upper}]), with optional arbitrary-precision numeric evaluation via N[..., digits].
  3. wolfram_contour_integrate: Compute closed circular contour integrals on $\mathbb{P}^1(\mathbb{C})$ (delegates to ContourIntegrate if available, with a standalone SymPy Cauchy residue fallback on master).
  4. wolfram_residue: Compute complex Cauchy–Lagrange residues at finite poles or Infinity (delegates to Residue if available, with a standalone SymPy residue fallback on master).
  5. wolfram_pade_approximant: Compute rational Padé approximants $[m/n]$ about $x = x_0$ (delegates to PadeApproximant if available, with a standalone Toeplitz solver fallback on master).
  6. wolfram_reset_session: Reset the persistent MathicsSession and clear user definitions.

Files Changed

  • mathics/mcp_server.py: Standalone JSON-RPC 2.0 stdio MCP server (supports both newline-delimited JSON-RPC and LSP-style Content-Length framing).
  • pyproject.toml: Registers the mathics3-mcp = "mathics.mcp_server:main" console script.
  • test/test_mcp_server.py: Unit tests verifying initialize, tools/list, and tools/call across symbolic, improper, contour, residue, and Padé evaluations (2/2 passing on clean master).

@rocky

rocky commented Nov 29, 2026

Copy link
Copy Markdown
Member

I am fine with the concept. We just need to fix that mypy error.
@mmatera your thoughts?

@mmatera

mmatera commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Apart from the mypy issue, LGTM

@KarataevDmitry

Copy link
Copy Markdown
Author

Apart from the mypy issue, LGTM

Wait a minute, I look at this)
We do IntelliSense in Jupyter now))

@KarataevDmitry

Copy link
Copy Markdown
Author

Fixed the mypy type error in 99fd37164 (self.session.evaluation.evaluate(from_sympy(...)) instead of calling .evaluate(...) on BaseElement). mypy --ignore-missing-imports mathics/mcp_server.py and pytest test/test_mcp_server.py pass with 0 issues.

@rocky

rocky commented Nov 29, 2026

Copy link
Copy Markdown
Member

These are Claude Code's review comments. Decide whether we should handle these before the merge, after the merge, or not handle.

File: mathics/mcp_server.py
Recommendation: Do not return traceback.format_exc() to MCP clients. Keep stdout protocol-only and send unexpected server diagnostics to stderr or a logger. Include only a sanitized error message in the tool result.

Protocol stdout contamination
File: mathics/mcp_server.py
Recommendation: Ensure no library or evaluation output is written directly to stdout. Unexpected diagnostics, warnings, and tracebacks should use stderr; otherwise, strict MCP clients may reject the stream.

UTF-8 Content-Length framing
File: mathics/mcp_server.py
Recommendation: Content-Length counts bytes, while text-mode sys.stdin.read(length) reads characters. Read and decode binary stdin so UTF-8 requests and non-ASCII bodies are handled correctly. The same byte-based approach should be used for responses.

Notification handling
File: mathics/mcp_server.py
Recommendation: Notification handling should distinguish valid MCP notifications such as notifications/initialized from malformed no-ID JSON-RPC requests. Valid notifications should be acknowledged internally and return no response; unknown notifications or invalid requests should follow JSON-RPC/MCP semantics.

JSON-RPC batch and parse errors
File: mathics/mcp_server.py
Recommendation: A malformed line should generate a JSON-RPC parse error instead of terminating the process. The loop should also decide whether batch requests are required or explicitly rejected with -32600.

Contour pole classification
File: mathics/mcp_server.py
Comment:

This fallback converts symbolic/arb-precision radius and pole coordinates to Python floats and uses a hard-coded 1e-9 tolerance. That can incorrectly include or exclude poles and will not be exact for symbolic or high-precision inputs.

Please compare exact containment using SymPy, for example sp.re/sp.im inequalities where supported, or clearly restrict this fallback to explicitly numeric inputs and document the tolerance. The native ContourIntegrate path also has to be handled first and the fallback should not report an exact symbolic result if it was computed approximately.

SymPy fallback availability
File: mathics/mcp_server.py
Comment:

Because contour integration and residue fallback paths import SymPy inside call_tool, clients should receive a stable MCP error if SymPy is unavailable. Also clarify whether SymPy is an existing Mathics dependency or an optional dependency for these tools; “zero-dependency” should not imply that these fallbacks have no runtime dependencies.

Padé matrix edge cases
File: mathics/mcp_server.py
Comment:

Please validate m and n at the schema and implementation boundaries. Negative degrees should be rejected; singular coefficient matrices should return an MCP tool error rather than allowing LUsolve to fail or produce an unexpected exception.

Tool exception semantics
File: mathics/mcp_server.py
Recommendation: tools/call exceptions are already translated to MCP isError: true; preserve that behavior but avoid exposing implementation exceptions directly. Wrap known invalid arguments and unsupported cases in concise user-facing errors.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants