modmex-lambda 0.6.3__py3-none-any.whl → 0.7.1__py3-none-any.whl
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.
- modmex_lambda/event_handler/api_gateway.py +15 -0
- modmex_lambda/mcp/__init__.py +37 -0
- modmex_lambda/mcp/middleware.py +70 -0
- modmex_lambda/mcp/prompt.py +51 -0
- modmex_lambda/mcp/protocol.py +64 -0
- modmex_lambda/mcp/registry.py +90 -0
- modmex_lambda/mcp/resource.py +83 -0
- modmex_lambda/mcp/schema.py +97 -0
- modmex_lambda/mcp/server.py +420 -0
- modmex_lambda/mcp/tool.py +170 -0
- modmex_lambda/mcp/transport.py +202 -0
- {modmex_lambda-0.6.3.dist-info → modmex_lambda-0.7.1.dist-info}/METADATA +109 -2
- {modmex_lambda-0.6.3.dist-info → modmex_lambda-0.7.1.dist-info}/RECORD +15 -5
- {modmex_lambda-0.6.3.dist-info → modmex_lambda-0.7.1.dist-info}/WHEEL +1 -1
- {modmex_lambda-0.6.3.dist-info → modmex_lambda-0.7.1.dist-info}/licenses/LICENSE +0 -0
|
@@ -171,6 +171,21 @@ class ApiGatewayResolver(BaseRouter, IApiGatewayResolver):
|
|
|
171
171
|
def include_router(self, router: Router, prefix: str = "") -> None:
|
|
172
172
|
self._router.include_router(router, prefix=prefix)
|
|
173
173
|
|
|
174
|
+
def include_mcp(self, server: Any, *, path: str = "/mcp") -> None:
|
|
175
|
+
"""Mount a transport-neutral MCP server as a normal HTTP route."""
|
|
176
|
+
from modmex_lambda.mcp import MCPServer
|
|
177
|
+
from modmex_lambda.mcp.transport import MCPHttpTransport
|
|
178
|
+
|
|
179
|
+
if not isinstance(server, MCPServer):
|
|
180
|
+
raise TypeError("include_mcp expects an MCPServer")
|
|
181
|
+
|
|
182
|
+
transport = MCPHttpTransport(server)
|
|
183
|
+
|
|
184
|
+
@self.route(path, method="POST", status_code=200)
|
|
185
|
+
def mcp_handler(request: Request) -> Response:
|
|
186
|
+
return transport.handle(request)
|
|
187
|
+
|
|
188
|
+
|
|
174
189
|
def resolve(self, event: dict[str, Any], context: object) -> dict[str, Any]:
|
|
175
190
|
self.current_event = self._to_proxy_event(event)
|
|
176
191
|
self.current_context = context
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""MCP server, protocol, and HTTP transport primitives."""
|
|
2
|
+
|
|
3
|
+
from modmex_lambda.mcp.protocol import (
|
|
4
|
+
MCP_PROTOCOL_VERSION,
|
|
5
|
+
JSONRPCError,
|
|
6
|
+
JSONRPCErrorCode,
|
|
7
|
+
JSONRPCRequest,
|
|
8
|
+
JSONRPCResponse,
|
|
9
|
+
)
|
|
10
|
+
from modmex_lambda.mcp.server import MCPError, MCPServer
|
|
11
|
+
from modmex_lambda.mcp.tool import MCPTool
|
|
12
|
+
from modmex_lambda.mcp.resource import MCPResource
|
|
13
|
+
from modmex_lambda.mcp.prompt import MCPPrompt
|
|
14
|
+
from modmex_lambda.mcp.transport import MCPHttpTransport, SSEEvent, encode_sse, encode_sse_stream, MCP_JSON_CONTENT_TYPE, MCP_SSE_CONTENT_TYPE
|
|
15
|
+
from modmex_lambda.mcp.middleware import MCPContext, MCPMiddleware, MCPNextMiddleware
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"JSONRPCError",
|
|
19
|
+
"JSONRPCErrorCode",
|
|
20
|
+
"MCP_PROTOCOL_VERSION",
|
|
21
|
+
"JSONRPCRequest",
|
|
22
|
+
"JSONRPCResponse",
|
|
23
|
+
"MCPServer",
|
|
24
|
+
"MCPError",
|
|
25
|
+
"MCPHttpTransport",
|
|
26
|
+
"MCPTool",
|
|
27
|
+
"MCPResource",
|
|
28
|
+
"MCPPrompt",
|
|
29
|
+
"SSEEvent",
|
|
30
|
+
"encode_sse",
|
|
31
|
+
"encode_sse_stream",
|
|
32
|
+
"MCP_JSON_CONTENT_TYPE",
|
|
33
|
+
"MCP_SSE_CONTENT_TYPE",
|
|
34
|
+
"MCPContext",
|
|
35
|
+
"MCPMiddleware",
|
|
36
|
+
"MCPNextMiddleware",
|
|
37
|
+
]
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Composable middleware for MCP capabilities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import TYPE_CHECKING, Callable, Protocol, TypeAlias, Union, Any
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from modmex_lambda.event_handler.request import Request
|
|
11
|
+
from modmex_lambda.mcp.server import MCPServer
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
JSONValue: TypeAlias = Union[
|
|
15
|
+
None,
|
|
16
|
+
bool,
|
|
17
|
+
int,
|
|
18
|
+
float,
|
|
19
|
+
str,
|
|
20
|
+
list["JSONValue"],
|
|
21
|
+
dict[str, "JSONValue"],
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class MCPContext:
|
|
27
|
+
request: "Request | None"
|
|
28
|
+
server: "MCPServer | None"
|
|
29
|
+
capability: str
|
|
30
|
+
name: str
|
|
31
|
+
arguments: dict[str, JSONValue]
|
|
32
|
+
state: dict[str, object] = field(default_factory=dict)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class MCPNextMiddleware(Protocol):
|
|
36
|
+
def __call__(self, context: MCPContext) -> object: ...
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class MCPMiddleware(Protocol):
|
|
40
|
+
def __call__(self, context: MCPContext, next_middleware: MCPNextMiddleware) -> object: ...
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def run_middleware(
|
|
44
|
+
middlewares: list[MCPMiddleware],
|
|
45
|
+
context: MCPContext,
|
|
46
|
+
endpoint: Callable[[MCPContext], Any],
|
|
47
|
+
) -> Any:
|
|
48
|
+
next_middleware: MCPNextMiddleware = endpoint
|
|
49
|
+
for middleware in reversed(middlewares):
|
|
50
|
+
current = next_middleware
|
|
51
|
+
next_middleware = lambda ctx, middleware=middleware, current=current: middleware(ctx, current)
|
|
52
|
+
result = next_middleware(context)
|
|
53
|
+
if inspect.isawaitable(result):
|
|
54
|
+
raise RuntimeError("MCP middleware is async; use run_middleware_async")
|
|
55
|
+
return result
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def run_middleware_async(
|
|
59
|
+
middlewares: list[MCPMiddleware],
|
|
60
|
+
context: MCPContext,
|
|
61
|
+
endpoint: Callable[[MCPContext], Any],
|
|
62
|
+
) -> Any:
|
|
63
|
+
async def invoke(index: int, ctx: MCPContext) -> Any:
|
|
64
|
+
if index == len(middlewares):
|
|
65
|
+
result = endpoint(ctx)
|
|
66
|
+
else:
|
|
67
|
+
middleware = middlewares[index]
|
|
68
|
+
result = middleware(ctx, lambda next_ctx: invoke(index + 1, next_ctx))
|
|
69
|
+
return await result if inspect.isawaitable(result) else result
|
|
70
|
+
return await invoke(0, context)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""MCP prompt registration and invocation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
from typing import Any, Callable, get_type_hints
|
|
7
|
+
|
|
8
|
+
from modmex_lambda.mcp.schema import input_schema
|
|
9
|
+
from modmex_lambda.mcp.tool import MCPTool
|
|
10
|
+
from modmex_lambda.mcp.middleware import MCPContext, MCPMiddleware
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class MCPPrompt:
|
|
14
|
+
def __init__(
|
|
15
|
+
self,
|
|
16
|
+
handler: Callable[..., Any],
|
|
17
|
+
*,
|
|
18
|
+
name: str | None = None,
|
|
19
|
+
description: str | None = None,
|
|
20
|
+
middlewares: list[Any] | None = None,
|
|
21
|
+
) -> None:
|
|
22
|
+
self.name = name or handler.__name__
|
|
23
|
+
self.description = description or inspect.getdoc(handler) or ""
|
|
24
|
+
self.operation = MCPTool(handler, middlewares=middlewares)
|
|
25
|
+
|
|
26
|
+
def definition(self) -> dict[str, Any]:
|
|
27
|
+
schema = input_schema(self.operation.handler)
|
|
28
|
+
required = set(schema.get("required", []))
|
|
29
|
+
properties = schema.get("properties", {})
|
|
30
|
+
return {
|
|
31
|
+
"name": self.name,
|
|
32
|
+
"description": self.description,
|
|
33
|
+
"arguments": [
|
|
34
|
+
{"name": name, "description": str(properties[name].get("description", "")), "required": name in required}
|
|
35
|
+
for name in properties
|
|
36
|
+
],
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
def get(self, arguments: dict[str, Any] | None = None, *, context: Any = None, server: Any = None, middlewares: list[MCPMiddleware] | None = None) -> dict[str, Any]:
|
|
40
|
+
values = arguments or {}
|
|
41
|
+
output = self.operation.invoke(values, request=context, middlewares=middlewares, middleware_context=MCPContext(request=context, server=server, capability="prompts", name=self.name, arguments=values))
|
|
42
|
+
if not isinstance(output, list):
|
|
43
|
+
output = [{"role": "user", "content": {"type": "text", "text": str(output)}}]
|
|
44
|
+
return {"messages": output}
|
|
45
|
+
|
|
46
|
+
async def aget(self, arguments: dict[str, Any] | None = None, *, context: Any = None, server: Any = None, middlewares: list[MCPMiddleware] | None = None) -> dict[str, Any]:
|
|
47
|
+
values = arguments or {}
|
|
48
|
+
output = await self.operation.ainvoke(values, request=context, middlewares=middlewares, middleware_context=MCPContext(request=context, server=server, capability="prompts", name=self.name, arguments=values))
|
|
49
|
+
if not isinstance(output, list):
|
|
50
|
+
output = [{"role": "user", "content": {"type": "text", "text": str(output)}}]
|
|
51
|
+
return {"messages": output}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Small, transport-neutral JSON-RPC models used by the MCP server."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import IntEnum
|
|
6
|
+
from typing import Any, Dict, Literal, Optional, Union
|
|
7
|
+
|
|
8
|
+
from modmex import BaseModel
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
JSONRPCVersion = Literal["2.0"]
|
|
12
|
+
JSONRPCId = Optional[Union[str, int]]
|
|
13
|
+
MCP_PROTOCOL_VERSION = "2026-07-28"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class JSONRPCErrorCode(IntEnum):
|
|
17
|
+
PARSE_ERROR = -32700
|
|
18
|
+
INVALID_REQUEST = -32600
|
|
19
|
+
METHOD_NOT_FOUND = -32601
|
|
20
|
+
INVALID_PARAMS = -32602
|
|
21
|
+
INTERNAL_ERROR = -32603
|
|
22
|
+
HEADER_MISMATCH = -32020
|
|
23
|
+
UNSUPPORTED_PROTOCOL_VERSION = -32022
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class JSONRPCRequest(BaseModel):
|
|
27
|
+
jsonrpc: JSONRPCVersion = "2.0"
|
|
28
|
+
id: JSONRPCId = None
|
|
29
|
+
method: str
|
|
30
|
+
params: Optional[Dict[str, Any]] = None
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def metadata(self) -> dict[str, Any]:
|
|
34
|
+
return (self.params or {}).get("_meta", {})
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class JSONRPCError(BaseModel):
|
|
38
|
+
code: int
|
|
39
|
+
message: str
|
|
40
|
+
data: Any = None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class JSONRPCResponse(BaseModel):
|
|
44
|
+
jsonrpc: JSONRPCVersion = "2.0"
|
|
45
|
+
id: JSONRPCId = None
|
|
46
|
+
result: Any = None
|
|
47
|
+
error: Optional[JSONRPCError] = None
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def success(cls, request_id: JSONRPCId, result: Any = None) -> "JSONRPCResponse":
|
|
51
|
+
return cls(id=request_id, result=result)
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def failure(
|
|
55
|
+
cls,
|
|
56
|
+
request_id: JSONRPCId,
|
|
57
|
+
code: int | JSONRPCErrorCode,
|
|
58
|
+
message: str,
|
|
59
|
+
data: Any = None,
|
|
60
|
+
) -> "JSONRPCResponse":
|
|
61
|
+
return cls(
|
|
62
|
+
id=request_id,
|
|
63
|
+
error=JSONRPCError(code=int(code), message=message, data=data),
|
|
64
|
+
)
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Capability registries used by the MCP server."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from modmex_lambda.mcp.tool import MCPTool
|
|
8
|
+
from modmex_lambda.mcp.prompt import MCPPrompt
|
|
9
|
+
from modmex_lambda.mcp.resource import MCPResource
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class MCPToolRegistry:
|
|
13
|
+
def __init__(self) -> None:
|
|
14
|
+
self._tools: dict[str, MCPTool] = {}
|
|
15
|
+
|
|
16
|
+
def add(self, tool: MCPTool) -> MCPTool:
|
|
17
|
+
if tool.name in self._tools:
|
|
18
|
+
raise ValueError(f"Duplicate MCP tool: {tool.name}")
|
|
19
|
+
self._tools[tool.name] = tool
|
|
20
|
+
return tool
|
|
21
|
+
|
|
22
|
+
def get(self, name: str) -> MCPTool | None:
|
|
23
|
+
return self._tools.get(name)
|
|
24
|
+
|
|
25
|
+
def definitions(self) -> list[dict[str, Any]]:
|
|
26
|
+
return [tool.definition() for tool in self._tools.values()]
|
|
27
|
+
|
|
28
|
+
def page(self, cursor: str | None = None, *, limit: int = 50) -> tuple[list[dict[str, Any]], str | None]:
|
|
29
|
+
return _page(self.definitions(), cursor, limit)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class MCPResourceRegistry:
|
|
33
|
+
def __init__(self) -> None:
|
|
34
|
+
self._resources: list[MCPResource] = []
|
|
35
|
+
|
|
36
|
+
def add(self, resource: MCPResource) -> MCPResource:
|
|
37
|
+
if any(item.uri_template == resource.uri_template for item in self._resources):
|
|
38
|
+
raise ValueError(f"Duplicate MCP resource: {resource.uri_template}")
|
|
39
|
+
self._resources.append(resource)
|
|
40
|
+
return resource
|
|
41
|
+
|
|
42
|
+
def match(self, uri: str) -> tuple[MCPResource, dict[str, str]] | None:
|
|
43
|
+
for resource in self._resources:
|
|
44
|
+
arguments = resource.match(uri)
|
|
45
|
+
if arguments is not None:
|
|
46
|
+
return resource, arguments
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
def definitions(self) -> list[dict[str, Any]]:
|
|
50
|
+
return [resource.definition() for resource in self._resources if "{" not in resource.uri_template]
|
|
51
|
+
|
|
52
|
+
def templates(self) -> list[dict[str, Any]]:
|
|
53
|
+
return [resource.template_definition() for resource in self._resources if "{" in resource.uri_template]
|
|
54
|
+
|
|
55
|
+
def page(self, cursor: str | None = None, *, templates: bool = False, limit: int = 50) -> tuple[list[dict[str, Any]], str | None]:
|
|
56
|
+
values = self.templates() if templates else self.definitions()
|
|
57
|
+
return _page(values, cursor, limit)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class MCPPromptRegistry:
|
|
61
|
+
def __init__(self) -> None:
|
|
62
|
+
self._prompts: dict[str, MCPPrompt] = {}
|
|
63
|
+
|
|
64
|
+
def add(self, prompt: MCPPrompt) -> MCPPrompt:
|
|
65
|
+
if prompt.name in self._prompts:
|
|
66
|
+
raise ValueError(f"Duplicate MCP prompt: {prompt.name}")
|
|
67
|
+
self._prompts[prompt.name] = prompt
|
|
68
|
+
return prompt
|
|
69
|
+
|
|
70
|
+
def get(self, name: str) -> MCPPrompt | None:
|
|
71
|
+
return self._prompts.get(name)
|
|
72
|
+
|
|
73
|
+
def definitions(self) -> list[dict[str, Any]]:
|
|
74
|
+
return [prompt.definition() for prompt in self._prompts.values()]
|
|
75
|
+
|
|
76
|
+
def page(self, cursor: str | None = None, *, limit: int = 50) -> tuple[list[dict[str, Any]], str | None]:
|
|
77
|
+
return _page(self.definitions(), cursor, limit)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _page(values: list[dict[str, Any]], cursor: str | None, limit: int) -> tuple[list[dict[str, Any]], str | None]:
|
|
81
|
+
if limit <= 0:
|
|
82
|
+
raise ValueError("page size must be positive")
|
|
83
|
+
try:
|
|
84
|
+
start = int(cursor) if cursor is not None else 0
|
|
85
|
+
except (TypeError, ValueError) as exc:
|
|
86
|
+
raise ValueError("invalid pagination cursor") from exc
|
|
87
|
+
if start < 0 or start > len(values):
|
|
88
|
+
raise ValueError("invalid pagination cursor")
|
|
89
|
+
end = min(start + min(limit, 100), len(values))
|
|
90
|
+
return values[start:end], str(end) if end < len(values) else None
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""MCP resource URI templates and invocation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any, Callable
|
|
7
|
+
|
|
8
|
+
from modmex_lambda.mcp.tool import MCPTool
|
|
9
|
+
from modmex_lambda.mcp.middleware import MCPContext, MCPMiddleware
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class MCPResource:
|
|
13
|
+
def __init__(
|
|
14
|
+
self,
|
|
15
|
+
uri_template: str,
|
|
16
|
+
handler: Callable[..., Any],
|
|
17
|
+
*,
|
|
18
|
+
name: str | None = None,
|
|
19
|
+
description: str | None = None,
|
|
20
|
+
mime_type: str = "application/json",
|
|
21
|
+
middlewares: list[Any] | None = None,
|
|
22
|
+
) -> None:
|
|
23
|
+
if not uri_template:
|
|
24
|
+
raise ValueError("MCP resource URI template cannot be empty")
|
|
25
|
+
self.uri_template = uri_template
|
|
26
|
+
self.name = name or uri_template
|
|
27
|
+
self.description = description or ""
|
|
28
|
+
self.mime_type = mime_type
|
|
29
|
+
self.operation = MCPTool(handler, middlewares=middlewares)
|
|
30
|
+
self._names = tuple(re.findall(r"\{([A-Za-z_][A-Za-z0-9_]*)\}", uri_template))
|
|
31
|
+
pattern = re.escape(uri_template)
|
|
32
|
+
for parameter in self._names:
|
|
33
|
+
pattern = pattern.replace("\\{" + parameter + "\\}", rf"(?P<{parameter}>[^/]+)")
|
|
34
|
+
self._pattern = re.compile(rf"^{pattern}$")
|
|
35
|
+
|
|
36
|
+
def match(self, uri: str) -> dict[str, str] | None:
|
|
37
|
+
matched = self._pattern.match(uri)
|
|
38
|
+
return matched.groupdict() if matched else None
|
|
39
|
+
|
|
40
|
+
def definition(self) -> dict[str, Any]:
|
|
41
|
+
return {
|
|
42
|
+
"uri": self.uri_template,
|
|
43
|
+
"name": self.name,
|
|
44
|
+
"description": self.description,
|
|
45
|
+
"mimeType": self.mime_type,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
def template_definition(self) -> dict[str, Any]:
|
|
49
|
+
definition = self.definition()
|
|
50
|
+
definition.pop("uri", None)
|
|
51
|
+
definition["uriTemplate"] = self.uri_template
|
|
52
|
+
return definition
|
|
53
|
+
|
|
54
|
+
def read(self, uri: str, *, context: Any = None, server: Any = None, middlewares: list[MCPMiddleware] | None = None) -> dict[str, Any]:
|
|
55
|
+
arguments = self.match(uri)
|
|
56
|
+
if arguments is None:
|
|
57
|
+
raise ValueError(f"Resource URI does not match: {uri}")
|
|
58
|
+
output = self.operation.invoke(arguments, request=context, middlewares=middlewares, middleware_context=MCPContext(request=context, server=server, capability="resources", name=self.name, arguments=arguments))
|
|
59
|
+
if isinstance(output, bytes):
|
|
60
|
+
import base64
|
|
61
|
+
return {"uri": uri, "mimeType": self.mime_type, "blob": base64.b64encode(output).decode()}
|
|
62
|
+
if isinstance(output, str):
|
|
63
|
+
return {"uri": uri, "mimeType": self.mime_type, "text": output}
|
|
64
|
+
return {"uri": uri, "mimeType": self.mime_type, "text": _json_text(output)}
|
|
65
|
+
|
|
66
|
+
async def aread(self, uri: str, *, context: Any = None, server: Any = None, middlewares: list[MCPMiddleware] | None = None) -> dict[str, Any]:
|
|
67
|
+
arguments = self.match(uri)
|
|
68
|
+
if arguments is None:
|
|
69
|
+
raise ValueError(f"Resource URI does not match: {uri}")
|
|
70
|
+
output = await self.operation.ainvoke(arguments, request=context, middlewares=middlewares, middleware_context=MCPContext(request=context, server=server, capability="resources", name=self.name, arguments=arguments))
|
|
71
|
+
if isinstance(output, bytes):
|
|
72
|
+
import base64
|
|
73
|
+
return {"uri": uri, "mimeType": self.mime_type, "blob": base64.b64encode(output).decode()}
|
|
74
|
+
if isinstance(output, str):
|
|
75
|
+
return {"uri": uri, "mimeType": self.mime_type, "text": output}
|
|
76
|
+
return {"uri": uri, "mimeType": self.mime_type, "text": _json_text(output)}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _json_text(value: Any) -> str:
|
|
80
|
+
import json
|
|
81
|
+
if hasattr(value, "model_dump"):
|
|
82
|
+
value = value.model_dump()
|
|
83
|
+
return json.dumps(value, default=str, separators=(",", ":"))
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Provider-neutral input schemas for MCP operations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
import types
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from copy import deepcopy
|
|
9
|
+
from enum import Enum
|
|
10
|
+
from typing import Annotated, Any, Literal, Union, get_args, get_origin, get_type_hints
|
|
11
|
+
|
|
12
|
+
from modmex import BaseModel
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def input_schema(
|
|
16
|
+
callable_: Any,
|
|
17
|
+
*,
|
|
18
|
+
excluded: set[str] | None = None,
|
|
19
|
+
) -> dict[str, Any]:
|
|
20
|
+
"""Build an object schema from a callable signature.
|
|
21
|
+
|
|
22
|
+
Dependency-injected parameters are excluded from the public MCP input.
|
|
23
|
+
"""
|
|
24
|
+
excluded = excluded or set()
|
|
25
|
+
try:
|
|
26
|
+
hints = get_type_hints(callable_, include_extras=True)
|
|
27
|
+
except Exception:
|
|
28
|
+
hints = {}
|
|
29
|
+
|
|
30
|
+
properties: dict[str, Any] = {}
|
|
31
|
+
required: list[str] = []
|
|
32
|
+
for name, parameter in inspect.signature(callable_).parameters.items():
|
|
33
|
+
if name in excluded or name in {"self", "request", "context", "ctx"}:
|
|
34
|
+
continue
|
|
35
|
+
annotation = hints.get(name, parameter.annotation)
|
|
36
|
+
if _is_dependency(annotation):
|
|
37
|
+
continue
|
|
38
|
+
properties[name] = schema_for_type(annotation)
|
|
39
|
+
if parameter.default is inspect.Signature.empty:
|
|
40
|
+
required.append(name)
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
"type": "object",
|
|
44
|
+
"properties": properties,
|
|
45
|
+
"required": required,
|
|
46
|
+
"additionalProperties": False,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def schema_for_type(annotation: Any) -> dict[str, Any]:
|
|
51
|
+
if annotation is inspect.Signature.empty or annotation is Any:
|
|
52
|
+
return {}
|
|
53
|
+
origin = get_origin(annotation)
|
|
54
|
+
args = get_args(annotation)
|
|
55
|
+
|
|
56
|
+
if origin in (Union, types.UnionType):
|
|
57
|
+
non_none = [arg for arg in args if arg is not type(None)]
|
|
58
|
+
if len(non_none) == 1 and len(non_none) != len(args):
|
|
59
|
+
return {"anyOf": [schema_for_type(non_none[0]), {"type": "null"}]}
|
|
60
|
+
return {"anyOf": [schema_for_type(arg) for arg in args]}
|
|
61
|
+
if origin in (list, Sequence):
|
|
62
|
+
return {"type": "array", "items": schema_for_type(args[0] if args else Any)}
|
|
63
|
+
if origin is dict:
|
|
64
|
+
return {"type": "object"}
|
|
65
|
+
if origin is Literal:
|
|
66
|
+
values = list(args)
|
|
67
|
+
return {"enum": values, "type": _json_type(type(values[0])) if values else "string"}
|
|
68
|
+
if inspect.isclass(annotation) and issubclass(annotation, Enum):
|
|
69
|
+
values = [item.value for item in annotation]
|
|
70
|
+
return {"enum": values, "type": _json_type(type(values[0])) if values else "string"}
|
|
71
|
+
if inspect.isclass(annotation) and issubclass(annotation, BaseModel):
|
|
72
|
+
return deepcopy(annotation.model_json_schema())
|
|
73
|
+
return {"type": _json_type(annotation)}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _is_dependency(annotation: Any) -> bool:
|
|
77
|
+
from modmex_lambda.event_handler.dependencies.depends import Depends
|
|
78
|
+
|
|
79
|
+
if get_origin(annotation) is not Annotated:
|
|
80
|
+
return False
|
|
81
|
+
return any(isinstance(item, Depends) for item in get_args(annotation)[1:])
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _accepts_none(annotation: Any) -> bool:
|
|
85
|
+
origin = get_origin(annotation)
|
|
86
|
+
return origin in (Union, types.UnionType) and any(arg is type(None) for arg in get_args(annotation))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _json_type(annotation: Any) -> str:
|
|
90
|
+
return {
|
|
91
|
+
str: "string",
|
|
92
|
+
int: "integer",
|
|
93
|
+
float: "number",
|
|
94
|
+
bool: "boolean",
|
|
95
|
+
list: "array",
|
|
96
|
+
dict: "object",
|
|
97
|
+
}.get(annotation, "string")
|