scmcp-shared 0.2.5__tar.gz → 0.3.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.
Files changed (30) hide show
  1. scmcp_shared-0.3.0/.github/release.yml +32 -0
  2. {scmcp_shared-0.2.5 → scmcp_shared-0.3.0}/PKG-INFO +1 -1
  3. scmcp_shared-0.3.0/src/scmcp_shared/__init__.py +3 -0
  4. scmcp_shared-0.3.0/src/scmcp_shared/cli.py +96 -0
  5. {scmcp_shared-0.2.5 → scmcp_shared-0.3.0}/src/scmcp_shared/schema/__init__.py +9 -0
  6. {scmcp_shared-0.2.5 → scmcp_shared-0.3.0}/src/scmcp_shared/schema/io.py +0 -4
  7. {scmcp_shared-0.2.5 → scmcp_shared-0.3.0}/src/scmcp_shared/schema/tl.py +0 -5
  8. scmcp_shared-0.3.0/src/scmcp_shared/server/__init__.py +13 -0
  9. scmcp_shared-0.3.0/src/scmcp_shared/server/base.py +153 -0
  10. scmcp_shared-0.3.0/src/scmcp_shared/server/io.py +84 -0
  11. scmcp_shared-0.3.0/src/scmcp_shared/server/pl.py +315 -0
  12. scmcp_shared-0.3.0/src/scmcp_shared/server/pp.py +325 -0
  13. scmcp_shared-0.3.0/src/scmcp_shared/server/tl.py +398 -0
  14. scmcp_shared-0.3.0/src/scmcp_shared/server/util.py +251 -0
  15. {scmcp_shared-0.2.5 → scmcp_shared-0.3.0}/src/scmcp_shared/util.py +82 -17
  16. scmcp_shared-0.2.5/src/scmcp_shared/__init__.py +0 -3
  17. scmcp_shared-0.2.5/src/scmcp_shared/server/__init__.py +0 -51
  18. scmcp_shared-0.2.5/src/scmcp_shared/server/io.py +0 -84
  19. scmcp_shared-0.2.5/src/scmcp_shared/server/pl.py +0 -366
  20. scmcp_shared-0.2.5/src/scmcp_shared/server/pp.py +0 -379
  21. scmcp_shared-0.2.5/src/scmcp_shared/server/tl.py +0 -447
  22. scmcp_shared-0.2.5/src/scmcp_shared/server/util.py +0 -261
  23. {scmcp_shared-0.2.5 → scmcp_shared-0.3.0}/.github/workflows/publish.yml +0 -0
  24. {scmcp_shared-0.2.5 → scmcp_shared-0.3.0}/LICENSE +0 -0
  25. {scmcp_shared-0.2.5 → scmcp_shared-0.3.0}/README.md +0 -0
  26. {scmcp_shared-0.2.5 → scmcp_shared-0.3.0}/pyproject.toml +0 -0
  27. {scmcp_shared-0.2.5 → scmcp_shared-0.3.0}/src/scmcp_shared/logging_config.py +0 -0
  28. {scmcp_shared-0.2.5 → scmcp_shared-0.3.0}/src/scmcp_shared/schema/pl.py +0 -0
  29. {scmcp_shared-0.2.5 → scmcp_shared-0.3.0}/src/scmcp_shared/schema/pp.py +0 -0
  30. {scmcp_shared-0.2.5 → scmcp_shared-0.3.0}/src/scmcp_shared/schema/util.py +0 -0
@@ -0,0 +1,32 @@
1
+ changelog:
2
+ exclude:
3
+ labels:
4
+ - ignore in release notes
5
+
6
+ categories:
7
+ - title: New Features 🎉
8
+ labels:
9
+ - feature
10
+ - enhancement
11
+ exclude:
12
+ labels:
13
+ - breaking change
14
+
15
+ - title: Fixes 🐞
16
+ labels:
17
+ - bug
18
+ exclude:
19
+ labels:
20
+ - breaking change
21
+
22
+ - title: Breaking Changes 🛫
23
+ labels:
24
+ - breaking change
25
+
26
+ - title: Docs 📚
27
+ labels:
28
+ - documentation
29
+
30
+ - title: Other Changes 🦾
31
+ labels:
32
+ - "*"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: scmcp_shared
3
- Version: 0.2.5
3
+ Version: 0.3.0
4
4
  Summary: A shared function libray for scmcphub
