mcpager 0.1.0__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.
- mcpager/__init__.py +0 -0
- mcpager/adapters/__init__.py +6 -0
- mcpager/adapters/backends.py +90 -0
- mcpager/client/__init__.py +12 -0
- mcpager/client/client.py +21 -0
- mcpager/client/session.py +127 -0
- mcpager/client/transport.py +163 -0
- mcpager-0.1.0.dist-info/METADATA +20 -0
- mcpager-0.1.0.dist-info/RECORD +11 -0
- mcpager-0.1.0.dist-info/WHEEL +5 -0
- mcpager-0.1.0.dist-info/top_level.txt +1 -0
mcpager/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import List, Any, Dict
|
|
3
|
+
from functools import partial
|
|
4
|
+
|
|
5
|
+
from langchain_core.tools import BaseTool, StructuredTool
|
|
6
|
+
from pydantic import create_model
|
|
7
|
+
|
|
8
|
+
from mcpager.client import Session
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class BackendAdapter(ABC):
|
|
12
|
+
"""Abstract interface defining how to talk to a backend engine."""
|
|
13
|
+
|
|
14
|
+
@abstractmethod
|
|
15
|
+
def initialize(self, session: Session, **kwargs) -> dict:
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
@abstractmethod
|
|
19
|
+
def list_tools(self, session: Session) -> List[dict]:
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
@abstractmethod
|
|
23
|
+
def call_tool(self, session: Session, name: str, args: dict) -> dict:
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class LangGraphBackend(BackendAdapter):
|
|
28
|
+
"""Implements backend logic for a LangGraph-style MCP server."""
|
|
29
|
+
|
|
30
|
+
def initialize(self, session: Session, **kwargs) -> dict:
|
|
31
|
+
return session.initialize(**kwargs)
|
|
32
|
+
|
|
33
|
+
def list_tools(self, session: Session) -> List[BaseTool]:
|
|
34
|
+
tools_data = session.list_tools()
|
|
35
|
+
return [
|
|
36
|
+
self.convert_mcp_tool_to_langchain_tool(session, t)
|
|
37
|
+
for t in tools_data
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
def call_tool(self, session: Session, name: str, **kwargs: Dict[str, Any]) -> Any:
|
|
41
|
+
result = session._send_request("tools/call", {"name": name, "arguments": kwargs})
|
|
42
|
+
# Return as (content, artifact)
|
|
43
|
+
# 'content' is what the LLM sees, 'artifact' is the raw result
|
|
44
|
+
if isinstance(result, dict):
|
|
45
|
+
content = result.get("content") or result.get("result") or str(result)
|
|
46
|
+
else:
|
|
47
|
+
content = str(result)
|
|
48
|
+
|
|
49
|
+
return (content, result)
|
|
50
|
+
|
|
51
|
+
def convert_mcp_tool_to_langchain_tool(
|
|
52
|
+
self,
|
|
53
|
+
session: Session,
|
|
54
|
+
tool_info: dict
|
|
55
|
+
) -> StructuredTool:
|
|
56
|
+
"""
|
|
57
|
+
Convert an MCP tool description (from session.list_tools()) into
|
|
58
|
+
a LangChain-compatible StructuredTool
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
tool_name = tool_info["name"]
|
|
62
|
+
description = tool_info.get("description", "")
|
|
63
|
+
|
|
64
|
+
# Build args schema dynamically from MCP input schema (if any)
|
|
65
|
+
input_schema = tool_info.get("inputSchema", {"type": "object", "properties": {}})
|
|
66
|
+
properties = input_schema.get("properties", {})
|
|
67
|
+
|
|
68
|
+
fields = {}
|
|
69
|
+
for name, prop in properties.items():
|
|
70
|
+
typ = str # default type
|
|
71
|
+
match prop.get("type"):
|
|
72
|
+
case "number":
|
|
73
|
+
typ = float
|
|
74
|
+
case "integer":
|
|
75
|
+
typ = int
|
|
76
|
+
case "boolean":
|
|
77
|
+
typ = bool
|
|
78
|
+
case "array":
|
|
79
|
+
typ = list
|
|
80
|
+
fields[name] = (typ, ... if name in input_schema.get("required", []) else None)
|
|
81
|
+
|
|
82
|
+
ArgsModel = create_model(f"{tool_name}_Args", **fields)
|
|
83
|
+
|
|
84
|
+
return StructuredTool(
|
|
85
|
+
name=tool_name,
|
|
86
|
+
description=description,
|
|
87
|
+
args_schema=ArgsModel,
|
|
88
|
+
func=partial(self.call_tool, session, tool_name),
|
|
89
|
+
response_format="content_and_artifact",
|
|
90
|
+
)
|
mcpager/client/client.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from typing import List
|
|
2
|
+
|
|
3
|
+
from mcpager.adapters import BackendAdapter
|
|
4
|
+
from .session import Session
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class MCPClient:
|
|
8
|
+
"""User-facing high-level client for interacting with a backend."""
|
|
9
|
+
|
|
10
|
+
def __init__(self, backend: BackendAdapter, session: Session):
|
|
11
|
+
self.backend = backend
|
|
12
|
+
self.session = session
|
|
13
|
+
|
|
14
|
+
def initialize(self, **kwargs) -> dict:
|
|
15
|
+
return self.backend.initialize(self.session, **kwargs)
|
|
16
|
+
|
|
17
|
+
def list_tools(self) -> List[dict]:
|
|
18
|
+
return self.backend.list_tools(self.session)
|
|
19
|
+
|
|
20
|
+
def call_tool(self, name: str, **kwargs: dict) -> dict:
|
|
21
|
+
return self.backend.call_tool(self.session, name, **kwargs)
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import threading
|
|
3
|
+
import uuid
|
|
4
|
+
from typing import Any, Dict, Optional
|
|
5
|
+
from .transport import Transport
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SessionError(Exception):
|
|
9
|
+
"""Base class for all session errors."""
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Session:
|
|
14
|
+
"""
|
|
15
|
+
A synchronous implementation of an MCP client session.
|
|
16
|
+
Mirrors the logic of async ClientSession.initialize() and list_tools().
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, transport: Transport):
|
|
20
|
+
self.transport = transport
|
|
21
|
+
self._lock = threading.Lock()
|
|
22
|
+
self._id_counter = 0
|
|
23
|
+
self.capabilities = {}
|
|
24
|
+
self.initialized = False
|
|
25
|
+
|
|
26
|
+
def _next_id(self) -> str:
|
|
27
|
+
self._id_counter += 1
|
|
28
|
+
return f"req-{self._id_counter}-{uuid.uuid4().hex[:6]}"
|
|
29
|
+
|
|
30
|
+
def _send_request(
|
|
31
|
+
self,
|
|
32
|
+
method: str,
|
|
33
|
+
params: Optional[dict] = None,
|
|
34
|
+
timeout: float = 10.0,
|
|
35
|
+
) -> Dict[str, Any]:
|
|
36
|
+
"""Send a request and wait for the corresponding response.
|
|
37
|
+
|
|
38
|
+
Supports both normal and streaming transports.
|
|
39
|
+
"""
|
|
40
|
+
with self._lock:
|
|
41
|
+
req_id = self._next_id()
|
|
42
|
+
message = {
|
|
43
|
+
"jsonrpc": "2.0",
|
|
44
|
+
"id": req_id,
|
|
45
|
+
"method": method,
|
|
46
|
+
"params": params or {},
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
self.transport.send(message)
|
|
50
|
+
|
|
51
|
+
response = self.transport.receive(timeout=timeout)
|
|
52
|
+
|
|
53
|
+
# normal dict response
|
|
54
|
+
if isinstance(response, dict):
|
|
55
|
+
if response.get("id") == req_id:
|
|
56
|
+
if "error" in response:
|
|
57
|
+
raise SessionError(response["error"])
|
|
58
|
+
return response.get("result", {})
|
|
59
|
+
else:
|
|
60
|
+
raise SessionError(f"Unexpected response id: {response.get('id')}")
|
|
61
|
+
|
|
62
|
+
# streaming generator
|
|
63
|
+
elif hasattr(response, "__iter__"):
|
|
64
|
+
final_result = None
|
|
65
|
+
for event in response:
|
|
66
|
+
if not isinstance(event, dict):
|
|
67
|
+
continue
|
|
68
|
+
|
|
69
|
+
# Optional: handle progress events or updates
|
|
70
|
+
if event.get("method") == "progress":
|
|
71
|
+
# You could yield or log this
|
|
72
|
+
continue
|
|
73
|
+
|
|
74
|
+
# Handle final result
|
|
75
|
+
if event.get("id") == req_id:
|
|
76
|
+
if "error" in event:
|
|
77
|
+
raise SessionError(event["error"])
|
|
78
|
+
final_result = event.get("result")
|
|
79
|
+
|
|
80
|
+
if final_result is None:
|
|
81
|
+
raise SessionError(f"No final result for request {req_id}")
|
|
82
|
+
return final_result
|
|
83
|
+
|
|
84
|
+
else:
|
|
85
|
+
raise SessionError(f"Unexpected response type: {type(response)}")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# === MCP client methods ===
|
|
89
|
+
|
|
90
|
+
def initialize(
|
|
91
|
+
self,
|
|
92
|
+
client_name: str = "mcpager",
|
|
93
|
+
client_version: str = "0.1.0",
|
|
94
|
+
protocol_version: str = "2025-03-26",
|
|
95
|
+
capabilities: Optional[str] = None
|
|
96
|
+
):
|
|
97
|
+
"""Initialize connection to the MCP server."""
|
|
98
|
+
params = {
|
|
99
|
+
"clientInfo": {
|
|
100
|
+
"name": client_name,
|
|
101
|
+
"version": client_version,
|
|
102
|
+
},
|
|
103
|
+
"capabilities": capabilities or {},
|
|
104
|
+
"protocolVersion": protocol_version
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
result = self._send_request("initialize", params)
|
|
108
|
+
self.capabilities = result.get("capabilities", {})
|
|
109
|
+
self.session_id = result.get("sessionId")
|
|
110
|
+
self.initialized = True
|
|
111
|
+
return result
|
|
112
|
+
|
|
113
|
+
def list_tools(self):
|
|
114
|
+
"""Retrieve list of tools available on the MCP server."""
|
|
115
|
+
if not self.initialized:
|
|
116
|
+
raise SessionError("Session not initialized. Call initialize() first.")
|
|
117
|
+
|
|
118
|
+
result = self._send_request("tools/list")
|
|
119
|
+
tools = result.get("tools", [])
|
|
120
|
+
return tools
|
|
121
|
+
|
|
122
|
+
def close(self):
|
|
123
|
+
"""Gracefully close the transport connection."""
|
|
124
|
+
try:
|
|
125
|
+
self.transport.close()
|
|
126
|
+
except Exception:
|
|
127
|
+
pass
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import subprocess
|
|
3
|
+
import time
|
|
4
|
+
import abc
|
|
5
|
+
from typing import Any, Optional
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Transport(abc.ABC):
|
|
11
|
+
"""Abstract transport interface for MCP communication."""
|
|
12
|
+
|
|
13
|
+
@abc.abstractmethod
|
|
14
|
+
def send(self, message: dict[str, Any]) -> None:
|
|
15
|
+
"""Send a JSON-RPC message to the backend."""
|
|
16
|
+
raise NotImplementedError
|
|
17
|
+
|
|
18
|
+
@abc.abstractmethod
|
|
19
|
+
def receive(self, timeout: Optional[float] = None) -> dict[str, Any]:
|
|
20
|
+
"""Wait for a JSON-RPC message from the backend."""
|
|
21
|
+
raise NotImplementedError
|
|
22
|
+
|
|
23
|
+
@abc.abstractmethod
|
|
24
|
+
def close(self) -> None:
|
|
25
|
+
"""Cleanly close the connection."""
|
|
26
|
+
raise NotImplementedError
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class StdioTransport(Transport):
|
|
31
|
+
def __init__(self, command: list[str]):
|
|
32
|
+
self.process = subprocess.Popen(
|
|
33
|
+
command,
|
|
34
|
+
stdin=subprocess.PIPE,
|
|
35
|
+
stdout=subprocess.PIPE,
|
|
36
|
+
stderr=subprocess.PIPE,
|
|
37
|
+
text=True,
|
|
38
|
+
bufsize=1,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
def send(self, message: dict[str, Any]):
|
|
42
|
+
line = json.dumps(message)
|
|
43
|
+
print(message)
|
|
44
|
+
self.process.stdin.write(line + "\n")
|
|
45
|
+
self.process.stdin.flush()
|
|
46
|
+
|
|
47
|
+
def receive(self, timeout: float = 10.0) -> dict[str, Any]:
|
|
48
|
+
"""
|
|
49
|
+
Read a single JSON message from stdout, blocking up to `timeout` seconds.
|
|
50
|
+
"""
|
|
51
|
+
start = time.time()
|
|
52
|
+
buffer = ""
|
|
53
|
+
|
|
54
|
+
while True:
|
|
55
|
+
# Check timeout
|
|
56
|
+
if time.time() - start > timeout:
|
|
57
|
+
raise TimeoutError("Timed out waiting for server response.")
|
|
58
|
+
|
|
59
|
+
# Try to read a single character (non-blocking when no data)
|
|
60
|
+
char = self.process.stdout.read(1)
|
|
61
|
+
if char:
|
|
62
|
+
buffer += char
|
|
63
|
+
if char == "\n": # End of message line
|
|
64
|
+
line = buffer.strip()
|
|
65
|
+
if not line:
|
|
66
|
+
buffer = ""
|
|
67
|
+
continue
|
|
68
|
+
try:
|
|
69
|
+
return json.loads(line)
|
|
70
|
+
except json.JSONDecodeError as e:
|
|
71
|
+
raise RuntimeError(f"Invalid JSON line: {line!r}") from e
|
|
72
|
+
else:
|
|
73
|
+
# Sleep a bit to avoid busy waiting
|
|
74
|
+
time.sleep(0.01)
|
|
75
|
+
|
|
76
|
+
def close(self):
|
|
77
|
+
"""Gracefully terminate the subprocess."""
|
|
78
|
+
if self.process.poll() is None:
|
|
79
|
+
self.process.terminate()
|
|
80
|
+
try:
|
|
81
|
+
self.process.wait(timeout=2)
|
|
82
|
+
except subprocess.TimeoutExpired:
|
|
83
|
+
self.process.kill()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def event_stream(response):
|
|
87
|
+
response.encoding = 'utf-8'
|
|
88
|
+
for chunk in response.iter_lines(decode_unicode=True):
|
|
89
|
+
if not chunk:
|
|
90
|
+
continue
|
|
91
|
+
if chunk.startswith("data:"):
|
|
92
|
+
data_str = chunk[len("data:"):].strip()
|
|
93
|
+
try:
|
|
94
|
+
data = json.loads(data_str)
|
|
95
|
+
yield data
|
|
96
|
+
except json.JSONDecodeError:
|
|
97
|
+
print(f"[WARN] Skipping invalid JSON chunk: {data_str}")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class HttpTransport(Transport):
|
|
101
|
+
"""Simple synchronous HTTP transport for JSON-RPC 2.0."""
|
|
102
|
+
|
|
103
|
+
def __init__(self, base_url: str, headers: Optional[dict[str, str]] = None, timeout: int = 30):
|
|
104
|
+
self.base_url = base_url.rstrip("/")
|
|
105
|
+
self.headers = headers or {
|
|
106
|
+
"Content-Type": "application/json"
|
|
107
|
+
}
|
|
108
|
+
self.timeout = timeout
|
|
109
|
+
|
|
110
|
+
def send(self, message: dict[str, Any]) -> None:
|
|
111
|
+
"""Store outgoing message (used by Session._send_request)."""
|
|
112
|
+
self._last_message = message
|
|
113
|
+
|
|
114
|
+
def receive(self, timeout: Optional[float] = None) -> dict[str, Any]:
|
|
115
|
+
"""Send stored request and wait for a response."""
|
|
116
|
+
if not hasattr(self, "_last_message"):
|
|
117
|
+
raise RuntimeError("No message to send. Call send() first.")
|
|
118
|
+
|
|
119
|
+
payload = self._last_message
|
|
120
|
+
del self._last_message
|
|
121
|
+
|
|
122
|
+
try:
|
|
123
|
+
resp = requests.post(
|
|
124
|
+
self.base_url,
|
|
125
|
+
json=payload,
|
|
126
|
+
headers={
|
|
127
|
+
**self.headers,
|
|
128
|
+
**{"Accept": "application/json, text/event-stream"}
|
|
129
|
+
},
|
|
130
|
+
timeout=timeout or self.timeout,
|
|
131
|
+
)
|
|
132
|
+
if resp.headers.get('mcp-session-id'):
|
|
133
|
+
self.headers.setdefault('mcp-session-id', resp.headers['mcp-session-id'])
|
|
134
|
+
except Exception as e:
|
|
135
|
+
raise RuntimeError(f"HTTP request failed: {e}")
|
|
136
|
+
|
|
137
|
+
if resp.status_code != 200:
|
|
138
|
+
raise RuntimeError(f"HTTP error {resp.status_code}: {resp.text}")
|
|
139
|
+
|
|
140
|
+
try:
|
|
141
|
+
content_type = resp.headers.get("Content-Type", "")
|
|
142
|
+
# --- Handle Server-Sent Events (text/event-stream) ---
|
|
143
|
+
if "text/event-stream" in content_type:
|
|
144
|
+
return event_stream(resp)
|
|
145
|
+
# --- Handle regular JSON response ---
|
|
146
|
+
else:
|
|
147
|
+
data = resp.json()
|
|
148
|
+
except ValueError:
|
|
149
|
+
raise RuntimeError(f"Invalid JSON response: {resp.text}")
|
|
150
|
+
finally:
|
|
151
|
+
resp.close()
|
|
152
|
+
|
|
153
|
+
if not isinstance(data, dict):
|
|
154
|
+
raise RuntimeError(f"Unexpected response type: {type(data)}")
|
|
155
|
+
|
|
156
|
+
if "error" in data:
|
|
157
|
+
raise RuntimeError(f"Server error: {data['error']}")
|
|
158
|
+
|
|
159
|
+
return data.get("result", {})
|
|
160
|
+
|
|
161
|
+
def close(self) -> None:
|
|
162
|
+
"""No persistent connection to close."""
|
|
163
|
+
pass
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mcpager
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Pythonic MCP client
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: fastmcp>=2.12.4
|
|
8
|
+
Requires-Dist: langchain>=0.3.27
|
|
9
|
+
Requires-Dist: langchain-openai>=0.3.35
|
|
10
|
+
Requires-Dist: langgraph>=0.6.10
|
|
11
|
+
Requires-Dist: python-dotenv>=1.1.1
|
|
12
|
+
|
|
13
|
+
## MCPager
|
|
14
|
+
|
|
15
|
+
Quickstart:
|
|
16
|
+
```
|
|
17
|
+
uv pip install -e .
|
|
18
|
+
cd examples
|
|
19
|
+
uv run basic_example.py
|
|
20
|
+
```
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
mcpager/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
mcpager/adapters/__init__.py,sha256=pvm_7Xv47OJ4PMXfIqbvCrUAZzZDOGCAE-eB7g2NzAc,115
|
|
3
|
+
mcpager/adapters/backends.py,sha256=ttv7f4OcOerPf_YzHf0RFbfH6VsmmXp5rUVNfZ6XVWQ,3066
|
|
4
|
+
mcpager/client/__init__.py,sha256=Evqn4fyYQ1ylQFqznm8-pS-QKuSKbwNII6gUQcw44eI,235
|
|
5
|
+
mcpager/client/client.py,sha256=qu-0K8moGbn-PqFo2X2voXBK1Q9CJcgvLN6tMz8uEjI,669
|
|
6
|
+
mcpager/client/session.py,sha256=2sTx8NoF5sET7sI-C0gu8cMChFMKOR-rwfUHg9Ken-Y,4123
|
|
7
|
+
mcpager/client/transport.py,sha256=AY5jq9A_uTFDUad8Ee5YWI3grYSAwAlueO4GgNEdWjE,5507
|
|
8
|
+
mcpager-0.1.0.dist-info/METADATA,sha256=Livz3QMwdkTyWoETBDKD5sQQFPibU9W73E5SzfwH5KE,426
|
|
9
|
+
mcpager-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
10
|
+
mcpager-0.1.0.dist-info/top_level.txt,sha256=sVTRGLJ8r7f9LkLnXiS8GHMxb42d2KiBOnRuKqORL8M,8
|
|
11
|
+
mcpager-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mcpager
|