codemode-mcp 0.2.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.
@@ -0,0 +1,332 @@
1
+ """Tool catalog: turns MCP tool JSON schemas into compact Python stubs and searches them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import keyword
6
+ import math
7
+ import re
8
+ from collections import Counter
9
+ from dataclasses import dataclass, field
10
+ from typing import Any
11
+
12
+
13
+ def estimate_tokens(text: str) -> int:
14
+ """Cheap, model-agnostic token estimate (~4 chars per token)."""
15
+ return max(1, math.ceil(len(text) / 4))
16
+
17
+
18
+ def to_identifier(name: str) -> str:
19
+ ident = re.sub(r"\W", "_", name)
20
+ if not ident or ident[0].isdigit():
21
+ ident = "_" + ident
22
+ if keyword.iskeyword(ident) or ident in ("print", "json", "ToolError"):
23
+ ident += "_"
24
+ return ident
25
+
26
+
27
+ def _resolve_ref(schema: dict[str, Any], root: dict[str, Any]) -> dict[str, Any]:
28
+ ref = schema.get("$ref")
29
+ if not isinstance(ref, str) or not ref.startswith("#/"):
30
+ return schema
31
+ node: Any = root
32
+ for part in ref[2:].split("/"):
33
+ if not isinstance(node, dict) or part not in node:
34
+ return {}
35
+ node = node[part]
36
+ return node if isinstance(node, dict) else {}
37
+
38
+
39
+ def type_hint(schema: Any, root: dict[str, Any] | None = None, depth: int = 0) -> str:
40
+ """Render a JSON schema as a compact, Python-flavoured type expression.
41
+
42
+ Objects with known properties are shown inline as ``{key: type, opt?: type}`` so the
43
+ model knows their shape without a separate lookup.
44
+ """
45
+ if not isinstance(schema, dict) or depth > 4:
46
+ return "Any"
47
+ root = root if root is not None else schema
48
+ if "$ref" in schema:
49
+ return type_hint(_resolve_ref(schema, root), root, depth + 1)
50
+ if "const" in schema:
51
+ return f"Literal[{schema['const']!r}]"
52
+ if "enum" in schema and isinstance(schema["enum"], list):
53
+ values = schema["enum"][:12]
54
+ more = ", ..." if len(schema["enum"]) > 12 else ""
55
+ return "Literal[" + ", ".join(repr(v) for v in values) + more + "]"
56
+ for key in ("anyOf", "oneOf"):
57
+ if isinstance(schema.get(key), list):
58
+ parts = _dedupe(type_hint(s, root, depth + 1) for s in schema[key])
59
+ return " | ".join(parts) if parts else "Any"
60
+ if isinstance(schema.get("allOf"), list) and len(schema["allOf"]) == 1:
61
+ return type_hint(schema["allOf"][0], root, depth + 1)
62
+
63
+ t = schema.get("type")
64
+ if isinstance(t, list):
65
+ return " | ".join(_dedupe(type_hint({**schema, "type": x}, root, depth) for x in t))
66
+ simple = {"string": "str", "integer": "int", "number": "float", "boolean": "bool", "null": "None"}
67
+ if t in simple:
68
+ return simple[t]
69
+ if t == "array" or "items" in schema:
70
+ return f"list[{type_hint(schema.get('items'), root, depth + 1)}]"
71
+ if t == "object" or "properties" in schema:
72
+ props = schema.get("properties")
73
+ if isinstance(props, dict) and props and depth < 3:
74
+ required = set(schema.get("required") or [])
75
+ inner = ", ".join(
76
+ f"{k}{'' if k in required else '?'}: {type_hint(v, root, depth + 1)}"
77
+ for k, v in list(props.items())[:25]
78
+ )
79
+ if len(props) > 25:
80
+ inner += ", ..."
81
+ return "{" + inner + "}"
82
+ extra = schema.get("additionalProperties")
83
+ if isinstance(extra, dict):
84
+ return f"dict[str, {type_hint(extra, root, depth + 1)}]"
85
+ return "dict"
86
+ return "Any"
87
+
88
+
89
+ def _dedupe(items: Any) -> list[str]:
90
+ out: list[str] = []
91
+ for item in items:
92
+ if item not in out:
93
+ out.append(item)
94
+ return out
95
+
96
+
97
+ def _shorten(text: str, limit: int) -> str:
98
+ text = " ".join(text.split())
99
+ return text if len(text) <= limit else text[: limit - 1].rstrip() + "…"
100
+
101
+
102
+ def _nullable(type_str: str) -> bool:
103
+ return type_str == "Any" or "None" in type_str.split(" | ")
104
+
105
+
106
+ def is_wrapped_result(schema: dict[str, Any] | None) -> bool:
107
+ """MCP SDKs wrap non-object return values as ``{"result": value}``; detect that envelope."""
108
+ if not isinstance(schema, dict):
109
+ return False
110
+ props = schema.get("properties")
111
+ return isinstance(props, dict) and list(props) == ["result"] and schema.get("required") == ["result"]
112
+
113
+
114
+ _NO_DEFAULT: Any = object()
115
+
116
+
117
+ def _default_repr(value: Any) -> str:
118
+ text = repr(value)
119
+ return text if len(text) <= 40 else "..."
120
+
121
+
122
+ @dataclass
123
+ class Param:
124
+ name: str
125
+ """Original JSON property name sent to the server."""
126
+ py_name: str
127
+ type: str
128
+ required: bool
129
+ description: str = ""
130
+ default: Any = _NO_DEFAULT
131
+
132
+
133
+ @dataclass
134
+ class ToolSpec:
135
+ server: str
136
+ name: str
137
+ py_server: str
138
+ py_name: str
139
+ description: str
140
+ input_schema: dict[str, Any]
141
+ output_schema: dict[str, Any] | None = None
142
+ params: list[Param] = field(default_factory=list)
143
+
144
+ @classmethod
145
+ def from_mcp(
146
+ cls,
147
+ server: str,
148
+ py_server: str,
149
+ py_name: str,
150
+ name: str,
151
+ description: str | None,
152
+ input_schema: dict[str, Any] | None,
153
+ output_schema: dict[str, Any] | None,
154
+ ) -> ToolSpec:
155
+ schema = input_schema or {}
156
+ props = schema.get("properties") if isinstance(schema.get("properties"), dict) else {}
157
+ required = set(schema.get("required") or [])
158
+ params: list[Param] = []
159
+ used: set[str] = set()
160
+ for pname, pschema in props.items():
161
+ py = to_identifier(pname)
162
+ while py in used:
163
+ py += "_"
164
+ used.add(py)
165
+ pschema = pschema if isinstance(pschema, dict) else {}
166
+ params.append(
167
+ Param(
168
+ name=pname,
169
+ py_name=py,
170
+ type=type_hint(pschema, schema),
171
+ required=pname in required,
172
+ description=str(pschema.get("description") or ""),
173
+ default=pschema["default"]
174
+ if "default" in pschema and pschema["default"] is not None
175
+ else _NO_DEFAULT,
176
+ )
177
+ )
178
+ params.sort(key=lambda p: not p.required)
179
+ if is_wrapped_result(output_schema):
180
+ assert output_schema is not None
181
+ inner = output_schema["properties"]["result"]
182
+ defs = {k: v for k, v in output_schema.items() if k in ("$defs", "definitions")}
183
+ output_schema = {**inner, **defs} if isinstance(inner, dict) else None
184
+ return cls(server, name, py_server, py_name, description or "", schema, output_schema, params)
185
+
186
+ @property
187
+ def qualified_name(self) -> str:
188
+ return f"{self.py_server}.{self.py_name}"
189
+
190
+ def signature(self) -> str:
191
+ parts = [f"{p.py_name}: {p.type}" for p in self.params if p.required]
192
+ optional = [
193
+ f"{p.py_name}: {p.type} = {_default_repr(p.default)}"
194
+ if p.default is not _NO_DEFAULT
195
+ else f"{p.py_name}: {p.type if _nullable(p.type) else p.type + ' | None'} = None"
196
+ for p in self.params
197
+ if not p.required
198
+ ]
199
+ if optional:
200
+ parts.append("*")
201
+ parts.extend(optional)
202
+ ret = type_hint(self.output_schema) if self.output_schema else "Any"
203
+ return f"async def {self.py_name}({', '.join(parts)}) -> {ret}"
204
+
205
+ def render(self, max_description_chars: int = 600, indent: str = " ") -> str:
206
+ """Render as a Python stub (method of the server namespace class)."""
207
+ lines = [f"{indent}{self.signature()}:"]
208
+ doc: list[str] = []
209
+ if self.description:
210
+ doc.append(_shorten(self.description, max_description_chars))
211
+ described = [p for p in self.params if p.description]
212
+ if described:
213
+ doc.append("Args:")
214
+ doc.extend(f" {p.py_name}: {_shorten(p.description, 200)}" for p in described)
215
+ if not doc:
216
+ lines.append(f"{indent} ...")
217
+ elif len(doc) == 1:
218
+ lines.append(f'{indent} """{doc[0]}"""')
219
+ else:
220
+ body = "\n".join(f"{indent} {d}" for d in doc)
221
+ lines.append(f'{indent} """{body.strip()}\n{indent} """')
222
+ return "\n".join(lines)
223
+
224
+ def sandbox_spec(self) -> dict[str, Any]:
225
+ return {
226
+ "server": self.server,
227
+ "tool": self.name,
228
+ "py_server": self.py_server,
229
+ "py_name": self.py_name,
230
+ "params": [[p.py_name, p.name, p.required] for p in self.params],
231
+ "doc": _shorten(self.description, 300),
232
+ }
233
+
234
+
235
+ _TOKEN_RE = re.compile(r"[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+")
236
+
237
+
238
+ def _terms(text: str) -> list[str]:
239
+ out = []
240
+ for raw in _TOKEN_RE.findall(text):
241
+ t = raw.lower()
242
+ if len(t) > 3 and t.endswith("ies"):
243
+ t = t[:-3] + "y"
244
+ elif len(t) > 3 and t.endswith("s") and not t.endswith("ss"):
245
+ t = t[:-1]
246
+ out.append(t)
247
+ return out
248
+
249
+
250
+ class Catalog:
251
+ """All upstream tools, addressable as ``<server>.<tool>`` inside the sandbox."""
252
+
253
+ def __init__(self, tools: list[ToolSpec], max_description_chars: int = 600):
254
+ self.tools = tools
255
+ self.max_description_chars = max_description_chars
256
+ self._by_qualified = {t.qualified_name: t for t in tools}
257
+ self._docs: list[Counter[str]] = []
258
+ df: Counter[str] = Counter()
259
+ for t in tools:
260
+ doc: Counter[str] = Counter()
261
+ for term in _terms(t.name):
262
+ doc[term] += 4
263
+ for term in _terms(t.server):
264
+ doc[term] += 2
265
+ for term in _terms(t.description):
266
+ doc[term] += 1
267
+ for p in t.params:
268
+ for term in _terms(p.name):
269
+ doc[term] += 1
270
+ self._docs.append(doc)
271
+ df.update(doc.keys())
272
+ n = max(1, len(tools))
273
+ self._idf = {term: math.log(1 + (n - c + 0.5) / (c + 0.5)) for term, c in df.items()}
274
+
275
+ def __len__(self) -> int:
276
+ return len(self.tools)
277
+
278
+ def get(self, qualified_name: str) -> ToolSpec | None:
279
+ return self._by_qualified.get(qualified_name)
280
+
281
+ @property
282
+ def servers(self) -> list[str]:
283
+ return _dedupe(t.py_server for t in self.tools)
284
+
285
+ def search(self, query: str, limit: int = 8) -> list[ToolSpec]:
286
+ exact = self.get(query.strip())
287
+ if exact:
288
+ return [exact]
289
+ q_terms = _terms(query)
290
+ if not q_terms:
291
+ return self.tools[:limit]
292
+ scored = []
293
+ for tool, doc in zip(self.tools, self._docs, strict=True):
294
+ score = 0.0
295
+ for term in q_terms:
296
+ tf = doc.get(term, 0)
297
+ if not tf:
298
+ # Partial match (e.g. "repo" vs "repository").
299
+ tf = 0.5 * sum(
300
+ v
301
+ for k, v in doc.items()
302
+ if len(term) >= 3 and (k.startswith(term) or term.startswith(k) and len(k) >= 3)
303
+ )
304
+ if tf:
305
+ score += self._idf.get(term, 1.0) * (tf * 2.2) / (tf + 1.2)
306
+ if score > 0:
307
+ scored.append((score, tool))
308
+ scored.sort(key=lambda x: -x[0])
309
+ return [t for _, t in scored[:limit]]
310
+
311
+ def render(self, tools: list[ToolSpec] | None = None) -> str:
312
+ """Render tools grouped by server as Python class stubs."""
313
+ tools = self.tools if tools is None else tools
314
+ blocks = []
315
+ for server in _dedupe(t.py_server for t in tools):
316
+ members = [t.render(self.max_description_chars) for t in tools if t.py_server == server]
317
+ blocks.append(f"class {server}:\n" + "\n\n".join(members))
318
+ return "\n\n".join(blocks)
319
+
320
+ def render_names(self) -> str:
321
+ lines = []
322
+ for server in self.servers:
323
+ names = [t.py_name for t in self.tools if t.py_server == server]
324
+ lines.append(f"{server}: {', '.join(names)}")
325
+ return "\n".join(lines)
326
+
327
+ def render_servers(self) -> str:
328
+ counts = Counter(t.py_server for t in self.tools)
329
+ return ", ".join(f"{s} ({counts[s]} tools)" for s in self.servers)
330
+
331
+ def sandbox_specs(self) -> list[dict[str, Any]]:
332
+ return [t.sandbox_spec() for t in self.tools]