Python Client Example
Complete Python implementation of an MCP client for TraceMem.
Overview
This example provides a reusable Python client class for interacting with TraceMem's Agent MCP server.
Client Implementation
text
import requests
import json
class MCPClient:
def __init__(self, base_url, api_key):
self.base_url = base_url
self.api_key = api_key
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"Agent {api_key}",
"Content-Type": "application/json"
})
self.request_id = 0
self.initialized = False
def _next_id(self):
self.request_id += 1
return self.request_id
def _call(self, method, params=None):
request = {
"jsonrpc": "2.0",
"id": self._next_id(),
"method": method,
"params": params or {}
}
response = self.session.post(self.base_url, json=request)
response.raise_for_status()
result = response.json()
if "error" in result:
error = result["error"]
raise Exception(f"MCP Error {error['code']}: {error['message']}")
return result.get("result", {})
def initialize(self):
result = self._call("initialize", {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {"name": "my-agent", "version": "1.0.0"}
})
self.initialized = True
return result
def call_tool(self, name, arguments):
if not self.initialized:
self.initialize()
result = self._call("tools/call", {
"name": name,
"arguments": arguments
})
# Extract text content from MCP response
if "content" in result and len(result["content"]) > 0:
text_content = result["content"][0].get("text", "{}")
try:
return json.loads(text_content)
except json.JSONDecodeError:
return {"raw_text": text_content}
return result
Usage Examples
[Content to be filled]
Error Handling
[Content to be filled]