avsolatorio commited on
Commit
035087a
·
1 Parent(s): 62a92d3

Refactor data

Browse files

Signed-off-by: Aivin V. Solatorio <avsolatorio@gmail.com>

Files changed (2) hide show
  1. mcp_client.py +10 -5
  2. wdi_mcp_server.py +11 -134
mcp_client.py CHANGED
@@ -162,8 +162,11 @@ class MCPClientWrapper:
162
  result_messages = []
163
 
164
  print(response.content)
 
 
 
 
165
 
166
- for content in response.content:
167
  if content.type == "text":
168
  result_messages.append({"role": "assistant", "content": content.text})
169
  claude_messages.append({"role": "assistant", "content": content.text})
@@ -278,10 +281,12 @@ class MCPClientWrapper:
278
 
279
  print("next_response", next_response.content)
280
 
281
- if next_response.content and next_response.content[0].type == "text":
282
- result_messages.append(
283
- {"role": "assistant", "content": next_response.content[0].text}
284
- )
 
 
285
 
286
  return result_messages
287
 
 
162
  result_messages = []
163
 
164
  print(response.content)
165
+ contents = response.content
166
+
167
+ while len(contents) > 0:
168
+ content = contents.pop(0)
169
 
 
170
  if content.type == "text":
171
  result_messages.append({"role": "assistant", "content": content.text})
172
  claude_messages.append({"role": "assistant", "content": content.text})
 
281
 
282
  print("next_response", next_response.content)
283
 
284
+ contents.extend(next_response.content)
285
+
286
+ # if next_response.content and next_response.content[0].type == "text":
287
+ # result_messages.append(
288
+ # {"role": "assistant", "content": next_response.content[0].text}
289
+ # )
290
 
291
  return result_messages
292
 
wdi_mcp_server.py CHANGED
@@ -1,87 +1,18 @@
1
  from mcp.server.fastmcp import FastMCP
2
- import json
3
-
4
- # import sys
5
- # import io
6
- # import time
7
- # import numpy as np
8
- import pandas as pd
9
- import torch
10
- import httpx
11
-
12
-
13
  from typing import Optional, Any
14
- from sentence_transformers import SentenceTransformer
15
-
16
- # from gradio_client import Client
17
- from pydantic import BaseModel, Field
18
-
19
-
20
- def get_best_torch_device():
21
- if torch.cuda.is_available():
22
- return torch.device("cuda")
23
- elif getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
24
- return torch.device("mps")
25
- else:
26
- return torch.device("cpu")
27
-
28
-
29
- device = get_best_torch_device()
30
 
31
  # sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
32
  # sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")
33
 
34
 
35
- mcp = FastMCP("huggingface_spaces_wdi_data")
36
-
37
-
38
- # Load the basic WDI metadata and vectors.
39
- wdi_data_vec_fpath = (
40
- "./data/avsolatorio__GIST-small-Embedding-v0__005__indicator_embeddings.json"
41
- )
42
- df = pd.read_json(wdi_data_vec_fpath)
43
-
44
- # Make it easy to index based on the idno
45
- df.index = df["idno"]
46
-
47
- # Change the IDS naming to metadata standard
48
- df.rename(columns={"title": "name", "text": "definition"}, inplace=True)
49
-
50
- # Extract the vectors into a torch.tensor
51
- vectors = torch.Tensor(df["embedding"]).to(device)
52
-
53
-
54
- # Load the embedding model
55
- model_name = "/".join(wdi_data_vec_fpath.split("/")[-1].split("__")[:2])
56
- embedding_model = SentenceTransformer(model_name, device=device)
57
-
58
-
59
- def get_top_k(query: str, top_k: int = 10, fields: list[str] | None = None):
60
- if fields is None:
61
- fields = ["idno"]
62
-
63
- # Convert the query to a search vector
64
- search_vec = embedding_model.encode([query], convert_to_tensor=True) @ vectors.T
65
-
66
- # Sort by descending similarity score
67
- idx = search_vec.argsort(descending=True)[0][:top_k].tolist()
68
-
69
- return df.iloc[idx][fields].to_dict("records")
70
-
71
-
72
- class SearchOutput(BaseModel):
73
- idno: str = Field(..., description="The unique identifier of the indicator.")
74
- name: str = Field(..., description="The name of the indicator.")
75
-
76
-
77
- class DetailedOutput(SearchOutput):
78
- definition: str | None = Field(None, description="The indicator definition.")
79
 
80
 
81
  @mcp.tool()
82
  async def search_relevant_indicators(
83
  query: str, top_k: int = 1
84
- ) -> dict[str, list[SearchOutput] | str]:
85
  """Search for a shortlist of relevant indicators from the World Development Indicators (WDI) given the query. The search ranking may not be optimal, so the LLM may use this as shortlist and pick the most relevant from the list (if any).
86
 
87
  Args:
@@ -92,17 +23,11 @@ async def search_relevant_indicators(
92
  A dictionary with keys `indicators` and `note`. The `indicators` key contains a list of indicator objects with keys indicator code/idno and name. The `note` key contains a note about the search.
93
  """
94
 
