Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,33 @@ jobs:
- run: uv run mypy src/metorial/

test:
name: test (py${{ matrix.python-version }}, ${{ matrix.mcp }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12"]
mcp: ["mcp>=2,<3", "mcp>=1.21,<2"]
include:
# Oldest supported mcp. Its bundled FastMCP test server needs a
# pydantic from the same era.
- python-version: "3.10"
mcp: "mcp==1.21.0"
extra: "pydantic<2.13"
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v3
- run: uv python install ${{ matrix.python-version }}
- run: uv sync --dev --python ${{ matrix.python-version }}
- run: uv pip install "${{ matrix.mcp }}" ${{ matrix.extra && format('"{0}"', matrix.extra) || '' }}
- run: uv run --no-sync python -c "import importlib.metadata as m; print('mcp', m.version('mcp'))"
- run: uv run --no-sync pytest -q

type-check-mcp-v1:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v3
- run: uv sync --dev
- run: |
if [ -d tests ]; then
uv run pytest -q
else
echo "No tests directory present; skipping pytest."
fi
- run: uv pip install "mcp>=1.21,<2"
- run: uv run --no-sync mypy src/metorial/
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,25 @@ All notable changes to the Metorial Python SDK will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [2.7.0] - 2026-11-09

### Added

- Added support for v2 of the MCP Python SDK (`mcp` 2.x). The SDK now works with both `mcp>=1.21,<2` and `mcp>=2,<3`; all version-specific handling lives in `metorial.mcp._compat`.

### Fixed

- `MetorialMcpClient.from_url` no longer fails with `TypeError: unsupported operand type(s) for +: 'float' and 'datetime.timedelta'` on mcp 2.x. The read timeout is passed in the form the installed `mcp` expects.
- Tool input schemas and resource URI templates are read correctly from mcp 2.x models (which use snake_case attributes). Previously they would have been silently dropped.
- Tool results passed to LLM providers and framework integrations are serialized with MCP wire names (`isError`, `structuredContent`, `_meta`) regardless of the installed `mcp` version, and `null` fields are omitted.
- A failed HTTP request to the MCP server (for example a read timeout on a long-running tool or a 5xx response) now fails only that request, with a JSON-RPC error. Previously it shut down the client's transport, and every later call on that client failed.
- Per-request MCP headers set by the `mcp` client session are now forwarded by the Streamable HTTP transport.

### Changed

- `httpx-sse` is now a direct dependency. mcp 2.x no longer installs it.
- The minimum supported `mcp` version is now 1.21.0, the oldest release that provides every API the SDK already used.

## [2.6.0] - 2026-10-16

### Added
Expand Down
4 changes: 3 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@ dependencies = [
"aiohttp-sse-client>=0.2.1",
"typing-extensions>=4.0.0",
"httpx>=0.25.0",
"httpx-sse>=0.4.0",
"requests>=2.25.0",
"truststore>=0.8.0",
"mcp>=1.0.0,<2",
# Both MCP Python SDK majors are supported; metorial.mcp._compat bridges them.
"mcp>=1.21.0,<3",
]

# Provider SDKs are optional: the Metorial SDK itself never imports them, they
Expand Down
26 changes: 26 additions & 0 deletions src/metorial/_tool_results.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""Turning tool results into the plain JSON handed to LLM providers."""

from __future__ import annotations

import json
from typing import Any

from pydantic import BaseModel


def normalize_tool_result(result: Any) -> Any:
"""Convert an MCP result model into plain JSON-compatible data.

Pydantic models are dumped by alias so the keys match the MCP wire format
(``structuredContent``, ``isError``, ``_meta``) regardless of whether the
installed MCP SDK names its attributes in camelCase (1.x) or snake_case (2.x).
"""
if isinstance(result, BaseModel):
return result.model_dump(by_alias=True, mode="json", exclude_none=True)
if hasattr(result, "model_dump"):
return result.model_dump()
return result


def serialize_tool_result(result: Any) -> str:
return json.dumps(normalize_tool_result(result), ensure_ascii=False, default=str)
2 changes: 1 addition & 1 deletion src/metorial/_version.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""Metorial SDK version."""

__version__ = "2.6.0"
__version__ = "2.7.0"
13 changes: 0 additions & 13 deletions src/metorial/integrations/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import asyncio
import inspect
import json
from collections.abc import Callable
from typing import Any

Expand All @@ -22,18 +21,6 @@ def json_type_to_python(json_type: str) -> type[Any]:
return type_map.get(json_type, str)


def normalize_tool_result(result: Any) -> Any:
"""Normalize SDK objects into plain Python data."""
if hasattr(result, "model_dump"):
return result.model_dump()
return result


def serialize_tool_result(result: Any) -> str:
"""Serialize a tool result as JSON text."""
return json.dumps(normalize_tool_result(result), ensure_ascii=False, default=str)


def apply_tool_signature(
fn: Callable[..., Any],
*,
Expand Down
2 changes: 1 addition & 1 deletion src/metorial/integrations/autogen.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ async def _invoke(**kwargs: Any) -> str:
try:
result = await tool_manager.execute_tool(tool_name, args)
if hasattr(result, "model_dump"):
result = result.model_dump()
result = result.model_dump(by_alias=True, mode="json", exclude_none=True)
return json.dumps(result, ensure_ascii=False, default=str)
except Exception as e:
return json.dumps({"error": str(e)}, ensure_ascii=False)
Expand Down
2 changes: 1 addition & 1 deletion src/metorial/integrations/crewai.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
import json
from typing import TYPE_CHECKING, Any

from metorial._tool_results import serialize_tool_result
from metorial.integrations import _sanitize_tool_name
from metorial.integrations._common import (
apply_tool_signature,
run_coro_on_loop,
serialize_tool_result,
)

if TYPE_CHECKING:
Expand Down
2 changes: 1 addition & 1 deletion src/metorial/integrations/google_adk.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
import json
from typing import TYPE_CHECKING, Any

from metorial._tool_results import normalize_tool_result
from metorial.integrations import _sanitize_tool_name
from metorial.integrations._common import (
apply_tool_signature,
normalize_tool_result,
)

if TYPE_CHECKING:
Expand Down
6 changes: 3 additions & 3 deletions src/metorial/integrations/langchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import json
from typing import TYPE_CHECKING, Any

from metorial._tool_results import serialize_tool_result

if TYPE_CHECKING:
from metorial._client import ProviderSession

Expand Down Expand Up @@ -64,9 +66,7 @@ async def tool_fn(**kwargs: Any) -> str:
filtered_kwargs = {k: v for k, v in kwargs.items() if v is not None}
try:
result = await tool_manager.execute_tool(tool_name, filtered_kwargs)
if hasattr(result, "model_dump"):
result = result.model_dump()
return json.dumps(result, ensure_ascii=False, default=str)
return serialize_tool_result(result)
except Exception as e:
return json.dumps({"error": str(e)}, ensure_ascii=False)

Expand Down
2 changes: 1 addition & 1 deletion src/metorial/integrations/llamaindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
import json
from typing import TYPE_CHECKING, Any

from metorial._tool_results import serialize_tool_result
from metorial.integrations import _sanitize_tool_name
from metorial.integrations._common import (
apply_tool_signature,
run_coro_on_loop,
serialize_tool_result,
)

if TYPE_CHECKING:
Expand Down
10 changes: 4 additions & 6 deletions src/metorial/integrations/openai_agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import json
from typing import TYPE_CHECKING, Any

from metorial._tool_results import serialize_tool_result

if TYPE_CHECKING:
from metorial._client import ProviderSession

Expand Down Expand Up @@ -94,9 +96,7 @@ async def tool_fn(**kwargs: Any) -> str:
# Filter out None values
filtered_kwargs = {k: v for k, v in kwargs.items() if v is not None}
result = await tool_manager.execute_tool(original_name, filtered_kwargs)
if hasattr(result, "model_dump"):
result = result.model_dump()
return json.dumps(result, ensure_ascii=False, default=str)
return serialize_tool_result(result)

tool_fn.__name__ = tool_name
tool_fn.__doc__ = tool_description
Expand Down Expand Up @@ -126,9 +126,7 @@ async def invoke_handler(ctx: Any, input_json: str) -> str:
if k in required_params or (v is not None and v != ""):
filtered_kwargs[k] = v
result = await tool_manager.execute_tool(tool_name, filtered_kwargs)
if hasattr(result, "model_dump"):
result = result.model_dump()
return json.dumps(result, ensure_ascii=False, default=str)
return serialize_tool_result(result)

return invoke_handler

Expand Down
14 changes: 5 additions & 9 deletions src/metorial/integrations/pydantic_ai.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import json
from typing import TYPE_CHECKING, Any

from metorial._tool_results import serialize_tool_result

if TYPE_CHECKING:
from metorial._client import ProviderSession

Expand Down Expand Up @@ -70,9 +72,7 @@ async def metorial_tool(**kwargs: Any) -> str:
result = await tool_manager.execute_tool(tool_name, filtered_kwargs)
except Exception as e:
return json.dumps({"error": str(e)}, ensure_ascii=False)
if hasattr(result, "model_dump"):
result = result.model_dump()
return json.dumps(result, ensure_ascii=False, default=str)
return serialize_tool_result(result)

# Override the function metadata
metorial_tool.__name__ = tool_name
Expand Down Expand Up @@ -154,9 +154,7 @@ async def tool_fn(**kwargs: Any) -> str:
result = await mgr.execute_tool(name, filtered_kwargs)
except Exception as e:
return json.dumps({"error": str(e)}, ensure_ascii=False)
if hasattr(result, "model_dump"):
result = result.model_dump()
return json.dumps(result, ensure_ascii=False, default=str)
return serialize_tool_result(result)

# Set annotations for PydanticAI to discover parameters
tool_fn.__annotations__ = {
Expand Down Expand Up @@ -184,9 +182,7 @@ async def tool_fn() -> str:
result = await mgr.execute_tool(name, {})
except Exception as e:
return json.dumps({"error": str(e)}, ensure_ascii=False)
if hasattr(result, "model_dump"):
result = result.model_dump()
return json.dumps(result, ensure_ascii=False, default=str)
return serialize_tool_result(result)

tool_fn.__signature__ = inspect.Signature(return_annotation=str)

Expand Down
93 changes: 93 additions & 0 deletions src/metorial/mcp/_compat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
"""Bridges the differences between the 1.x and 2.x MCP Python SDKs.

Every place in Metorial that depends on an API that changed between the two
majors goes through this module, so the rest of the SDK can stay
version-agnostic. The differences handled here:

- ``ClientSession(read_timeout_seconds=...)`` takes a ``timedelta`` in 1.x and
a ``float`` of seconds in 2.x.
- ``mcp.types.JSONRPCMessage`` is a pydantic ``RootModel`` in 1.x (the concrete
message lives on ``.root``) and a plain ``Union`` of message models in 2.x.
- MCP models expose camelCase attributes in 1.x (``tool.inputSchema``) and
snake_case attributes in 2.x (``tool.input_schema``). The wire format is
camelCase in both.
- ``ClientSession.get_server_capabilities()`` became the
``ClientSession.server_capabilities`` property in 2.x.
- ``ClientSession.read_resource`` takes a pydantic ``AnyUrl`` in 1.x and a
``str`` in 2.x.
"""

from __future__ import annotations

import re
from datetime import timedelta
from typing import TYPE_CHECKING, Any

from mcp.types import JSONRPCMessage, ServerCapabilities, Tool
from pydantic import AnyUrl, TypeAdapter

if TYPE_CHECKING:
from mcp import ClientSession

MCP_V2: bool = "input_schema" in Tool.model_fields

_JSONRPC_MESSAGE_ADAPTER: TypeAdapter[JSONRPCMessage] = TypeAdapter(JSONRPCMessage)

_CAMEL_BOUNDARY = re.compile(r"(?<!^)(?=[A-Z])")

_MISSING = object()


def session_read_timeout(seconds: float | None) -> Any:
if seconds is None:
return None
return float(seconds) if MCP_V2 else timedelta(seconds=seconds)


def parse_jsonrpc_message(data: Any) -> JSONRPCMessage:
return _JSONRPC_MESSAGE_ADAPTER.validate_python(data)


def parse_jsonrpc_json(data: str | bytes) -> JSONRPCMessage:
return _JSONRPC_MESSAGE_ADAPTER.validate_json(data)


def unwrap_jsonrpc_message(message: JSONRPCMessage) -> Any:
"""Return the concrete request/notification/response/error model."""
return message if MCP_V2 else message.root # type: ignore[union-attr,attr-defined,unused-ignore]


def to_snake_case(name: str) -> str:
return _CAMEL_BOUNDARY.sub("_", name).lower()


def get_field(obj: Any, name: str, default: Any = None) -> Any:
"""Read an MCP field by its camelCase wire name from a dict or a model.

Accepts raw JSON dicts, 1.x models (camelCase attributes) and 2.x models
(snake_case attributes) alike.
"""
if obj is None:
return default

snake = to_snake_case(name)

if isinstance(obj, dict):
if name in obj:
return obj[name]
return obj.get(snake, default)

value = getattr(obj, name, _MISSING)
if value is _MISSING:
value = getattr(obj, snake, default)
return value


def get_server_capabilities(session: ClientSession) -> ServerCapabilities | None:
if MCP_V2:
return session.server_capabilities # type: ignore[attr-defined,no-any-return,unused-ignore]
return session.get_server_capabilities() # type: ignore[attr-defined,no-any-return,unused-ignore]


def resource_uri(uri: str) -> Any:
return uri if MCP_V2 else AnyUrl(uri)
Loading
Loading