Skip to content

Agent Mesh

fix python sdk

Antonio Ojeadc1d72e31ff7
diff --git a/sam-mcp-python/src/sam_mcp/adapters/langchain.py b/sam-mcp-python/src/sam_mcp/adapters/langchain.py
index b251f8bc..18f85541 100644
--- a/sam-mcp-python/src/sam_mcp/adapters/langchain.py
+++ b/sam-mcp-python/src/sam_mcp/adapters/langchain.py
@@ -4,21 +4,53 @@ from ..client import SamClient
def get_langchain_tools(client: SamClient, tools: List[Dict[str, Any]]) -> List[Any]:
"""Converts MCP tools into LangChain-compatible StructuredTool objects.
- Requires `langchain-core` to be installed.
+ Requires `langchain-core` and `pydantic` to be installed.
"""
try:
from langchain_core.tools import StructuredTool
+ from pydantic import create_model, Field
except ImportError:
raise ImportError(
- "langchain-core is required to use this adapter. "
- "Install it with `pip install langchain-core`"
+ "langchain-core and pydantic are required to use this adapter. "
+ "Install them or ensure they are available via langchain."
)
lc_tools = []
for tool in tools:
name = tool.get("name")
description = tool.get("description", "")
+ input_schema = tool.get("inputSchema", {})
+ properties = input_schema.get("properties", {})
+ required = input_schema.get("required", [])
+
+ fields = {}
+ for prop_name, prop_schema in properties.items():
+ prop_type = prop_schema.get("type")
+ prop_desc = prop_schema.get("description", "")
+
+ python_type = Any
+ if prop_type == "string":
+ python_type = str
+ elif prop_type == "integer":
+ python_type = int
+ elif prop_type == "number":
+ python_type = float
+ elif prop_type == "boolean":
+ python_type = bool
+ elif prop_type == "array":
+ python_type = list
+ elif prop_type == "object":
+ python_type = dict
+
+ default = ... if prop_name in required else None
+
+ fields[prop_name] = (python_type, Field(default=default, description=prop_desc))
+
+ args_schema = None
+ if fields:
+ args_schema = create_model(f"{name}Schema", **fields)
+
# Capture the tool name in the closure
def make_call(tool_name=name):
async def call_remote_tool(**kwargs):
@@ -28,7 +60,8 @@ def get_langchain_tools(client: SamClient, tools: List[Dict[str, Any]]) -> List[
lc_tool = StructuredTool.from_function(
name=name,
description=description,
- coroutine=make_call(name)
+ coroutine=make_call(name),
+ args_schema=args_schema
)
lc_tools.append(lc_tool)
diff --git a/sam-mcp-python/src/sam_mcp/client.py b/sam-mcp-python/src/sam_mcp/client.py
index b107c3e8..cc3ad15e 100644
--- a/sam-mcp-python/src/sam_mcp/client.py
+++ b/sam-mcp-python/src/sam_mcp/client.py
@@ -41,20 +41,8 @@ class SamClient:
raise JsonRpcError(resp["error"]["code"], resp["error"]["message"], resp["error"].get("data"))
# Standard MCP also expects an 'initialized' notification
- notif = {
- "jsonrpc": "2.0",
- "method": "notifications/initialized"
- }
- # We don't strictly need to wait for response for notification, but we send it.
- await self.transport.writer.write((
- f"POST /mcp HTTP/1.1\r\n"
- f"Host: localhost\r\n"
- f"Content-Type: application/json\r\n"
- f"Content-Length: {len(json.dumps(notif))}\r\n"
- f"\r\n"
- f"{json.dumps(notif)}"
- ).encode('utf-8'))
- await self.transport.writer.drain()
+ notif = Protocol.create_request("notifications/initialized")
+ await self.transport.send_message(json.dumps(notif))
async def get_tools(self) -> List[Dict[str, Any]]:
"""Returns available mesh tools."""
diff --git a/sam-mcp-python/src/sam_mcp/protocol.py b/sam-mcp-python/src/sam_mcp/protocol.py
index 41c194af..66a21908 100644
--- a/sam-mcp-python/src/sam_mcp/protocol.py
+++ b/sam-mcp-python/src/sam_mcp/protocol.py
@@ -51,7 +51,7 @@ class Protocol:
try:
data = json.loads(message_str)
except json.JSONDecodeError as e:
- raise JsonRpcError(-32700, "Parse error", str(e))
+ raise JsonRpcError(-32700, f"Parse error: {e}. Message: {message_str}")
if not isinstance(data, dict):
raise JsonRpcError(-32600, "Invalid Request", "Message must be a JSON object")
diff --git a/sam-mcp-python/src/sam_mcp/transport.py b/sam-mcp-python/src/sam_mcp/transport.py
index 3c276103..6e645855 100644
--- a/sam-mcp-python/src/sam_mcp/transport.py
+++ b/sam-mcp-python/src/sam_mcp/transport.py
@@ -32,7 +32,7 @@ class SamTransport:
f"POST /mcp HTTP/1.1\r\n"
f"Host: localhost\r\n"
f"Content-Type: application/json\r\n"
- f"Accept: application/json\r\n"
+ f"Accept: application/json, text/event-stream\r\n"
f"Content-Length: {len(data_bytes)}\r\n"
f"\r\n"
).encode('utf-8') + data_bytes
@@ -53,17 +53,29 @@ class SamTransport:
headers_str = headers_data.decode('utf-8')
lines = headers_str.split("\r\n")
+ # Parse status line
+ status_line = lines[0]
+ parts = status_line.split(" ", 2)
+ if len(parts) < 2:
+ raise RuntimeError(f"Invalid HTTP status line: {status_line}")
+ status_code = int(parts[1])
+
# Find Content-Length
content_length = 0
- for line in lines:
+ for line in lines[1:]:
if line.lower().startswith("content-length:"):
content_length = int(line.split(":", 1)[1].strip())
break
+ if not (200 <= status_code < 300):
+ body = ""
+ if content_length > 0:
+ body_bytes = await self.reader.readexactly(content_length)
+ body = body_bytes.decode('utf-8')
+ raise RuntimeError(f"HTTP Error {status_code}: {body}")
+
if content_length == 0:
- # If no content length, read until EOF
- body = await self.reader.read(-1)
- return body.decode('utf-8')
+ return ""
body = await self.reader.readexactly(content_length)
return body.decode('utf-8')