5
5
  Author-email: shuang <hsh-me@outlook.com>
6
6
  License: BSD 3-Clause License
@@ -0,0 +1,3 @@
1
+
2
+ __version__ = "0.3.0"
3
+
@@ -0,0 +1,96 @@
1
+ import typer
2
+ from typing import Optional, Union, Type
3
+ from enum import Enum
4
+ from .util import add_figure_route, set_env,setup_mcp
5
+
6
+
7
+ class TransportEnum(str, Enum):
8
+ STDIO = "stdio"
9
+ SSE = "sse"
10
+ SHTTP = "shttp"
11
+
12
+ @property
13
+ def transport_value(self) -> str:
14
+ """Get the actual transport value to use."""
15
+ if self == TransportEnum.SHTTP:
16
+ return "streamable-http"
17
+ return self.value
18
+
19
+
20
+ class ModuleEnum(str, Enum):
21
+ """Base class for module types."""
22
+ ALL = "all"
23
+
24
+
25
+
26
+ class MCPCLI:
27
+ """Base class for CLI applications with support for dynamic modules and parameters."""
28
+
29
+ def __init__(self, name: str, help_text: str, manager=None, modules=ModuleEnum):
30
+ self.name = name
31
+ self.modules = modules
32
+ self.manager = manager
33
+ self.app = typer.Typer(
34
+ name=name,
35
+ help=help_text,
36
+ add_completion=False,
37
+ no_args_is_help=True,
38
+ )
39
+ self._setup_commands()
40
+
41
+ def _setup_commands(self):
42
+ """Setup the main commands for the CLI."""
43
+ self.app.command(name="run", help="Start the server with the specified configuration")(self.run_command())
44
+ self.app.callback()(self._callback)
45
+
46
+ def run_command(self):
47
+ def _run_command(
48
+ log_file: Optional[str] = typer.Option(None, "--log-file", help="log file path, use stdout if None"),
49
+ transport: TransportEnum = typer.Option(TransportEnum.STDIO, "-t", "--transport", help="specify transport type",
50
+ case_sensitive=False),
51
+ port: int = typer.Option(8000, "-p", "--port", help="transport port"),
52
+ host: str = typer.Option("127.0.0.1", "--host", help="transport host"),
53
+ forward: str = typer.Option(None, "-f", "--forward", help="forward request to another server"),
54
+ module: list[self.modules] = typer.Option(
55
+ [self.modules.ALL],
56
+ "-m",
57
+ "--module",
58
+ help="specify module to run"
59
+ ),
60
+ ):
61
+ """Start the server with the specified configuration."""
62
+ if "all" in module:
63
+ modules = None
64
+ elif isinstance(module, list) and bool(module):
65
+ modules = [m.value for m in module]
66
+ self.mcp = self.manager(self.name, include_modules=modules).mcp
67
+
68
+ self.run_mcp(log_file, forward, transport, host, port)
69
+ return _run_command
70
+
71
+
72
+ def _callback(self):
73
+ """Liana MCP CLI root command."""
74
+ pass
75
+
76
+ def run_mcp(self, log_file, forward, transport, host, port):
77
+ set_env(log_file, forward, transport, host, port)
78
+ from .logging_config import setup_logger
79
+ setup_logger(log_file)
80
+ if transport == "stdio":
81
+ self.mcp.run()
82
+ elif transport in ["sse", "shttp"]:
83
+ add_figure_route(self.mcp)
84
+ transport = transport.transport_value
85
+ self.mcp.run(
86
+ transport=transport,
87
+ host=host,
88
+ port=port,
89
+ log_level="info"
90
+ )
91
+
92
+ def run_cli(self, mcp=None, module_dic=None):
93
+ """Run the CLI application."""
94
+ self.mcp = mcp
95
+ self.module_dic = module_dic
96
+ self.app()
@@ -11,3 +11,12 @@ class AdataModel(BaseModel):
11
11
  model_config = ConfigDict(
12
12
  extra="ignore"
13
13
  )
