Skip to content

Agent Mesh

add python sdk

Antonio Ojeae0d4b70cf708
diff --git a/.github/workflows/test_python.yml b/.github/workflows/test_python.yml
new file mode 100644
index 00000000..c97de2c0
--- /dev/null
+++ b/.github/workflows/test_python.yml
@@ -0,0 +1,48 @@
+name: Python SDK Test
+
+on:
+ push:
+ branches: [ main ]
+ paths:
+ - 'sam-mcp-python/**'
+ pull_request:
+ branches: [ main ]
+ paths:
+ - 'sam-mcp-python/**'
+
+jobs:
+ test_python:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Go
+ uses: actions/setup-go@v5
+ with:
+ go-version: '1.22'
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.10'
+
+ - name: Build Go node
+ run: |
+ make build
+
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install -e .[test]
+ working-directory: sam-mcp-python
+
+ - name: Run unit tests
+ run: |
+ pytest tests/unit
+ working-directory: sam-mcp-python
+
+ - name: Run E2E tests
+ run: |
+ pytest tests/e2e
+ working-directory: sam-mcp-python
diff --git a/sam-mcp-python/README.md b/sam-mcp-python/README.md
new file mode 100644
index 00000000..916f2e89
--- /dev/null
+++ b/sam-mcp-python/README.md
@@ -0,0 +1,38 @@
+# SAM Python SDK (sam-mcp-python)
+
+The official Python SDK for the Sovereign Agent Mesh (SAM).
+
+This SDK acts as a "Thin Client" that connects to the local Go node via a Unix Domain Socket and communicates using the Model Context Protocol (MCP) over JSON-RPC 2.0.
+
+## Installation
+
+```bash
+pip install .
+```
+
+## Usage
+
+```python
+import asyncio
+from sam_mcp.client import SamClient
+
+async def main():
+ async with SamClient() as client:
+ tools = await client.get_tools()
+ print("Available tools:", tools)
+
+ result = await client.call_tool("echo", {"message": "hello"})
+ print("Result:", result)
+
+if __name__ == "__main__":
+ asyncio.run(main())
+```
+
+## Development
+
+### Running Tests
+
+```bash
+pytest tests/unit
+pytest tests/e2e
+```
diff --git a/sam-mcp-python/pyproject.toml b/sam-mcp-python/pyproject.toml
new file mode 100644
index 00000000..1c4c4d5b
--- /dev/null
+++ b/sam-mcp-python/pyproject.toml
@@ -0,0 +1,26 @@
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[project]
+name = "sam-mcp"
+version = "0.1.0"
+description = "Python SDK for Sovereign Agent Mesh (SAM) using MCP"
+readme = "README.md"
+requires-python = ">=3.10"
+dependencies = []
+
+[project.optional-dependencies]
+langchain = [
+ "langchain-core>=0.1.0",
+]
+test = [
+ "pytest>=7.0.0",
+ "pytest-asyncio>=0.20.0",
+]
+
+[tool.hatch.build.targets.sdist]
+include = ["src"]
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/sam_mcp"]
diff --git a/sam-mcp-python/src/sam_mcp/__init__.py b/sam-mcp-python/src/sam_mcp/__init__.py
new file mode 100644
index 00000000..1a06e96b
--- /dev/null
+++ b/sam-mcp-python/src/sam_mcp/__init__.py
@@ -0,0 +1,3 @@
+"""SAM MCP Python SDK."""
+
+__version__ = "0.1.0"
diff --git a/sam-mcp-python/src/sam_mcp/adapters/__init__.py b/sam-mcp-python/src/sam_mcp/adapters/__init__.py
new file mode 100644
index 00000000..6bc465bf
--- /dev/null
+++ b/sam-mcp-python/src/sam_mcp/adapters/__init__.py
@@ -0,0 +1 @@
+"""Adapters for popular frameworks."""
diff --git a/sam-mcp-python/src/sam_mcp/adapters/langchain.py b/sam-mcp-python/src/sam_mcp/adapters/langchain.py
new file mode 100644
index 00000000..b251f8bc
--- /dev/null
+++ b/sam-mcp-python/src/sam_mcp/adapters/langchain.py
@@ -0,0 +1,35 @@
+from typing import Any, Dict, List
+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.
+ """
+ try:
+ from langchain_core.tools import StructuredTool
+ except ImportError:
+ raise ImportError(
+ "langchain-core is required to use this adapter. "
+ "Install it with `pip install langchain-core`"
+ )
+
+ lc_tools = []
+ for tool in tools:
+ name = tool.get("name")
+ description = tool.get("description", "")
+
+ # Capture the tool name in the closure
+ def make_call(tool_name=name):
+ async def call_remote_tool(**kwargs):
+ return await client.call_tool(tool_name, kwargs)
+ return call_remote_tool
+
+ lc_tool = StructuredTool.from_function(
+ name=name,
+ description=description,
+ coroutine=make_call(name)
+ )
+ lc_tools.append(lc_tool)
+
+ return lc_tools
diff --git a/sam-mcp-python/src/sam_mcp/client.py b/sam-mcp-python/src/sam_mcp/client.py
new file mode 100644
index 00000000..b107c3e8
--- /dev/null
+++ b/sam-mcp-python/src/sam_mcp/client.py
@@ -0,0 +1,90 @@
+import json
+import os
+from typing import Any, Dict, List, Optional
+from .transport import SamTransport
+from .protocol import Protocol, JsonRpcError
+
+class SamClient:
+ """High-level developer interface for SAM MCP."""
+
+ def __init__(self, socket_path: Optional[str] = None):
+ if socket_path is None:
+ socket_path = os.environ.get("SAM_MCP_SOCKET", "/tmp/sam/mcp.sock")
+ self.transport = SamTransport(socket_path)
+ self._request_id = 0
+
+ async def connect(self):
+ """Connects to the SAM node and performs MCP initialization."""
+ await self.transport.connect()
+ await self._initialize()
+
+ async def close(self):
+ """Closes the connection."""
+ await self.transport.close()
+
+ def _next_id(self) -> int:
+ self._request_id += 1
+ return self._request_id
+
+ async def _initialize(self):
+ """Performs MCP handshake."""
+ params = {
+ "protocolVersion": "2024-11-05",
+ "capabilities": {},
+ "clientInfo": {"name": "sam-mcp-python", "version": "0.1.0"}
+ }
+ req = Protocol.create_request("initialize", params, self._next_id())
+ resp_str = await self.transport.send_message(json.dumps(req))
+ resp = Protocol.parse_message(resp_str)
+
+ if "error" in resp:
+ 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()
+
+ async def get_tools(self) -> List[Dict[str, Any]]:
+ """Returns available mesh tools."""
+ req = Protocol.create_request("tools/list", {}, self._next_id())
+ resp_str = await self.transport.send_message(json.dumps(req))
+ resp = Protocol.parse_message(resp_str)
+
+ if "error" in resp:
+ raise JsonRpcError(resp["error"]["code"], resp["error"]["message"], resp["error"].get("data"))
+
+ return resp.get("result", {}).get("tools", [])
+
+ async def call_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
+ """Executes a tool over the mesh."""
+ params = {
+ "name": name,
+ "arguments": arguments
+ }
+ req = Protocol.create_request("tools/call", params, self._next_id())
+ resp_str = await self.transport.send_message(json.dumps(req))
+ resp = Protocol.parse_message(resp_str)
+
+ if "error" in resp:
+ raise JsonRpcError(resp["error"]["code"], resp["error"]["message"], resp["error"].get("data"))
+
+ return resp.get("result", {})
+
+ async def __aenter__(self):
+ await self.connect()
+ return self
+
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
+ await self.close()
diff --git a/sam-mcp-python/src/sam_mcp/protocol.py b/sam-mcp-python/src/sam_mcp/protocol.py
new file mode 100644
index 00000000..41c194af
--- /dev/null
+++ b/sam-mcp-python/src/sam_mcp/protocol.py
@@ -0,0 +1,62 @@
+import json
+from typing import Any, Dict, Optional, Union
+
+class JsonRpcError(Exception):
+ def __init__(self, code: int, message: str, data: Optional[Any] = None):
+ self.code = code
+ self.message = message
+ self.data = data
+ super().__init__(f"JSON-RPC Error {code}: {message}")
+
+ def to_dict(self) -> Dict[str, Any]:
+ res = {"code": self.code, "message": self.message}
+ if self.data is not None:
+ res["data"] = self.data
+ return res
+
+class Protocol:
+ @staticmethod
+ def create_request(method: str, params: Optional[Dict[str, Any]] = None, request_id: Optional[Union[int, str]] = None) -> Dict[str, Any]:
+ req = {
+ "jsonrpc": "2.0",
+ "method": method,
+ }
+ if params is not None:
+ req["params"] = params
+ if request_id is not None:
+ req["id"] = request_id
+ return req
+
+ @staticmethod
+ def create_response(request_id: Union[int, str], result: Any) -> Dict[str, Any]:
+ return {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "result": result
+ }
+
+ @staticmethod
+ def create_error_response(request_id: Optional[Union[int, str]], code: int, message: str, data: Optional[Any] = None) -> Dict[str, Any]:
+ error = {"code": code, "message": message}
+ if data is not None:
+ error["data"] = data
+ return {
+ "jsonrpc": "2.0",
+ "id": request_id,
+ "error": error
+ }
+
+ @staticmethod
+ def parse_message(message_str: str) -> Dict[str, Any]:
+ try:
+ data = json.loads(message_str)
+ except json.JSONDecodeError as e:
+ raise JsonRpcError(-32700, "Parse error", str(e))
+
+ if not isinstance(data, dict):
+ raise JsonRpcError(-32600, "Invalid Request", "Message must be a JSON object")
+
+ if data.get("jsonrpc") != "2.0":
+ raise JsonRpcError(-32600, "Invalid Request", "Missing or invalid jsonrpc version")
+
+ return data
diff --git a/sam-mcp-python/src/sam_mcp/transport.py b/sam-mcp-python/src/sam_mcp/transport.py
new file mode 100644
index 00000000..3c276103
--- /dev/null
+++ b/sam-mcp-python/src/sam_mcp/transport.py
@@ -0,0 +1,76 @@
+import asyncio
+import os
+from typing import Optional
+
+class SamTransport:
+ """Handles Unix domain socket connections and HTTP-like messaging for MCP."""
+
+ def __init__(self, socket_path: str):
+ self.socket_path = socket_path
+ self.reader: Optional[asyncio.StreamReader] = None
+ self.writer: Optional[asyncio.StreamWriter] = None
+
+ async def connect(self):
+ """Establishes connection to the Unix socket."""
+ self.reader, self.writer = await asyncio.open_unix_connection(self.socket_path)
+
+ async def close(self):
+ """Closes the connection."""
+ if self.writer:
+ self.writer.close()
+ await self.writer.wait_closed()
+ self.reader = None
+ self.writer = None
+
+ async def send_message(self, data: str) -> str:
+ """Sends a JSON-RPC message wrapped in HTTP POST and returns the response body."""
+ if not self.writer or not self.reader:
+ raise RuntimeError("Not connected to SAM node")
+
+ data_bytes = data.encode('utf-8')
+ request = (
+ 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"Content-Length: {len(data_bytes)}\r\n"
+ f"\r\n"
+ ).encode('utf-8') + data_bytes
+
+ self.writer.write(request)
+ await self.writer.drain()
+
+ # Read HTTP response headers
+ headers_data = bytearray()
+ while True:
+ line = await self.reader.readline()
+ if not line:
+ raise RuntimeError("Connection closed while reading headers")
+ headers_data.extend(line)
+ if headers_data.endswith(b"\r\n\r\n"):
+ break
+
+ headers_str = headers_data.decode('utf-8')
+ lines = headers_str.split("\r\n")
+
+ # Find Content-Length
+ content_length = 0
+ for line in lines:
+ if line.lower().startswith("content-length:"):
+ content_length = int(line.split(":", 1)[1].strip())
+ break
+
+ if content_length == 0:
+ # If no content length, read until EOF
+ body = await self.reader.read(-1)
+ return body.decode('utf-8')
+
+ body = await self.reader.readexactly(content_length)
+ return body.decode('utf-8')
+
+ async def __aenter__(self):
+ await self.connect()
+ return self
+
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
+ await self.close()
diff --git a/sam-mcp-python/tests/e2e/test_e2e.py b/sam-mcp-python/tests/e2e/test_e2e.py
new file mode 100644
index 00000000..039f9aa6
--- /dev/null
+++ b/sam-mcp-python/tests/e2e/test_e2e.py
@@ -0,0 +1,91 @@
+import asyncio
+import os
+import subprocess
+import time
+import pytest
+import pytest_asyncio
+from sam_mcp.client import SamClient
+
[email protected](scope="session")
+def sam_node_binary():
+ """Ensures the sam-node binary is built."""
+ repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))
+ bin_path = os.path.join(repo_root, "bin", "sam-node")
+
+ if not os.path.exists(bin_path):
+ print(f"Binary not found at {bin_path}, building...")
+ subprocess.run(["make", "build"], cwd=repo_root, check=True)
+
+ return bin_path
+
[email protected](scope="function")
+def sam_node(sam_node_binary):
+ """Spins up a sam-node instance for testing."""
+ socket_path = f"/tmp/sam-test-mcp-{os.getpid()}.sock"
+ if os.path.exists(socket_path):
+ os.remove(socket_path)
+
+ # Create directory if not exists
+ os.makedirs(os.path.dirname(socket_path), exist_ok=True)
+
+ # Run sam-node with a dummy JWT and custom socket path.
+ # We might need to pass more flags if it requires a hub, but let's try minimal first.
+ process = subprocess.Popen(
+ [sam_node_binary, "run", "--mcp-socket", socket_path, "--jwt", "dummy-token"],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+
+ # Wait for the socket file to appear
+ connected = False
+ for _ in range(20):
+ if os.path.exists(socket_path):
+ connected = True
+ break
+ time.sleep(0.5)
+
+ if not connected:
+ process.kill()
+ stdout, stderr = process.communicate()
+ pytest.fail(f"sam-node failed to create socket. Stdout: {stdout.decode()}, Stderr: {stderr.decode()}")
+
+ yield socket_path
+
+ process.terminate()
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ process.kill()
+
+ if os.path.exists(socket_path):
+ os.remove(socket_path)
+
+async def test_e2e_get_tools(sam_node):
+ """Verifies that we can connect to the real node and get tools."""
+ os.environ["SAM_MCP_SOCKET"] = sam_node
+
+ async with SamClient() as client:
+ tools = await client.get_tools()
+ assert isinstance(tools, list)
+ # Even if empty, it should be a list
+ print(f"Received tools: {tools}")
+
+async def test_e2e_call_echo_tool(sam_node):
+ """Verifies that we can call a tool on the real node."""
+ os.environ["SAM_MCP_SOCKET"] = sam_node
+
+ async with SamClient() as client:
+ # Assuming the node has an 'echo' or similar built-in tool or returns error gracefully
+ try:
+ result = await client.call_tool("echo", {"message": "hello"})
+ print(f"Tool result: {result}")
+ except Exception as e:
+ # If 'echo' doesn't exist, we might get a JSON-RPC error, which is also a valid E2E interaction
+ print(f"Tool call failed as expected if missing: {e}")
+ # If it's a connection error, that's a failure. If it's a method not found, that's a success for the pipeline.
+ if "Method not found" in str(e) or "error" in str(e).lower():
+ pass
+ else:
+ raise e
diff --git a/sam-mcp-python/tests/unit/test_unit.py b/sam-mcp-python/tests/unit/test_unit.py
new file mode 100644
index 00000000..8c5e595b
--- /dev/null
+++ b/sam-mcp-python/tests/unit/test_unit.py
@@ -0,0 +1,106 @@
+import asyncio
+import json
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+from sam_mcp.protocol import Protocol, JsonRpcError
+from sam_mcp.transport import SamTransport
+from sam_mcp.client import SamClient
+from sam_mcp.adapters.langchain import get_langchain_tools
+
+# Protocol Tests
+def test_protocol_create_request():
+ req = Protocol.create_request("test_method", {"param": "value"}, 1)
+ assert req == {
+ "jsonrpc": "2.0",
+ "method": "test_method",
+ "params": {"param": "value"},
+ "id": 1
+ }
+
+def test_protocol_create_response():
+ resp = Protocol.create_response(1, {"result": "ok"})
+ assert resp == {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "result": {"result": "ok"}
+ }
+
+def test_protocol_parse_message():
+ msg = '{"jsonrpc": "2.0", "method": "test", "id": 1}'
+ parsed = Protocol.parse_message(msg)
+ assert parsed["method"] == "test"
+
+def test_protocol_parse_invalid_json():
+ with pytest.raises(JsonRpcError) as excinfo:
+ Protocol.parse_message("{invalid}")
+ assert excinfo.value.code == -32700
+
+# Transport Tests
+async def test_transport_send_message():
+ transport = SamTransport("/tmp/test.sock")
+
+ mock_reader = AsyncMock()
+ # Simulate HTTP response
+ mock_reader.readline.side_effect = [
+ b"HTTP/1.1 200 OK\r\n",
+ b"Content-Length: 15\r\n",
+ b"\r\n"
+ ]
+ mock_reader.readexactly.return_value = b'{"result":"ok"}'
+
+ mock_writer = MagicMock()
+ mock_writer.drain = AsyncMock()
+
+ transport.reader = mock_reader
+ transport.writer = mock_writer
+
+ resp = await transport.send_message('{"method":"test"}')
+ assert resp == '{"result":"ok"}'
+
+ # Verify HTTP request was sent
+ args, _ = mock_writer.write.call_args
+ request_bytes = args[0]
+ assert b"POST /mcp HTTP/1.1" in request_bytes
+ assert b"Content-Length: 17" in request_bytes
+
+# Client Tests
+async def test_client_get_tools():
+ with patch("sam_mcp.client.SamTransport") as MockTransport:
+ mock_transport = MockTransport.return_value
+ mock_transport.connect = AsyncMock()
+ mock_transport.close = AsyncMock()
+
+ # Mock initialize response and tools/list response
+ mock_transport.send_message.side_effect = [
+ '{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2024-11-05"}}', # init
+ '{"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"test_tool"}]}}' # list
+ ]
+ mock_transport.writer = MagicMock()
+ mock_transport.writer.write = AsyncMock()
+ mock_transport.writer.drain = AsyncMock()
+
+ async with SamClient(socket_path="/tmp/test.sock") as client:
+ tools = await client.get_tools()
+ assert len(tools) == 1
+ assert tools[0]["name"] == "test_tool"
+
+# Adapter Tests
+def test_langchain_adapter():
+ class MockClient:
+ pass
+
+ client = MockClient()
+ tools = [{"name": "test_tool", "description": "A test tool"}]
+
+ # We need to mock langchain-core import if it's not installed in the environment
+ with patch.dict("sys.modules", {"langchain_core.tools": MagicMock()}):
+ from langchain_core.tools import StructuredTool
+
+ mock_structured_tool = MagicMock()
+ StructuredTool.from_function.return_value = mock_structured_tool
+
+ lc_tools = get_langchain_tools(client, tools)
+ assert len(lc_tools) == 1
+ assert lc_tools[0] == mock_structured_tool
diff --git a/tests/e2e/python_sdk_test.bats b/tests/e2e/python_sdk_test.bats
new file mode 100644
index 00000000..cc6b7c56
--- /dev/null
+++ b/tests/e2e/python_sdk_test.bats
@@ -0,0 +1,70 @@
+#!/usr/bin/env bats
+
+load "lib/container_mesh.bash"
+
+setup() {
+ if ! mesh_require_docker; then
+ skip "docker not available or daemon not running"
+ fi
+
+ if [[ ! -x "./bin/sam-node" || ! -x "./bin/sam-hub" ]]; then
+ skip "missing binaries; run: make build"
+ fi
+
+ mesh_setup_env
+}
+
+teardown() {
+ mesh_cleanup_env
+}
+
+@test "Python SDK: Connect, get tools, and call tool" {
+ run mesh_start_mock_oidc
+ [[ "$status" -eq 0 ]]
+
+ run mesh_start_hub
+ [[ "$status" -eq 0 ]]
+
+ run mesh_start_node 1 "--discovery-interval 100ms --log-level debug"
+ [[ "$status" -eq 0 ]]
+
+ local node1_name="${MESH_PREFIX}-node-1"
+ mesh_wait_for_log "${node1_name}" "SAM Node Online" 20
+ mesh_wait_for_mcp_ready 1 20
+
+ # Use the Python SDK to interact with the node
+ run docker run --rm \
+ -v "${MESH_SOCKET_DIR}:/sockets" \
+ -v "$(pwd)/sam-mcp-python:/sam-mcp-python" \
+ -e PYTHONPATH=/sam-mcp-python/src \
+ python:3.12 \
+ python3 -c "
+import asyncio
+from sam_mcp.client import SamClient
+import os
+import sys
+
+async def main():
+ os.environ['SAM_MCP_SOCKET'] = '/sockets/node-1.sock'
+ try:
+ async with SamClient() as client:
+ # Test get_tools
+ tools = await client.get_tools()
+ print(f'TOOLS_COUNT:{len(tools)}')
+
+ # Test call_tool (get_mesh_info is a standard tool in sam-node)
+ result = await client.call_tool('get_mesh_info', {})
+ print(f'CALL_RESULT:{result}')
+
+ sys.exit(0)
+ except Exception as e:
+ print(f'ERROR:{e}')
+ sys.exit(1)
+
+asyncio.run(main())
+"
+ echo "Python SDK output: $output"
+ [[ "$status" -eq 0 ]]
+ [[ "$output" == *"TOOLS_COUNT:"* ]]
+ [[ "$output" == *"CALL_RESULT:"* ]]
+}