95
- return {
96
- "indicators": [
97
- SearchOutput(**out)
98
- for out in get_top_k(query=query, top_k=top_k, fields=["idno", "name"])
99
- ],
100
- "note": "IMPORTANT: Let the user know that the search is not exhaustive. The search is based on the semantic similarity of the query to the indicator definitions. It may not be optimal and the LLM may use this as shortlist and pick the most relevant from the list (if any).",
101
- }
102
 
103
 
104
  @mcp.tool()
105
- async def indicator_info(indicator_ids: list[str]) -> list[DetailedOutput]:
106
  """Provides definition information for the given indicator id (idno).
107
 
108
  Args:
@@ -111,15 +36,8 @@ async def indicator_info(indicator_ids: list[str]) -> list[DetailedOutput]:
111
  Returns:
112
  List of objects with keys indicator code/idno, name, and definition.
113
  """
114
- if isinstance(indicator_ids, str):
115
- indicator_ids = [indicator_ids]
116
 
117
- return [
118
- DetailedOutput(**out)
119
- for out in df.loc[indicator_ids][
120
- ["idno", "name", "definition", "time_coverage", "geographic_coverage"]
121
- ].to_dict("records")
122
- ]
123
 
124
 
125
  @mcp.tool()
@@ -140,54 +58,13 @@ async def get_wdi_data(
140
  Returns:
141
  A dictionary with keys `data` and `note`. The `data` key contains a list of indicator data entries requested. The `note` key contains a note about the data returned.
142
  """
143
- MAX_INFO = 20
144
- note = ""
145
-
146
- if isinstance(country_codes, str):
147
- country_codes = [country_codes]
148
 
149
- country_code = ";".join(country_codes)
150
- base_url = (
151
- f"https://api.worldbank.org/v2/country/{country_code}/indicator/{indicator_id}"
 
 
152
  )
153
- params = {"format": "json", "date": date, "per_page": per_page or 100, "page": 1}
154
-
155
- with open("mcp_server.log", "a+") as log:
156
- log.write(json.dumps(dict(base_url=base_url, params=params)) + "\n")
157
-
158
- with httpx.Client(timeout=30.0) as client:
159
- all_data = []
160
- while True:
161
- response = client.get(base_url, params=params)
162
- if response.status_code != 200:
163
- note = f"ERROR: Failed to fetch data: HTTP {response.status_code}"
164
- break
165
-
166
- json_response = response.json()
167
-
168
- if not isinstance(json_response, list) or len(json_response) < 2:
169
- note = "ERROR: The API response is invalid or empty."
170
- break
171
-
172
- metadata, data_page = json_response
173
- all_data.extend(data_page)
174
-
175
- if len(all_data) >= MAX_INFO:
176
- note = f"IMPORTANT: Let the user know that the data is truncated to the first {MAX_INFO} entries."
177
- break
178
-
179
- if params["page"] >= metadata.get("pages", 1):
180
- break
181
-
182
- params["page"] += 1
183
-
184
- with open("mcp_server.log", "a+") as log:
185
- log.write(json.dumps(dict(all_data=all_data)) + "\n")
186
-
187
- return dict(
188
- data=all_data,
189
- note=note,
190
- )
191
 
192
 
193
  if __name__ == "__main__":
 
1
  from mcp.server.fastmcp import FastMCP
 
 
 
 
 
 
 
 
 
 
 
2
  from typing import Optional, Any
3
+ import services
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  # sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
6
  # sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8", errors="replace")
7
 
8
 
9
+ mcp = FastMCP("wdi_data_mcp")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
 
12
  @mcp.tool()
13
  async def search_relevant_indicators(
14
  query: str, top_k: int = 1
15
+ ) -> dict[str, list[services.SearchOutput] | str]:
16
  """Search for a shortlist of relevant indicators from the World Development Indicators (WDI) given the query. The search ranking may not be optimal, so the LLM may use this as shortlist and pick the most relevant from the list (if any).
17
 
18
  Args:
 
23
  A dictionary with keys `indicators` and `note`. The `indicators` key contains a list of indicator objects with keys indicator code/idno and name. The `note` key contains a note about the search.
24
  """
25
 
26
+ return services.search_relevant_indicators(query=query, top_k=top_k)
 
 
 
 
 
 
27
 
28
 
29
  @mcp.tool()
30
+ async def indicator_info(indicator_ids: list[str]) -> list[services.DetailedOutput]:
31
  """Provides definition information for the given indicator id (idno).
32
 
33
  Args:
 
36
  Returns:
37
  List of objects with keys indicator code/idno, name, and definition.
38
  """
 
 
39
 
40
+ return services.indicator_info(indicator_ids=indicator_ids)
 
 
 
 
 
41
 
42
 
43
  @mcp.tool()
 
58
  Returns:
59
  A dictionary with keys `data` and `note`. The `data` key contains a list of indicator data entries requested. The `note` key contains a note about the data returned.
60
  """
 
 
 
 
 
61
 
62
+ return services.get_wdi_data(
63
+ indicator_id=indicator_id,
64
+ country_codes=country_codes,
65
+ date=date,
66
+ per_page=per_page,
67
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
 
70
  if __name__ == "__main__":