14
+
15
+ class AdataInfo(BaseModel):
16
+ """Input schema for the adata tool."""
17
+ sampleid: str | None = Field(default=None, description="adata sampleid")
18
+ adtype: str = Field(default="exp", description="The input adata.X data type for preprocess/analysis/plotting")
19
+
20
+ model_config = ConfigDict(
21
+ extra="ignore"
22
+ )
@@ -22,10 +22,6 @@ class ReadModel(BaseModel):
22
22
  default=None,
23
23
  description="Name of sheet/table in hdf5 or Excel file."
24
24
  )
25
- ext: str = Field(
26
- default=None,
27
- description="Extension that indicates the file type. If None, uses extension of filename."
28
- )
29
25
  delimiter: str = Field(
30
26
  default=None,
31
27
  description="Delimiter that separates data within text file. If None, will split at arbitrary number of white spaces, which is different from enforcing splitting at any single white space."
@@ -300,11 +300,6 @@ class LeidenModel(BaseModel):
300
300
  description="Which package's implementation to use."
301
301
  )
302
302
 
303
- clustering_args: Optional[Dict[str, Any]] = Field(
304
- default=None,
305
- description="Any further arguments to pass to the clustering algorithm."
306
- )
307
-
308
303
  @field_validator('resolution')
309
304
  def validate_resolution(cls, v: float) -> float:
310
305
  """Validate resolution is positive"""
