-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
253 lines (225 loc) · 8.89 KB
/
client.py
File metadata and controls
253 lines (225 loc) · 8.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
"""MCP client for the GEE server (server.py via stdio)."""
from __future__ import annotations
import json
import os
import sys
from types import TracebackType
from typing import Any
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
PYTHON_BIN = sys.executable
SERVER_MODULE = "gee_mcp.server"
class GEEToolError(RuntimeError):
"""Raised when the MCP server returns an error for a tool call."""
class GEEMCPClient:
"""Async context manager wrapping an MCP stdio session.
Usage::
async with GEEMCPClient() as gee:
meta = await gee.get_metadata("MODIS_061_MOD10A1")
"""
def __init__(self) -> None:
self._session: ClientSession | None = None
self._cm_stdio: object = None
self._cm_session: object = None
async def __aenter__(self) -> GEEMCPClient:
# Prepend the local ``src/`` directory to PYTHONPATH so the
# example client can launch the server straight from a
# checkout (without installing the package first).
repo_src = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "src"
)
existing = os.environ.get("PYTHONPATH", "")
pythonpath = (
f"{repo_src}{os.pathsep}{existing}" if existing else repo_src
)
params = StdioServerParameters(
command=PYTHON_BIN,
args=["-m", SERVER_MODULE],
env={**os.environ, "PYTHONPATH": pythonpath},
)
self._cm_stdio = stdio_client(params)
read, write = await self._cm_stdio.__aenter__() # type: ignore[union-attr]
self._cm_session = ClientSession(read, write)
self._session = await self._cm_session.__aenter__() # type: ignore[union-attr]
await self._session.initialize()
return self
async def __aexit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
if self._cm_session is not None:
await self._cm_session.__aexit__( # type: ignore[union-attr]
exc_type, exc_val, exc_tb
)
if self._cm_stdio is not None:
await self._cm_stdio.__aexit__( # type: ignore[union-attr]
exc_type, exc_val, exc_tb
)
self._session = None
@staticmethod
def _parse_result(result: Any) -> Any:
"""Extract JSON from a tool result, raising on server errors."""
text = result.content[0].text
if result.isError:
raise GEEToolError(text)
try:
return json.loads(text)
except:
return text
async def test(self) -> dict:
return {"test": "uno"}
async def get_metadata(self, catalog_id: str) -> dict:
"""Call ``get_dataset_metadata`` on the MCP server."""
assert self._session is not None, "Use as async context manager"
result = await self._session.call_tool(
"get_dataset_metadata",
{"catalog_id": catalog_id},
)
return json.loads(result.content[0].text) # type: ignore[union-attr]
async def check_availability(
self,
dataset_id: str,
start_date: str,
end_date: str,
**kwargs: object,
) -> dict:
"""Call ``check_imagery_availability`` on the MCP server."""
assert self._session is not None, "Use as async context manager"
args: dict[str, object] = {
"dataset_id": dataset_id,
"start_date": start_date,
"end_date": end_date,
**kwargs,
}
result = await self._session.call_tool(
"check_imagery_availability",
args,
)
return json.loads(result.content[0].text) # type: ignore[union-attr]
async def list_datasets(self) -> dict:
"""Call ``get_dataset_metadata`` on the MCP server."""
assert self._session is not None, "Use as async context manager"
result = await self._session.call_tool("list_datasets", {})
return self._parse_result(result)
async def generate_python_from_question(
self,
question: str,
gee_datasets: list[dict] = None,
fix_code: bool = True,
) -> dict:
"""Call ``generate_python_from_question`` on the MCP server."""
assert self._session is not None, "Use as async context manager"
result = await self._session.call_tool(
"generate_python_from_question",
{
"question": question,
"gee_datasets": gee_datasets,
"fix_code": fix_code,
},
)
return self._parse_result(result)
async def generate_abstract_graph_from_question(
self, question: str, gee_datasets: list[dict] = None
) -> dict:
"""Call ``generate_abstract_graph_from_question`` on the MCP server."""
assert self._session is not None, "Use as async context manager"
result = await self._session.call_tool(
"generate_abstract_graph_from_question",
{"question": question, "gee_datasets": gee_datasets},
)
return self._parse_result(result)
async def generate_python_from_reasoning_steps(
self,
question: str,
reasoning_steps: str,
gee_datasets: list[dict] = None,
fix_code: bool = True,
) -> dict:
"""Call ``generate_python_from_reasoning_steps`` on the MCP server."""
assert self._session is not None, "Use as async context manager"
result = await self._session.call_tool(
"generate_python_from_reasoning_steps",
{
"question": question,
"gee_datasets": gee_datasets,
"reasoning_steps": reasoning_steps,
"fix_code": fix_code,
},
)
return self._parse_result(result)
async def generate_python_from_abstract_graph(
self,
question: str,
abstract_graph: str,
gee_datasets: list = None,
fix_code: bool = True,
) -> dict:
"""Call ``generate_python_from_abstract_graph`` on the MCP server."""
assert self._session is not None, "Use as async context manager"
result = await self._session.call_tool(
"generate_python_from_abstract_graph",
{
"question": question,
"gee_datasets": gee_datasets,
"abstract_graph": abstract_graph,
"fix_code": fix_code,
},
)
return self._parse_result(result)
async def execute_gee_python(self, code: str) -> dict:
"""Call ``execute_gee_python`` on the MCP server."""
assert self._session is not None, "Use as async context manager"
result = await self._session.call_tool(
"execute_gee_python", {"code": code}
)
return self._parse_result(result)
async def extract_factuality_issues(
self, question: str, python_code: str
) -> dict:
"""Call ``extract_factuality_issues`` on the MCP server."""
assert self._session is not None, "Use as async context manager"
result = await self._session.call_tool(
"extract_factuality_issues",
{"question": question, "python_code": python_code},
)
return self._parse_result(result)
async def get_datasets_locations_and_periods(
self, question: str, gee_datasets: list[dict]
) -> dict:
"""Call ``get_datasets_locations_and_periods`` on the MCP server."""
assert self._session is not None, "Use as async context manager"
result = await self._session.call_tool(
"get_datasets_locations_and_periods",
{"question": question, "gee_datasets": gee_datasets},
)
return self._parse_result(result)
async def identify_sensible_variables(
self, question: str, python_code: str, baseline_answer: str
) -> list[dict]:
"""Call ``identify_sensible_variables`` on the MCP server."""
assert self._session is not None, "Use as async context manager"
result = await self._session.call_tool(
"identify_sensible_variables",
{
"question": question,
"python_code": python_code,
"baseline_answer": baseline_answer,
},
)
return self._parse_result(result)
async def sensitivity_analysis(
self, question: str, python_code: str, baseline_answer: str
) -> list[dict]:
"""Call ``sensitivity_analysis`` on the MCP server."""
assert self._session is not None, "Use as async context manager"
result = await self._session.call_tool(
"sensitivity_analysis",
{
"question": question,
"python_code": python_code,
"baseline_answer": baseline_answer,
},
)
return self._parse_result(result)