mcp-sage 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mcp_sage-0.1.0/LICENSE +21 -0
- mcp_sage-0.1.0/PKG-INFO +97 -0
- mcp_sage-0.1.0/README.md +78 -0
- mcp_sage-0.1.0/mcp_sage.egg-info/PKG-INFO +97 -0
- mcp_sage-0.1.0/mcp_sage.egg-info/SOURCES.txt +10 -0
- mcp_sage-0.1.0/mcp_sage.egg-info/dependency_links.txt +1 -0
- mcp_sage-0.1.0/mcp_sage.egg-info/entry_points.txt +2 -0
- mcp_sage-0.1.0/mcp_sage.egg-info/requires.txt +3 -0
- mcp_sage-0.1.0/mcp_sage.egg-info/top_level.txt +1 -0
- mcp_sage-0.1.0/pyproject.toml +32 -0
- mcp_sage-0.1.0/sage_repl_server.py +369 -0
- mcp_sage-0.1.0/setup.cfg +4 -0
mcp_sage-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Stefan Szeider
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
mcp_sage-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mcp-sage
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MCP server providing persistent SageMath sessions (Sage REPL over the Model Context Protocol)
|
|
5
|
+
Author: Stefan Szeider
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/szeider/sage-mcp
|
|
8
|
+
Keywords: mcp,sagemath,sage,computer-algebra,model-context-protocol,agent
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: mcp<2,>=1.0.0
|
|
16
|
+
Requires-Dist: jupyter_client>=8.0.0
|
|
17
|
+
Requires-Dist: ipykernel>=6.0.0
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# sage-mcp
|
|
21
|
+
|
|
22
|
+
An MCP server providing persistent [SageMath](https://www.sagemath.org) sessions
|
|
23
|
+
to any MCP-compatible host: Claude Code, Claude Desktop, Cursor, or an agent
|
|
24
|
+
harness such as [mcp-minion](https://github.com/szeider/mcp-solver).
|
|
25
|
+
|
|
26
|
+
Without this server, each SageMath computation runs in isolation: loading a
|
|
27
|
+
list of graphs, analyzing one, then querying its automorphism group would
|
|
28
|
+
require reloading the graph file three times. The Sage REPL server maintains
|
|
29
|
+
state across calls, enabling iterative mathematical exploration.
|
|
30
|
+
|
|
31
|
+
## Quickstart
|
|
32
|
+
|
|
33
|
+
The server is a single file using UV's inline dependency syntax (PEP 723):
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
uv run sage_repl_server.py
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Claude Code / Claude Desktop config (`.mcp.json` or `~/.claude.json`):
|
|
40
|
+
|
|
41
|
+
```json
|
|
42
|
+
{
|
|
43
|
+
"mcpServers": {
|
|
44
|
+
"sage-repl": {
|
|
45
|
+
"command": "uv",
|
|
46
|
+
"args": ["run", "/path/to/sage_repl_server.py"]
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
An optional `--directory /path/to/workdir` argument sets the server's working
|
|
53
|
+
directory, so that relative paths in Sage code (e.g. a file written by the
|
|
54
|
+
agent) resolve inside a chosen run folder.
|
|
55
|
+
|
|
56
|
+
## Tools
|
|
57
|
+
|
|
58
|
+
| Tool | Purpose |
|
|
59
|
+
|------|---------|
|
|
60
|
+
| `sage_start` | Create a new named session (auto-created on first `sage_exec` if omitted) |
|
|
61
|
+
| `sage_exec` | Execute Sage/Python code and return results |
|
|
62
|
+
| `sage_interrupt` | Send Ctrl+C to stop long-running computations |
|
|
63
|
+
| `sage_stop` | Terminate a session and release resources |
|
|
64
|
+
| `sage_list` | Show all active sessions |
|
|
65
|
+
|
|
66
|
+
`sage_exec` returns structured output with separate fields for the expression
|
|
67
|
+
result, stdout, stderr, and any errors. A configurable timeout (default 60
|
|
68
|
+
seconds) prevents hanging on infinite loops.
|
|
69
|
+
|
|
70
|
+
## Architecture
|
|
71
|
+
|
|
72
|
+
The server drives SageMath through the Jupyter kernel protocol rather than raw
|
|
73
|
+
subprocess management: reliable prompt detection, clean separation of stdout /
|
|
74
|
+
stderr / return values, native interrupt support, and robust multi-line input.
|
|
75
|
+
It injects a `KernelSpec` directly into the `KernelManager`, so SageMath's
|
|
76
|
+
bundled Python runs with ipykernel without touching the user's Jupyter
|
|
77
|
+
configuration. On session start the server imports `sage.all`, making all Sage
|
|
78
|
+
functions immediately available. See `SPEC.md` for the full tool specification.
|
|
79
|
+
|
|
80
|
+
## Requirements
|
|
81
|
+
|
|
82
|
+
- SageMath 10.6+ in `PATH` (the server launches `sage -python`)
|
|
83
|
+
- [uv](https://docs.astral.sh/uv/)
|
|
84
|
+
|
|
85
|
+
Dependencies (resolved automatically by `uv run`): `mcp` (1.x low-level server
|
|
86
|
+
API; pinned `<2`), `jupyter_client`, `ipykernel`.
|
|
87
|
+
|
|
88
|
+
## Citation
|
|
89
|
+
|
|
90
|
+
This server was built for and used in the experiments of:
|
|
91
|
+
|
|
92
|
+
> *Neurosymbolic Discovery of Algebraic Graph Constructions.*
|
|
93
|
+
> NeSy 2026. (Full citation and archive DOI to appear.)
|
|
94
|
+
|
|
95
|
+
## License
|
|
96
|
+
|
|
97
|
+
MIT
|
mcp_sage-0.1.0/README.md
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# sage-mcp
|
|
2
|
+
|
|
3
|
+
An MCP server providing persistent [SageMath](https://www.sagemath.org) sessions
|
|
4
|
+
to any MCP-compatible host: Claude Code, Claude Desktop, Cursor, or an agent
|
|
5
|
+
harness such as [mcp-minion](https://github.com/szeider/mcp-solver).
|
|
6
|
+
|
|
7
|
+
Without this server, each SageMath computation runs in isolation: loading a
|
|
8
|
+
list of graphs, analyzing one, then querying its automorphism group would
|
|
9
|
+
require reloading the graph file three times. The Sage REPL server maintains
|
|
10
|
+
state across calls, enabling iterative mathematical exploration.
|
|
11
|
+
|
|
12
|
+
## Quickstart
|
|
13
|
+
|
|
14
|
+
The server is a single file using UV's inline dependency syntax (PEP 723):
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
uv run sage_repl_server.py
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Claude Code / Claude Desktop config (`.mcp.json` or `~/.claude.json`):
|
|
21
|
+
|
|
22
|
+
```json
|
|
23
|
+
{
|
|
24
|
+
"mcpServers": {
|
|
25
|
+
"sage-repl": {
|
|
26
|
+
"command": "uv",
|
|
27
|
+
"args": ["run", "/path/to/sage_repl_server.py"]
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
An optional `--directory /path/to/workdir` argument sets the server's working
|
|
34
|
+
directory, so that relative paths in Sage code (e.g. a file written by the
|
|
35
|
+
agent) resolve inside a chosen run folder.
|
|
36
|
+
|
|
37
|
+
## Tools
|
|
38
|
+
|
|
39
|
+
| Tool | Purpose |
|
|
40
|
+
|------|---------|
|
|
41
|
+
| `sage_start` | Create a new named session (auto-created on first `sage_exec` if omitted) |
|
|
42
|
+
| `sage_exec` | Execute Sage/Python code and return results |
|
|
43
|
+
| `sage_interrupt` | Send Ctrl+C to stop long-running computations |
|
|
44
|
+
| `sage_stop` | Terminate a session and release resources |
|
|
45
|
+
| `sage_list` | Show all active sessions |
|
|
46
|
+
|
|
47
|
+
`sage_exec` returns structured output with separate fields for the expression
|
|
48
|
+
result, stdout, stderr, and any errors. A configurable timeout (default 60
|
|
49
|
+
seconds) prevents hanging on infinite loops.
|
|
50
|
+
|
|
51
|
+
## Architecture
|
|
52
|
+
|
|
53
|
+
The server drives SageMath through the Jupyter kernel protocol rather than raw
|
|
54
|
+
subprocess management: reliable prompt detection, clean separation of stdout /
|
|
55
|
+
stderr / return values, native interrupt support, and robust multi-line input.
|
|
56
|
+
It injects a `KernelSpec` directly into the `KernelManager`, so SageMath's
|
|
57
|
+
bundled Python runs with ipykernel without touching the user's Jupyter
|
|
58
|
+
configuration. On session start the server imports `sage.all`, making all Sage
|
|
59
|
+
functions immediately available. See `SPEC.md` for the full tool specification.
|
|
60
|
+
|
|
61
|
+
## Requirements
|
|
62
|
+
|
|
63
|
+
- SageMath 10.6+ in `PATH` (the server launches `sage -python`)
|
|
64
|
+
- [uv](https://docs.astral.sh/uv/)
|
|
65
|
+
|
|
66
|
+
Dependencies (resolved automatically by `uv run`): `mcp` (1.x low-level server
|
|
67
|
+
API; pinned `<2`), `jupyter_client`, `ipykernel`.
|
|
68
|
+
|
|
69
|
+
## Citation
|
|
70
|
+
|
|
71
|
+
This server was built for and used in the experiments of:
|
|
72
|
+
|
|
73
|
+
> *Neurosymbolic Discovery of Algebraic Graph Constructions.*
|
|
74
|
+
> NeSy 2026. (Full citation and archive DOI to appear.)
|
|
75
|
+
|
|
76
|
+
## License
|
|
77
|
+
|
|
78
|
+
MIT
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mcp-sage
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MCP server providing persistent SageMath sessions (Sage REPL over the Model Context Protocol)
|
|
5
|
+
Author: Stefan Szeider
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/szeider/sage-mcp
|
|
8
|
+
Keywords: mcp,sagemath,sage,computer-algebra,model-context-protocol,agent
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: mcp<2,>=1.0.0
|
|
16
|
+
Requires-Dist: jupyter_client>=8.0.0
|
|
17
|
+
Requires-Dist: ipykernel>=6.0.0
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# sage-mcp
|
|
21
|
+
|
|
22
|
+
An MCP server providing persistent [SageMath](https://www.sagemath.org) sessions
|
|
23
|
+
to any MCP-compatible host: Claude Code, Claude Desktop, Cursor, or an agent
|
|
24
|
+
harness such as [mcp-minion](https://github.com/szeider/mcp-solver).
|
|
25
|
+
|
|
26
|
+
Without this server, each SageMath computation runs in isolation: loading a
|
|
27
|
+
list of graphs, analyzing one, then querying its automorphism group would
|
|
28
|
+
require reloading the graph file three times. The Sage REPL server maintains
|
|
29
|
+
state across calls, enabling iterative mathematical exploration.
|
|
30
|
+
|
|
31
|
+
## Quickstart
|
|
32
|
+
|
|
33
|
+
The server is a single file using UV's inline dependency syntax (PEP 723):
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
uv run sage_repl_server.py
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Claude Code / Claude Desktop config (`.mcp.json` or `~/.claude.json`):
|
|
40
|
+
|
|
41
|
+
```json
|
|
42
|
+
{
|
|
43
|
+
"mcpServers": {
|
|
44
|
+
"sage-repl": {
|
|
45
|
+
"command": "uv",
|
|
46
|
+
"args": ["run", "/path/to/sage_repl_server.py"]
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
An optional `--directory /path/to/workdir` argument sets the server's working
|
|
53
|
+
directory, so that relative paths in Sage code (e.g. a file written by the
|
|
54
|
+
agent) resolve inside a chosen run folder.
|
|
55
|
+
|
|
56
|
+
## Tools
|
|
57
|
+
|
|
58
|
+
| Tool | Purpose |
|
|
59
|
+
|------|---------|
|
|
60
|
+
| `sage_start` | Create a new named session (auto-created on first `sage_exec` if omitted) |
|
|
61
|
+
| `sage_exec` | Execute Sage/Python code and return results |
|
|
62
|
+
| `sage_interrupt` | Send Ctrl+C to stop long-running computations |
|
|
63
|
+
| `sage_stop` | Terminate a session and release resources |
|
|
64
|
+
| `sage_list` | Show all active sessions |
|
|
65
|
+
|
|
66
|
+
`sage_exec` returns structured output with separate fields for the expression
|
|
67
|
+
result, stdout, stderr, and any errors. A configurable timeout (default 60
|
|
68
|
+
seconds) prevents hanging on infinite loops.
|
|
69
|
+
|
|
70
|
+
## Architecture
|
|
71
|
+
|
|
72
|
+
The server drives SageMath through the Jupyter kernel protocol rather than raw
|
|
73
|
+
subprocess management: reliable prompt detection, clean separation of stdout /
|
|
74
|
+
stderr / return values, native interrupt support, and robust multi-line input.
|
|
75
|
+
It injects a `KernelSpec` directly into the `KernelManager`, so SageMath's
|
|
76
|
+
bundled Python runs with ipykernel without touching the user's Jupyter
|
|
77
|
+
configuration. On session start the server imports `sage.all`, making all Sage
|
|
78
|
+
functions immediately available. See `SPEC.md` for the full tool specification.
|
|
79
|
+
|
|
80
|
+
## Requirements
|
|
81
|
+
|
|
82
|
+
- SageMath 10.6+ in `PATH` (the server launches `sage -python`)
|
|
83
|
+
- [uv](https://docs.astral.sh/uv/)
|
|
84
|
+
|
|
85
|
+
Dependencies (resolved automatically by `uv run`): `mcp` (1.x low-level server
|
|
86
|
+
API; pinned `<2`), `jupyter_client`, `ipykernel`.
|
|
87
|
+
|
|
88
|
+
## Citation
|
|
89
|
+
|
|
90
|
+
This server was built for and used in the experiments of:
|
|
91
|
+
|
|
92
|
+
> *Neurosymbolic Discovery of Algebraic Graph Constructions.*
|
|
93
|
+
> NeSy 2026. (Full citation and archive DOI to appear.)
|
|
94
|
+
|
|
95
|
+
## License
|
|
96
|
+
|
|
97
|
+
MIT
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
sage_repl_server.py
|
|
5
|
+
mcp_sage.egg-info/PKG-INFO
|
|
6
|
+
mcp_sage.egg-info/SOURCES.txt
|
|
7
|
+
mcp_sage.egg-info/dependency_links.txt
|
|
8
|
+
mcp_sage.egg-info/entry_points.txt
|
|
9
|
+
mcp_sage.egg-info/requires.txt
|
|
10
|
+
mcp_sage.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sage_repl_server
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "mcp-sage"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "MCP server providing persistent SageMath sessions (Sage REPL over the Model Context Protocol)"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = { text = "MIT" }
|
|
7
|
+
authors = [{ name = "Stefan Szeider" }]
|
|
8
|
+
requires-python = ">=3.11"
|
|
9
|
+
dependencies = [
|
|
10
|
+
"mcp>=1.0.0,<2",
|
|
11
|
+
"jupyter_client>=8.0.0",
|
|
12
|
+
"ipykernel>=6.0.0",
|
|
13
|
+
]
|
|
14
|
+
keywords = ["mcp", "sagemath", "sage", "computer-algebra", "model-context-protocol", "agent"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Topic :: Scientific/Engineering :: Mathematics",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.scripts]
|
|
22
|
+
mcp-sage = "sage_repl_server:cli"
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Repository = "https://github.com/szeider/sage-mcp"
|
|
26
|
+
|
|
27
|
+
[build-system]
|
|
28
|
+
requires = ["setuptools>=68"]
|
|
29
|
+
build-backend = "setuptools.build_meta"
|
|
30
|
+
|
|
31
|
+
[tool.setuptools]
|
|
32
|
+
py-modules = ["sage_repl_server"]
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
#!/usr/bin/env -S uv run
|
|
2
|
+
# /// script
|
|
3
|
+
# requires-python = ">=3.11"
|
|
4
|
+
# dependencies = [
|
|
5
|
+
# "mcp>=1.0.0,<2",
|
|
6
|
+
# "jupyter_client>=8.0.0",
|
|
7
|
+
# "ipykernel>=6.0.0",
|
|
8
|
+
# ]
|
|
9
|
+
# ///
|
|
10
|
+
"""
|
|
11
|
+
Sage REPL MCP Server
|
|
12
|
+
|
|
13
|
+
A minimal MCP server providing persistent Sage sessions via Jupyter kernel.
|
|
14
|
+
|
|
15
|
+
Usage:
|
|
16
|
+
uv run sage_repl_server.py
|
|
17
|
+
uv run sage_repl_server.py --directory /path/to/experiment
|
|
18
|
+
|
|
19
|
+
Claude Code config (~/.claude.json or project .mcp.json):
|
|
20
|
+
{
|
|
21
|
+
"mcpServers": {
|
|
22
|
+
"sage-repl": {
|
|
23
|
+
"command": "uv",
|
|
24
|
+
"args": ["run", "/path/to/sage_repl_server.py"]
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
With working directory:
|
|
30
|
+
{
|
|
31
|
+
"mcpServers": {
|
|
32
|
+
"sage-repl": {
|
|
33
|
+
"command": "uv",
|
|
34
|
+
"args": ["run", "/path/to/sage_repl_server.py", "--directory", "/path/to/experiment"]
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
import argparse
|
|
41
|
+
import asyncio
|
|
42
|
+
import atexit
|
|
43
|
+
import os
|
|
44
|
+
import re
|
|
45
|
+
import shutil
|
|
46
|
+
from queue import Empty
|
|
47
|
+
from typing import Any
|
|
48
|
+
|
|
49
|
+
from jupyter_client import KernelManager
|
|
50
|
+
from jupyter_client.kernelspec import KernelSpec
|
|
51
|
+
from mcp.server import Server
|
|
52
|
+
from mcp.server.stdio import stdio_server
|
|
53
|
+
from mcp.types import TextContent, Tool
|
|
54
|
+
|
|
55
|
+
# --- Kernel Management ---
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# GAP crash detection - interrupt after repeated crashes to prevent fork bomb
|
|
59
|
+
GAP_CRASH_PATTERN = re.compile(r"Gap crashed|Restarting Gap", re.IGNORECASE)
|
|
60
|
+
GAP_CRASH_LIMIT = 3
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class SageKernel:
|
|
64
|
+
"""Manages a Sage IPython kernel for persistent code execution."""
|
|
65
|
+
|
|
66
|
+
def __init__(self):
|
|
67
|
+
if not shutil.which("sage"):
|
|
68
|
+
raise FileNotFoundError("'sage' not found in PATH")
|
|
69
|
+
|
|
70
|
+
# Use sage's Python - inject KernelSpec directly to bypass lookup
|
|
71
|
+
sage_cmd = [
|
|
72
|
+
"sage",
|
|
73
|
+
"-python",
|
|
74
|
+
"-m",
|
|
75
|
+
"ipykernel_launcher",
|
|
76
|
+
"-f",
|
|
77
|
+
"{connection_file}",
|
|
78
|
+
]
|
|
79
|
+
self.km = KernelManager()
|
|
80
|
+
self.km._kernel_spec = KernelSpec(
|
|
81
|
+
resource_dir="",
|
|
82
|
+
argv=sage_cmd,
|
|
83
|
+
display_name="Sage",
|
|
84
|
+
language="python",
|
|
85
|
+
)
|
|
86
|
+
self.km.start_kernel()
|
|
87
|
+
self.kc = self.km.client()
|
|
88
|
+
self.kc.start_channels()
|
|
89
|
+
self.kc.wait_for_ready(timeout=30)
|
|
90
|
+
|
|
91
|
+
# Import sage.all at startup
|
|
92
|
+
self._execute_silent("from sage.all import *")
|
|
93
|
+
|
|
94
|
+
def _execute_silent(self, code: str) -> None:
|
|
95
|
+
"""Execute code without returning output."""
|
|
96
|
+
msg_id = self.kc.execute(code, silent=True)
|
|
97
|
+
# Wait for completion
|
|
98
|
+
while True:
|
|
99
|
+
try:
|
|
100
|
+
msg = self.kc.get_iopub_msg(timeout=30)
|
|
101
|
+
if (
|
|
102
|
+
msg["msg_type"] == "status"
|
|
103
|
+
and msg["content"]["execution_state"] == "idle"
|
|
104
|
+
and msg["parent_header"].get("msg_id") == msg_id
|
|
105
|
+
):
|
|
106
|
+
break
|
|
107
|
+
except Empty:
|
|
108
|
+
break
|
|
109
|
+
|
|
110
|
+
def execute(self, code: str, timeout: int = 60) -> dict[str, Any]:
|
|
111
|
+
"""Execute code and return structured output."""
|
|
112
|
+
msg_id = self.kc.execute(code, silent=False, store_history=True)
|
|
113
|
+
|
|
114
|
+
output = {"stdout": "", "stderr": "", "result": None, "error": None}
|
|
115
|
+
gap_crash_count = 0
|
|
116
|
+
|
|
117
|
+
while True:
|
|
118
|
+
try:
|
|
119
|
+
msg = self.kc.get_iopub_msg(timeout=timeout)
|
|
120
|
+
|
|
121
|
+
# Only process our messages
|
|
122
|
+
if msg["parent_header"].get("msg_id") != msg_id:
|
|
123
|
+
continue
|
|
124
|
+
|
|
125
|
+
msg_type = msg["msg_type"]
|
|
126
|
+
content = msg["content"]
|
|
127
|
+
|
|
128
|
+
if msg_type == "stream":
|
|
129
|
+
if content["name"] == "stdout":
|
|
130
|
+
output["stdout"] += content["text"]
|
|
131
|
+
elif content["name"] == "stderr":
|
|
132
|
+
output["stderr"] += content["text"]
|
|
133
|
+
# Detect GAP crash loop to prevent fork bomb
|
|
134
|
+
if GAP_CRASH_PATTERN.search(content["text"]):
|
|
135
|
+
gap_crash_count += 1
|
|
136
|
+
if gap_crash_count >= GAP_CRASH_LIMIT:
|
|
137
|
+
self.interrupt()
|
|
138
|
+
output["error"] = (
|
|
139
|
+
f"GAP crash loop detected ({gap_crash_count} crashes). "
|
|
140
|
+
"Execution interrupted to prevent runaway processes. "
|
|
141
|
+
"Avoid structure_description() on this input."
|
|
142
|
+
)
|
|
143
|
+
break
|
|
144
|
+
elif msg_type == "execute_result":
|
|
145
|
+
output["result"] = content["data"].get("text/plain", "")
|
|
146
|
+
elif msg_type == "error":
|
|
147
|
+
output["error"] = f"{content['ename']}: {content['evalue']}"
|
|
148
|
+
elif msg_type == "status" and content["execution_state"] == "idle":
|
|
149
|
+
break
|
|
150
|
+
except Empty:
|
|
151
|
+
output["error"] = "Timeout: kernel may still be busy"
|
|
152
|
+
break
|
|
153
|
+
|
|
154
|
+
return output
|
|
155
|
+
|
|
156
|
+
def interrupt(self) -> None:
|
|
157
|
+
"""Interrupt the current execution."""
|
|
158
|
+
self.km.interrupt_kernel()
|
|
159
|
+
|
|
160
|
+
def shutdown(self) -> None:
|
|
161
|
+
"""Shutdown the kernel."""
|
|
162
|
+
try:
|
|
163
|
+
self.kc.stop_channels()
|
|
164
|
+
if self.km.is_alive():
|
|
165
|
+
self.km.shutdown_kernel(now=True)
|
|
166
|
+
except Exception:
|
|
167
|
+
pass
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# --- Global State ---
|
|
171
|
+
|
|
172
|
+
sessions: dict[str, SageKernel] = {}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def cleanup():
|
|
176
|
+
"""Cleanup all sessions on exit."""
|
|
177
|
+
for kernel in sessions.values():
|
|
178
|
+
kernel.shutdown()
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
atexit.register(cleanup)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# --- MCP Server ---
|
|
185
|
+
|
|
186
|
+
server = Server("sage-repl")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@server.list_tools()
|
|
190
|
+
async def list_tools() -> list[Tool]:
|
|
191
|
+
return [
|
|
192
|
+
Tool(
|
|
193
|
+
name="sage_start",
|
|
194
|
+
description="Start a new Sage session. Returns session ID.",
|
|
195
|
+
inputSchema={
|
|
196
|
+
"type": "object",
|
|
197
|
+
"properties": {
|
|
198
|
+
"session_id": {
|
|
199
|
+
"type": "string",
|
|
200
|
+
"description": "Optional session ID (default: 'default')",
|
|
201
|
+
"default": "default",
|
|
202
|
+
}
|
|
203
|
+
},
|
|
204
|
+
},
|
|
205
|
+
),
|
|
206
|
+
Tool(
|
|
207
|
+
name="sage_exec",
|
|
208
|
+
description="Execute Sage/Python code in a session. Returns result, stdout, stderr.",
|
|
209
|
+
inputSchema={
|
|
210
|
+
"type": "object",
|
|
211
|
+
"properties": {
|
|
212
|
+
"code": {
|
|
213
|
+
"type": "string",
|
|
214
|
+
"description": "Sage/Python code to execute",
|
|
215
|
+
},
|
|
216
|
+
"session_id": {
|
|
217
|
+
"type": "string",
|
|
218
|
+
"description": "Session ID (default: 'default')",
|
|
219
|
+
"default": "default",
|
|
220
|
+
},
|
|
221
|
+
"timeout": {
|
|
222
|
+
"type": "integer",
|
|
223
|
+
"description": "Execution timeout in seconds (default: 60)",
|
|
224
|
+
"default": 60,
|
|
225
|
+
},
|
|
226
|
+
},
|
|
227
|
+
"required": ["code"],
|
|
228
|
+
},
|
|
229
|
+
),
|
|
230
|
+
Tool(
|
|
231
|
+
name="sage_interrupt",
|
|
232
|
+
description="Interrupt a running computation.",
|
|
233
|
+
inputSchema={
|
|
234
|
+
"type": "object",
|
|
235
|
+
"properties": {
|
|
236
|
+
"session_id": {
|
|
237
|
+
"type": "string",
|
|
238
|
+
"description": "Session ID (default: 'default')",
|
|
239
|
+
"default": "default",
|
|
240
|
+
}
|
|
241
|
+
},
|
|
242
|
+
},
|
|
243
|
+
),
|
|
244
|
+
Tool(
|
|
245
|
+
name="sage_stop",
|
|
246
|
+
description="Stop a Sage session and free resources.",
|
|
247
|
+
inputSchema={
|
|
248
|
+
"type": "object",
|
|
249
|
+
"properties": {
|
|
250
|
+
"session_id": {
|
|
251
|
+
"type": "string",
|
|
252
|
+
"description": "Session ID (default: 'default')",
|
|
253
|
+
"default": "default",
|
|
254
|
+
}
|
|
255
|
+
},
|
|
256
|
+
},
|
|
257
|
+
),
|
|
258
|
+
Tool(
|
|
259
|
+
name="sage_list",
|
|
260
|
+
description="List all active Sage sessions.",
|
|
261
|
+
inputSchema={"type": "object", "properties": {}},
|
|
262
|
+
),
|
|
263
|
+
]
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
@server.call_tool()
|
|
267
|
+
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
|
|
268
|
+
if name == "sage_start":
|
|
269
|
+
session_id = arguments.get("session_id", "default")
|
|
270
|
+
|
|
271
|
+
if session_id in sessions:
|
|
272
|
+
return [
|
|
273
|
+
TextContent(type="text", text=f"Session '{session_id}' already exists")
|
|
274
|
+
]
|
|
275
|
+
|
|
276
|
+
try:
|
|
277
|
+
sessions[session_id] = SageKernel()
|
|
278
|
+
return [
|
|
279
|
+
TextContent(
|
|
280
|
+
type="text", text=f"Session '{session_id}' started. Sage is ready."
|
|
281
|
+
)
|
|
282
|
+
]
|
|
283
|
+
except Exception as e:
|
|
284
|
+
return [TextContent(type="text", text=f"Failed to start session: {e}")]
|
|
285
|
+
|
|
286
|
+
elif name == "sage_exec":
|
|
287
|
+
session_id = arguments.get("session_id", "default")
|
|
288
|
+
code = arguments.get("code", "")
|
|
289
|
+
timeout = arguments.get("timeout", 60)
|
|
290
|
+
|
|
291
|
+
if session_id not in sessions:
|
|
292
|
+
# Auto-start session
|
|
293
|
+
try:
|
|
294
|
+
sessions[session_id] = SageKernel()
|
|
295
|
+
except Exception as e:
|
|
296
|
+
return [TextContent(type="text", text=f"Failed to start session: {e}")]
|
|
297
|
+
|
|
298
|
+
kernel = sessions[session_id]
|
|
299
|
+
output = await asyncio.to_thread(kernel.execute, code, timeout)
|
|
300
|
+
|
|
301
|
+
# Format output
|
|
302
|
+
parts = []
|
|
303
|
+
if output["result"]:
|
|
304
|
+
parts.append(output["result"])
|
|
305
|
+
if output["stdout"]:
|
|
306
|
+
parts.append(f"[stdout]\n{output['stdout']}")
|
|
307
|
+
if output["stderr"]:
|
|
308
|
+
parts.append(f"[stderr]\n{output['stderr']}")
|
|
309
|
+
if output["error"]:
|
|
310
|
+
parts.append(f"[error]\n{output['error']}")
|
|
311
|
+
|
|
312
|
+
result = "\n".join(parts) if parts else "(no output)"
|
|
313
|
+
return [TextContent(type="text", text=result)]
|
|
314
|
+
|
|
315
|
+
elif name == "sage_interrupt":
|
|
316
|
+
session_id = arguments.get("session_id", "default")
|
|
317
|
+
|
|
318
|
+
if session_id not in sessions:
|
|
319
|
+
return [TextContent(type="text", text=f"No session '{session_id}'")]
|
|
320
|
+
|
|
321
|
+
sessions[session_id].interrupt()
|
|
322
|
+
return [TextContent(type="text", text=f"Interrupted session '{session_id}'")]
|
|
323
|
+
|
|
324
|
+
elif name == "sage_stop":
|
|
325
|
+
session_id = arguments.get("session_id", "default")
|
|
326
|
+
|
|
327
|
+
if session_id not in sessions:
|
|
328
|
+
return [TextContent(type="text", text=f"No session '{session_id}'")]
|
|
329
|
+
|
|
330
|
+
sessions[session_id].shutdown()
|
|
331
|
+
del sessions[session_id]
|
|
332
|
+
return [TextContent(type="text", text=f"Session '{session_id}' stopped")]
|
|
333
|
+
|
|
334
|
+
elif name == "sage_list":
|
|
335
|
+
if not sessions:
|
|
336
|
+
return [TextContent(type="text", text="No active sessions")]
|
|
337
|
+
|
|
338
|
+
lines = [f"Active sessions: {len(sessions)}"]
|
|
339
|
+
for sid in sessions:
|
|
340
|
+
lines.append(f" - {sid}")
|
|
341
|
+
return [TextContent(type="text", text="\n".join(lines))]
|
|
342
|
+
|
|
343
|
+
else:
|
|
344
|
+
return [TextContent(type="text", text=f"Unknown tool: {name}")]
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
async def main():
|
|
348
|
+
async with stdio_server() as (read, write):
|
|
349
|
+
await server.run(read, write, server.create_initialization_options())
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def cli():
|
|
353
|
+
parser = argparse.ArgumentParser(description="Sage REPL MCP Server")
|
|
354
|
+
parser.add_argument(
|
|
355
|
+
"--directory",
|
|
356
|
+
type=str,
|
|
357
|
+
default=None,
|
|
358
|
+
help="Change to this directory before starting the server",
|
|
359
|
+
)
|
|
360
|
+
args = parser.parse_args()
|
|
361
|
+
|
|
362
|
+
if args.directory:
|
|
363
|
+
os.chdir(args.directory)
|
|
364
|
+
|
|
365
|
+
asyncio.run(main())
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
if __name__ == "__main__":
|
|
369
|
+
cli()
|
mcp_sage-0.1.0/setup.cfg
ADDED