@@ -0,0 +1,13 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterable, AsyncIterator
4
+ from typing import Any, Dict, List, Optional
5
+ from contextlib import asynccontextmanager
6
+ import asyncio
7
+
8
+ from .base import BaseMCP,AdataState,BaseMCPManager
9
+ from .io import ScanpyIOMCP, io_mcp
10
+ from .util import ScanpyUtilMCP
11
+ from .pl import ScanpyPlottingMCP
12
+ from .pp import ScanpyPreprocessingMCP
13
+ from .tl import ScanpyToolsMCP
@@ -0,0 +1,153 @@
1
+ import inspect
2
+ from fastmcp import FastMCP
3
+ from ..schema import AdataInfo
4
+ from ..util import filter_tools
5
+ from collections.abc import AsyncIterator
6
+ from contextlib import asynccontextmanager
7
+ import asyncio
8
+ from typing import Optional, List, Any, Iterable
9
+
10
+
11
+ class BaseMCP:
12
+ """Base class for all Scanpy MCP classes."""
13
+
14
+ def __init__(self, name: str, include_tools: list = None, exclude_tools: list = None, AdataInfo = AdataInfo):
15
+ """
16
+ Initialize BaseMCP with optional tool filtering.
17
+
18
+ Args:
19
+ name (str): Name of the MCP server
20
+ include_tools (list, optional): List of tool names to include. If None, all tools are included.
21
+ exclude_tools (list, optional): List of tool names to exclude. If None, no tools are excluded.
22
+ AdataInfo: The AdataInfo class to use for type annotations.
23
+ """
24
+ self.mcp = FastMCP(name)
25
+ self.include_tools = include_tools
26
+ self.exclude_tools = exclude_tools
27
+ self.AdataInfo = AdataInfo
28
+ self._register_tools()
29
+
30
+ def _register_tools(self):
31
+ """Register all tool methods with the FastMCP instance based on include/exclude filters"""
32
+ # Get all methods of the class
33
+ methods = inspect.getmembers(self, predicate=inspect.ismethod)
34
+
35
+ # Filter methods that start with _tool_
36
+ tool_methods = {
37
+ name[6:]: method # Remove '_tool_' prefix
38
+ for name, method in methods
39
+ if name.startswith('_tool_')
40
+ }
41
+
42
+ # Filter tools based on include/exclude lists
43
+ if self.include_tools is not None:
44
+ tool_methods = {k: v for k, v in tool_methods.items() if k in self.include_tools}
45
+
46
+ if self.exclude_tools is not None:
47
+ tool_methods = {k: v for k, v in tool_methods.items() if k not in self.exclude_tools}
48
+
49
+ # Register filtered tools
50
+ for tool_name, tool_method in tool_methods.items():
51
+ # Get the function returned by the tool method
52
+ tool_func = tool_method()
53
+ if tool_func is not None:
54
+ self.mcp.add_tool(tool_func, name=tool_name)
55
+
56
+
57
+ class AdataState:
58
+ def __init__(self, add_adtypes=None):
59
+ self.adata_dic = {"exp": {}, "activity": {}, "cnv": {}, "splicing": {}}
60
+ if isinstance(add_adtypes, str):
61
+ self.adata_dic[add_adtypes] = {}
62
+ elif isinstance(add_adtypes, Iterable):
63
+ self.adata_dic.update({adtype: {} for adtype in add_adtypes})
64
+ self.active_id = None
65
+ self.metadatWa = {}
66
+ self.cr_kernel = {}
67
+ self.cr_estimator = {}
68
+
69
+ def get_adata(self, sampleid=None, adtype="exp", adinfo=None):
70
+ if adinfo is not None:
71
+ kwargs = adinfo.model_dump()
72
+ sampleid = kwargs.get("sampleid", None)
73
+ adtype = kwargs.get("adtype", "exp")
74
+ try:
75
+ if self.active_id is None:
76
+ return None
77
+ sampleid = sampleid or self.active_id
78
+ return self.adata_dic[adtype][sampleid]
79
+ except KeyError as e:
80
+ raise KeyError(f"Key {e} not found in adata_dic[{adtype}].Please check the sampleid or adtype.")
81
+ except Exception as e:
82
+ raise Exception(f"fuck {e} {type(e)}")
83
+
84
+ def set_adata(self, adata, sampleid=None, sdtype="exp", adinfo=None):
85
+ if adinfo is not None:
86
+ kwargs = adinfo.model_dump()
87
+ sampleid = kwargs.get("sampleid", None)
88
+ sdtype = kwargs.get("adtype", "exp")
89
+ sampleid = sampleid or self.active_id
90
+ if sdtype not in self.adata_dic:
91
+ self.adata_dic[sdtype] = {}
92
+ self.adata_dic[sdtype][sampleid] = adata
93
+
94
+
95
+ class BaseMCPManager:
96
+ """Base class for MCP module management."""
97
+
98
+ def __init__(self,
99
+ name: str,
100
+ include_modules: Optional[List[str]] = None,
101
+ exclude_modules: Optional[List[str]] = None,
102
+ include_tools: Optional[List[str]] = None,
103
+ exclude_tools: Optional[List[str]] = None,
104
+ ):
105
+ """
106
+ Initialize BaseMCPManager with optional module filtering.
107
+
108
+ Args:
109
+ name (str): Name of the MCP server
110
+ include_modules (List[str], optional): List of module names to include. If None, all modules are included.
111
+ exclude_modules (List[str], optional): List of module names to exclude. If None, no modules are excluded.
112
+ include_tools (List[str], optional): List of tool names to include. If None, all tools are included.
113
+ exclude_tools (List[str], optional): List of tool names to exclude. If None, no tools are excluded.
114
+ """
115
+ self.ads = AdataState()
116
+ self.mcp = FastMCP(name, lifespan=self.adata_lifespan)
117
+ self.include_modules = include_modules
118
+ self.exclude_modules = exclude_modules
119
+ self.include_tools = include_tools
120
+ self.exclude_tools = exclude_tools
121
+ self.available_modules = {}
122
+ self._init_modules()
123
+ self._register_modules()
124
+
125
+ def _init_modules(self):
126
+ """Initialize available modules. To be implemented by subclasses."""
127
+ raise NotImplementedError("Subclasses must implement _init_modules")
128
+
129
+ def _register_modules(self):
130
+ """Register modules based on include/exclude filters."""
131
+ # Filter modules based on include/exclude lists
132
+ if self.include_modules is not None:
133
+ self.available_modules = {k: v for k, v in self.available_modules.items() if k in self.include_modules}
134
+
135
+ if self.exclude_modules is not None:
136
+ self.available_modules = {k: v for k, v in self.available_modules.items() if k not in self.exclude_modules}
137
+
138
+ # Register each module
139
+ for module_name, mcpi in self.available_modules.items():
140
+ if isinstance(mcpi, FastMCP):
141
+ if self.include_tools is not None and module_name in self.include_tools:
142
+ mcpi = filter_tools(mcpi, include_tools= self.include_tools[module_name])
143
+ if self.exclude_tools is not None and module_name in self.exclude_tools:
144
+ mcpi = filter_tools(mcpi, exclude_tools=self.exclude_tools[module_name])
145
+
146
+ asyncio.run(self.mcp.import_server(module_name, mcpi))
147
+ else:
148
+ asyncio.run(self.mcp.import_server(module_name, mcpi().mcp))
149
+
150
+ @asynccontextmanager
151
+ async def adata_lifespan(self, server: FastMCP) -> AsyncIterator[Any]:
152
+ """Context manager for AdataState lifecycle."""
153
+ yield self.ads
@@ -0,0 +1,84 @@
1
+ import os
2
+ import inspect
3
+ from pathlib import Path
4
+ import scanpy as sc
5
+ from fastmcp import FastMCP, Context
6
+ from fastmcp.exceptions import ToolError
7
+ from ..schema import AdataInfo
8
+ from ..schema.io import *
9
+ from ..util import filter_args, forward_request, get_ads, generate_msg
10
+ from .base import BaseMCP
11
+
12
+
13
+ class ScanpyIOMCP(BaseMCP):
14
+ def __init__(self, include_tools: list = None, exclude_tools: list = None, AdataInfo = AdataInfo):
15
+ """Initialize ScanpyIOMCP with optional tool filtering."""
16
+ super().__init__("SCMCP-IO-Server", include_tools, exclude_tools, AdataInfo)
17
+
18
+ def _tool_read(self):
19
+ def _read(request: ReadModel, adinfo: self.AdataInfo=self.AdataInfo()):
20
+ """
21
+ Read data from 10X directory or various file formats (h5ad, 10x, text files, etc.).
22
+ """
23
+ try:
24
+ res = forward_request("io_read", request, adinfo)
25
+ if res is not None:
26
+ return res
27
+ kwargs = request.model_dump()
28
+ file = Path(kwargs.get("filename", None))
29
+ if file.is_dir():
30
+ kwargs["path"] = kwargs["filename"]
31
+ func_kwargs = filter_args(request, sc.read_10x_mtx)
32
+ adata = sc.read_10x_mtx(kwargs["path"], **func_kwargs)
33
+ elif file.is_file():
34
+ func_kwargs = filter_args(request, sc.read)
35
+ adata = sc.read(**func_kwargs)
36
+ if not kwargs.get("first_column_obs", True):
37
+ adata = adata.T
38
+ else:
39
+ raise FileNotFoundError(f"{kwargs['filename']} does not exist")
40
+
41
+ ads = get_ads()
42
+ if adinfo.sampleid is not None:
43
+ ads.active_id = adinfo.sampleid
44
+ else:
45
+ ads.active_id = f"adata{len(ads.adata_dic[adinfo.adtype])}"
46
+
47
+ adata.layers["counts"] = adata.X
48
+ adata.var_names_make_unique()
49
+ adata.obs_names_make_unique()
50
+ ads.set_adata(adata, adinfo=adinfo)
51
+ return generate_msg(adinfo, adata, ads)
52
+ except ToolError as e:
53
+ raise ToolError(e)
54
+ except Exception as e:
55
+ if hasattr(e, '__context__') and e.__context__:
56
+ raise ToolError(e.__context__)
57
+ else:
58
+ raise ToolError(e)
59
+ return _read
60
+
61
+ def _tool_write(self):
62
+ def _write(request: WriteModel, adinfo: self.AdataInfo=self.AdataInfo()):
63
+ """save adata into a file."""
64
+ try:
65
+ res = forward_request("io_write", request, adinfo)
66
+ if res is not None:
67
+ return res
68
+ ads = get_ads()
69
+ adata = ads.get_adata(adinfo=adinfo)
70
+ kwargs = request.model_dump()
71
+ sc.write(kwargs["filename"], adata)
72
+ return {"filename": kwargs["filename"], "msg": "success to save file"}
73
+ except ToolError as e:
74
+ raise ToolError(e)
75
+ except Exception as e:
76
+ if hasattr(e, '__context__') and e.__context__:
77
+ raise ToolError(e.__context__)
78
+ else:
79
+ raise ToolError(e)
80
+ return _write
81
+
82
+
83
+ # Create an instance of the class
84
+ io_mcp = ScanpyIOMCP().mcp