langchain-protogrid 0.1.0__tar.gz

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,7 @@
1
+ node_modules/
2
+ dist/
3
+ .venv/
4
+ __pycache__/
5
+ *.tsbuildinfo
6
+ pnpm-lock.yaml
7
+ .mcp-tokens.json
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 protogrid contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.5
2
+ Name: langchain-protogrid
3
+ Version: 0.1.0
4
+ Summary: LangChain tools from the protogrid MCP registry: find MCP servers by what they do, gate them on your rules, and load the tools of the ones that pass.
5
+ Project-URL: Homepage, https://protogrid.dev
6
+ Project-URL: Documentation, https://docs.protogrid.dev/sdk/langchain/
7
+ Project-URL: Repository, https://github.com/protogrid-dev/sdk
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: agents,langchain,mcp,model-context-protocol,registry,tools
11
+ Requires-Python: >=3.11
12
+ Requires-Dist: langchain-core>=1.8
13
+ Requires-Dist: langchain[mcp]>=1.5
14
+ Requires-Dist: protogrid-sdk>=0.4.4
15
+ Description-Content-Type: text/markdown
16
+
17
+ # langchain-protogrid
18
+
19
+ LangChain tools from the [protogrid](https://protogrid.dev) MCP registry: find MCP servers by what they do, check them against your rules, and give your agent the tools of the ones that pass.
20
+
21
+ ```bash
22
+ pip install langchain-protogrid
23
+ ```
24
+
25
+ ```python
26
+ from langchain.agents import create_agent
27
+ from langchain_protogrid import Rules, load_tools
28
+
29
+ tools = await load_tools(
30
+ "send an email",
31
+ rules=Rules(min_quality=70), # also refuses hidden text, tool poisoning and known vulnerabilities
32
+ secrets={"api_key": os.environ["MAIL_API_KEY"]},
33
+ )
34
+ agent = create_agent(model="anthropic:claude-sonnet-5", tools=tools)
35
+ ```
36
+
37
+ - `load_tools` tries the best search results (or the `servers` you name) in order. Each goes through protogrid's gate with your rules; one that passes is connected to directly, with no proxy, and its tools come back named `<server key>_<tool>`.
38
+ - Secrets fill the `${NAME}` placeholders of the server's connection in your process; they are never sent to protogrid. A server needing a secret you did not give is passed over.
39
+ - Rules are yours, not the model's. The defaults refuse tools that hide text from people, tools holding instructions aimed at the model, and servers with a known vulnerability in their dependencies. Local packages are never loaded.
40
+ - `pins={"io.github.owner/server": "<tools_hash>"}` passes over a server whose checked tools changed since you reviewed them; `strict_tools=True` also compares the tools the server lists right now with the ones protogrid checked.
41
+ - `ProtogridSearch()` and `ProtogridGate(rules=...)` let the agent look for servers and check one itself.
42
+
43
+ Python 3.11 or later. MCP support comes from `langchain[mcp]` (`langchain.mcp`, in beta upstream). Full guide: [docs.protogrid.dev/sdk/langchain](https://docs.protogrid.dev/sdk/langchain/).
44
+
45
+ MIT licensed.
@@ -0,0 +1,29 @@
1
+ # langchain-protogrid
2
+
3
+ LangChain tools from the [protogrid](https://protogrid.dev) MCP registry: find MCP servers by what they do, check them against your rules, and give your agent the tools of the ones that pass.
4
+
5
+ ```bash
6
+ pip install langchain-protogrid
7
+ ```
8
+
9
+ ```python
10
+ from langchain.agents import create_agent
11
+ from langchain_protogrid import Rules, load_tools
12
+
13
+ tools = await load_tools(
14
+ "send an email",
15
+ rules=Rules(min_quality=70), # also refuses hidden text, tool poisoning and known vulnerabilities
16
+ secrets={"api_key": os.environ["MAIL_API_KEY"]},
17
+ )
18
+ agent = create_agent(model="anthropic:claude-sonnet-5", tools=tools)
19
+ ```
20
+
21
+ - `load_tools` tries the best search results (or the `servers` you name) in order. Each goes through protogrid's gate with your rules; one that passes is connected to directly, with no proxy, and its tools come back named `<server key>_<tool>`.
22
+ - Secrets fill the `${NAME}` placeholders of the server's connection in your process; they are never sent to protogrid. A server needing a secret you did not give is passed over.
23
+ - Rules are yours, not the model's. The defaults refuse tools that hide text from people, tools holding instructions aimed at the model, and servers with a known vulnerability in their dependencies. Local packages are never loaded.
24
+ - `pins={"io.github.owner/server": "<tools_hash>"}` passes over a server whose checked tools changed since you reviewed them; `strict_tools=True` also compares the tools the server lists right now with the ones protogrid checked.
25
+ - `ProtogridSearch()` and `ProtogridGate(rules=...)` let the agent look for servers and check one itself.
26
+
27
+ Python 3.11 or later. MCP support comes from `langchain[mcp]` (`langchain.mcp`, in beta upstream). Full guide: [docs.protogrid.dev/sdk/langchain](https://docs.protogrid.dev/sdk/langchain/).
28
+
29
+ MIT licensed.
@@ -0,0 +1,37 @@
1
+ [project]
2
+ name = "langchain-protogrid"
3
+ version = "0.1.0"
4
+ description = "LangChain tools from the protogrid MCP registry: find MCP servers by what they do, gate them on your rules, and load the tools of the ones that pass."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ requires-python = ">=3.11"
8
+ dependencies = ["protogrid-sdk>=0.4.4", "langchain-core>=1.8", "langchain[mcp]>=1.5"]
9
+ keywords = ["langchain", "mcp", "model-context-protocol", "agents", "tools", "registry"]
10
+
11
+ [project.urls]
12
+ Homepage = "https://protogrid.dev"
13
+ Documentation = "https://docs.protogrid.dev/sdk/langchain/"
14
+ Repository = "https://github.com/protogrid-dev/sdk"
15
+
16
+ [dependency-groups]
17
+ dev = ["pytest>=8", "pytest-asyncio>=0.24", "langchain-tests>=1.1.9,<1.2", "uvicorn>=0.30"]
18
+
19
+ [build-system]
20
+ requires = ["hatchling"]
21
+ build-backend = "hatchling.build"
22
+
23
+ [tool.hatch.build.targets.wheel]
24
+ packages = ["src/langchain_protogrid"]
25
+
26
+ [tool.pytest.ini_options]
27
+ asyncio_mode = "auto"
28
+ asyncio_default_fixture_loop_scope = "function"
29
+ testpaths = ["tests"]
30
+ filterwarnings = ["ignore::langchain_core._api.beta_decorator.LangChainBetaWarning"]
31
+
32
+ [tool.uv]
33
+ package = true
34
+
35
+ [tool.uv.sources]
36
+ # The SDK next door while developing; the published wheel depends on protogrid-sdk from PyPI.
37
+ protogrid-sdk = { path = "../python", editable = true }
@@ -0,0 +1,11 @@
1
+ """LangChain tools from the protogrid MCP registry.
2
+
3
+ ``load_tools`` gives an agent the tools of MCP servers that pass your rules; ``ProtogridSearch`` and ``ProtogridGate``
4
+ let the agent look for servers and check them itself.
5
+ """
6
+ from .loader import LoadReport, NoServerLoaded, Skipped, load_tools
7
+ from .rules import DEFAULT_RULES, Rules
8
+ from .tools import ProtogridGate, ProtogridSearch
9
+ from .tools_hash import tool_hash, tool_set_hash
10
+
11
+ __all__ = ["DEFAULT_RULES", "LoadReport", "NoServerLoaded", "ProtogridGate", "ProtogridSearch", "Rules", "Skipped", "load_tools", "tool_hash", "tool_set_hash"]
@@ -0,0 +1,169 @@
1
+ """Load the tools of MCP servers that pass your rules, straight from each server (no proxy in between)."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import re
6
+ from collections.abc import Callable, Mapping, Sequence
7
+ from dataclasses import dataclass, field
8
+ from typing import Any
9
+
10
+ from fastmcp.client import Client
11
+ from fastmcp.client.transports import SSETransport, StreamableHttpTransport
12
+ from langchain.mcp import MCPAdapter, as_langchain_tool
13
+ from langchain_core.tools import BaseTool
14
+ from protogrid import AsyncProtogridClient, ProtogridError
15
+ from protogrid.connect import resolve_entry
16
+ from protogrid.secrets import placeholders_in
17
+
18
+ from .rules import DEFAULT_RULES, Rules
19
+ from .tools_hash import tool_set_hash
20
+
21
+ log = logging.getLogger("langchain_protogrid")
22
+
23
+ Secrets = Mapping[str, str | None]
24
+
25
+
26
+ @dataclass
27
+ class Skipped:
28
+ server: str
29
+ reason: str
30
+
31
+
32
+ @dataclass
33
+ class LoadReport:
34
+ """What `load_tools` did: the servers loaded, with the tool-set hash protogrid checked, and those it passed over."""
35
+
36
+ loaded: dict[str, str | None] = field(default_factory=dict)
37
+ skipped: list[Skipped] = field(default_factory=list)
38
+
39
+
40
+ class NoServerLoaded(RuntimeError):
41
+ def __init__(self, report: LoadReport):
42
+ reasons = "; ".join(f"{s.server}: {s.reason}" for s in report.skipped) or "no candidates"
43
+ super().__init__(f"no MCP server passed the rules and connected ({reasons})")
44
+ self.report = report
45
+
46
+
47
+ _TOOL_NAME = re.compile(r"[^A-Za-z0-9_-]")
48
+
49
+
50
+ def _tool_name(key: str, name: str) -> str:
51
+ """`<server key>_<tool>`, in the characters and length every chat model accepts for a tool name."""
52
+ return _TOOL_NAME.sub("_", f"{key}_{name}")[:64]
53
+
54
+
55
+ def _client(entry: Mapping[str, Any], *, oauth: bool) -> Client[Any]:
56
+ url = entry.get("url")
57
+ if not isinstance(url, str) or not url.startswith(("https://", "http://")):
58
+ raise ValueError("not a remote server")
59
+ headers = dict(entry.get("headers") or {})
60
+ auth = "oauth" if oauth else None
61
+ transport = SSETransport(url, headers=headers, auth=auth) if entry.get("type") == "sse" else StreamableHttpTransport(url, headers=headers, auth=auth)
62
+ return Client(transport)
63
+
64
+
65
+ async def load_tools(
66
+ query: str | None = None,
67
+ *,
68
+ servers: Sequence[str] | None = None,
69
+ rules: Rules = DEFAULT_RULES,
70
+ secrets: Secrets | None = None,
71
+ max_servers: int = 1,
72
+ candidates: int = 10,
73
+ pins: Mapping[str, str] | None = None,
74
+ strict_tools: bool = False,
75
+ api_key: str | None = None,
76
+ base_url: str | None = None,
77
+ registry: AsyncProtogridClient | None = None,
78
+ connect: Callable[[Mapping[str, Any], bool], Client[Any]] | None = None,
79
+ report: LoadReport | None = None,
80
+ ) -> list[BaseTool]:
81
+ """The LangChain tools of up to ``max_servers`` MCP servers that pass ``rules``.
82
+
83
+ Give a ``query`` (what the tools should do: the best ``candidates`` search results are tried in order) or a list
84
+ of ``servers`` by registry name. Each server goes through protogrid's gate with ``rules``; one that passes is
85
+ connected to directly, with the ``${NAME}`` placeholders of its connection filled from ``secrets`` (they never
86
+ leave your process), and its tools are returned named ``<server key>_<tool>``. A server that needs a secret you
87
+ did not give, a sign-in your rules do not allow, or a local package is passed over.
88
+
89
+ ``pins`` maps a server name to the tool-set hash you reviewed (``tools_hash`` of the gate): a server whose
90
+ checked tools changed since is passed over. With ``strict_tools``, the tools the server lists right now must be
91
+ the ones protogrid checked, so a change made after protogrid's last probe is caught too.
92
+
93
+ Raises :class:`NoServerLoaded` when none could be loaded; pass a :class:`LoadReport` to see why each server was
94
+ passed over either way.
95
+ """
96
+ if (query is None) == (servers is None):
97
+ raise ValueError("give either a query or a list of servers")
98
+ out = report if report is not None else LoadReport()
99
+ own = registry is None
100
+ reg = registry or AsyncProtogridClient(**{k: v for k, v in {"api_key": api_key, "base_url": base_url}.items() if v is not None}, user_agent="langchain-protogrid")
101
+ tools: list[BaseTool] = []
102
+ try:
103
+ names = list(servers) if servers is not None else [r["name"] for r in (await reg.search(query or "", limit=candidates, class_=[c for c in rules.classes if c != "L0"]))["results"]]
104
+ for name in names:
105
+ if len(out.loaded) >= max_servers:
106
+ break
107
+ loaded = await _load_one(reg, name, rules, secrets or {}, pins or {}, strict_tools, connect or (lambda e, o: _client(e, oauth=o)), out)
108
+ tools.extend(loaded)
109
+ finally:
110
+ if own:
111
+ await reg.aclose()
112
+ if not out.loaded:
113
+ raise NoServerLoaded(out)
114
+ return tools
115
+
116
+
117
+ async def _load_one(
118
+ reg: AsyncProtogridClient,
119
+ name: str,
120
+ rules: Rules,
121
+ secrets: Secrets,
122
+ pins: Mapping[str, str],
123
+ strict_tools: bool,
124
+ connect: Callable[[Mapping[str, Any], bool], Client[Any]],
125
+ out: LoadReport,
126
+ ) -> list[BaseTool]:
127
+ def skip(reason: str) -> list[BaseTool]:
128
+ log.info("protogrid: passed over %s: %s", name, reason)
129
+ out.skipped.append(Skipped(name, reason))
130
+ return []
131
+
132
+ try:
133
+ gate = await reg.gate(name, **rules.gate_kwargs())
134
+ except ProtogridError as e:
135
+ return skip(f"registry answered {e.status} ({e.code})")
136
+ if not gate["pass"]:
137
+ return skip("; ".join(f["detail"] for f in gate["failed"]))
138
+ checked = gate.get("tools_hash")
139
+ if name in pins and pins[name] != checked:
140
+ return skip(f"tools changed since pinned ({pins[name]} is now {checked})")
141
+ try:
142
+ conn = await reg.get_connection(name, "mcpServers")
143
+ except ProtogridError as e:
144
+ return skip(f"no connection offered ({e.code})")
145
+ if conn.get("kind") != "remote":
146
+ return skip("not a remote server (local packages are never loaded)")
147
+ _, raw = resolve_entry(conn, {}, partial=True)
148
+ missing = [p for p in placeholders_in(raw) if not secrets.get(p)]
149
+ if missing:
150
+ return skip(f"needs {', '.join(missing)}, not in secrets")
151
+ key, entry = resolve_entry(conn, secrets)
152
+ oauth = conn.get("class") == "R2"
153
+ try:
154
+ adapter = MCPAdapter(connect(entry, oauth))
155
+ # One listing serves both the comparison and the tools, as MCPAdapter.list_tools would do it.
156
+ async with adapter:
157
+ listed = await adapter.client.list_tools()
158
+ if strict_tools:
159
+ live = tool_set_hash([t.model_dump(mode="json", by_alias=True, exclude_unset=True) for t in listed])
160
+ if live != checked:
161
+ return skip(f"lists tools other than the ones protogrid checked ({live} against {checked})")
162
+ found = [await as_langchain_tool(t, adapter.client) for t in listed]
163
+ except Exception as e: # noqa: BLE001 - a server that cannot be reached is passed over, not fatal
164
+ return skip(f"could not connect: {type(e).__name__}: {e}")
165
+ for t in found:
166
+ t.name = _tool_name(key, t.name)
167
+ t.metadata = {**(t.metadata or {}), "protogrid_server": name, "protogrid_tools_hash": checked}
168
+ out.loaded[name] = checked
169
+ return list(found)
@@ -0,0 +1,36 @@
1
+ """The rules a server must pass before an agent may use it, set by whoever runs the agent, never by the model."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Sequence
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class Rules:
11
+ """Arguments of protogrid's gate. The defaults refuse what no agent should load: tools that hide text from people,
12
+ tools holding instructions aimed at the model, and servers depending on a package with a known vulnerability."""
13
+
14
+ min_quality: int | None = None
15
+ min_trust: int | None = None
16
+ no_fail: Sequence[str] = ("tools.hidden_text", "tools.poisoning")
17
+ exclude_quality_flags: Sequence[str] = ("known-vulns",)
18
+ exclude_flags: Sequence[str] = ()
19
+ owner_verified: bool | None = None
20
+ #: Connection classes allowed (R0 nothing to set up, R1 a key you hold, R2 OAuth sign-in). Local packages (L0)
21
+ #: are never loaded: they would run third-party code on your machine.
22
+ classes: Sequence[str] = field(default=("R0", "R1"))
23
+
24
+ def gate_kwargs(self) -> dict[str, Any]:
25
+ return {
26
+ "min_quality": self.min_quality,
27
+ "min_trust": self.min_trust,
28
+ "no_fail": list(self.no_fail) or None,
29
+ "exclude_quality_flags": list(self.exclude_quality_flags) or None,
30
+ "exclude_flags": list(self.exclude_flags) or None,
31
+ "class_": [c for c in self.classes if c != "L0"] or None,
32
+ "owner_verified": self.owner_verified,
33
+ }
34
+
35
+
36
+ DEFAULT_RULES = Rules()
@@ -0,0 +1,117 @@
1
+ """Two tools for an agent: find MCP servers by what they do, and ask whether one passes the rules its owner set."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ from typing import Any
7
+
8
+ from langchain_core.tools import BaseTool
9
+ from protogrid import AsyncProtogridClient, ProtogridClient, ProtogridError
10
+ from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, SecretStr
11
+
12
+ from .rules import DEFAULT_RULES, Rules
13
+
14
+
15
+ class _Registry(BaseTool):
16
+ """The connection to protogrid both tools share. ``PROTOGRID_API_KEY`` raises the limits; no key is needed."""
17
+
18
+ model_config = ConfigDict(arbitrary_types_allowed=True)
19
+ api_key: SecretStr | None = Field(default_factory=lambda: SecretStr(k) if (k := os.environ.get("PROTOGRID_API_KEY")) else None)
20
+ base_url: str = Field(default_factory=lambda: os.environ.get("PROTOGRID_API_URL", "https://api.protogrid.dev"))
21
+ _sync: ProtogridClient | None = PrivateAttr(default=None)
22
+
23
+ def _kwargs(self) -> dict[str, Any]:
24
+ return {"base_url": self.base_url, "api_key": self.api_key.get_secret_value() if self.api_key else None, "user_agent": "langchain-protogrid"}
25
+
26
+ def _client(self) -> ProtogridClient:
27
+ if self._sync is None:
28
+ self._sync = ProtogridClient(**self._kwargs())
29
+ return self._sync
30
+
31
+ def _aclient(self) -> AsyncProtogridClient:
32
+ return AsyncProtogridClient(**self._kwargs())
33
+
34
+
35
+ class SearchInput(BaseModel):
36
+ query: str = Field(description="What the MCP server should do, in plain words, such as 'send an email' or 'query a postgres database'.")
37
+ limit: int = Field(default=5, ge=1, le=20, description="How many servers to return.")
38
+
39
+
40
+ def _summary(r: dict[str, Any]) -> dict[str, Any]:
41
+ return {
42
+ "name": r["name"],
43
+ "title": r.get("title"),
44
+ "description": (r.get("description") or "")[:300],
45
+ "connection_class": r.get("connection_class"),
46
+ "quality_score": r.get("quality_score"),
47
+ "quality_flags": r.get("quality_flags", []),
48
+ "owner_verified": r.get("owner_verified", False),
49
+ "tools": [t["name"] for t in r.get("matched_tools", [])][:5],
50
+ }
51
+
52
+
53
+ class ProtogridSearch(_Registry):
54
+ """Finds MCP servers in the protogrid registry by what they do, with what decides the choice for each."""
55
+
56
+ name: str = "protogrid_search"
57
+ description: str = (
58
+ "Find MCP servers by what they do. Returns for each: its registry name, connection class (R0 nothing to set up, "
59
+ "R1 needs a key, R2 needs a sign-in, L0 a local package), quality score and flags, whether its owner is verified, "
60
+ "and the tools that matched."
61
+ )
62
+ args_schema: type[BaseModel] = SearchInput
63
+
64
+ def _run(self, query: str, limit: int = 5, **_: Any) -> str:
65
+ try:
66
+ res = self._client().search(query, limit=limit)
67
+ except ProtogridError as e:
68
+ return json.dumps({"error": e.code, "status": e.status})
69
+ return json.dumps([_summary(r) for r in res["results"]], ensure_ascii=False)
70
+
71
+ async def _arun(self, query: str, limit: int = 5, **_: Any) -> str:
72
+ async with self._aclient() as c:
73
+ try:
74
+ res = await c.search(query, limit=limit)
75
+ except ProtogridError as e:
76
+ return json.dumps({"error": e.code, "status": e.status})
77
+ return json.dumps([_summary(r) for r in res["results"]], ensure_ascii=False)
78
+
79
+
80
+ class GateInput(BaseModel):
81
+ server: str = Field(description="The server's registry name, such as io.github.owner/server, as protogrid_search returns it.")
82
+
83
+
84
+ class ProtogridGate(_Registry):
85
+ """Whether one MCP server passes the rules set when the tool was built. The model names the server; it cannot change
86
+ the rules."""
87
+
88
+ name: str = "protogrid_gate"
89
+ description: str = "Check whether an MCP server passes the rules its owner set for this agent before using it. Returns pass or fail with every broken rule."
90
+ args_schema: type[BaseModel] = GateInput
91
+ rules: Rules = DEFAULT_RULES
92
+
93
+ def _answer(self, gate: dict[str, Any]) -> str:
94
+ return json.dumps(
95
+ {
96
+ "server": gate["server"],
97
+ "pass": gate["pass"],
98
+ "failed": [f["detail"] for f in gate["failed"]],
99
+ "quality_score": gate["quality"]["score"],
100
+ "connection_class": gate["class"],
101
+ "owner_verified": gate["owner_verified"],
102
+ "tools_hash": gate.get("tools_hash"),
103
+ }
104
+ )
105
+
106
+ def _run(self, server: str, **_: Any) -> str:
107
+ try:
108
+ return self._answer(self._client().gate(server, **self.rules.gate_kwargs()))
109
+ except ProtogridError as e:
110
+ return json.dumps({"server": server, "pass": False, "failed": [f"registry answered {e.status} ({e.code})"]})
111
+
112
+ async def _arun(self, server: str, **_: Any) -> str:
113
+ async with self._aclient() as c:
114
+ try:
115
+ return self._answer(await c.gate(server, **self.rules.gate_kwargs()))
116
+ except ProtogridError as e:
117
+ return json.dumps({"server": server, "pass": False, "failed": [f"registry answered {e.status} ({e.code})"]})
@@ -0,0 +1,53 @@
1
+ """protogrid's tool-set hash, computed on the tools a server lists right now, to compare with the set protogrid checked.
2
+
3
+ The same canonical form as the registry: per tool, JSON with sorted keys of its name, title, description, input
4
+ schema, output schema and annotations (absent ones as null, a missing description as an empty string), SHA-256
5
+ truncated to 32 hex characters; the set hash is the same digest over the sorted ``name NUL hash`` lines.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ from collections.abc import Iterable, Mapping
12
+ from typing import Any
13
+
14
+
15
+ def _stable(value: Any) -> str:
16
+ if isinstance(value, dict):
17
+ return "{" + ",".join(f"{json.dumps(k, ensure_ascii=False)}:{_stable(v)}" for k, v in sorted(value.items())) + "}"
18
+ if isinstance(value, list):
19
+ return "[" + ",".join(_stable(v) for v in value) + "]"
20
+ if isinstance(value, bool) or value is None or isinstance(value, str):
21
+ return json.dumps(value, ensure_ascii=False)
22
+ if isinstance(value, float) and value.is_integer():
23
+ # JavaScript prints 1.0 as 1.
24
+ return str(int(value))
25
+ return json.dumps(value, ensure_ascii=False)
26
+
27
+
28
+
29
+ def _sha(s: str) -> str:
30
+ return hashlib.sha256(s.encode("utf-8")).hexdigest()[:32]
31
+
32
+
33
+ def tool_hash(tool: Mapping[str, Any]) -> str:
34
+ canonical = {
35
+ "name": tool.get("name"),
36
+ "title": tool.get("title"),
37
+ "description": tool.get("description") or "",
38
+ "inputSchema": tool.get("inputSchema"),
39
+ "outputSchema": tool.get("outputSchema"),
40
+ "annotations": tool.get("annotations"),
41
+ }
42
+ return _sha(_stable(canonical))
43
+
44
+
45
+ def tool_set_hash(tools: Iterable[Mapping[str, Any]]) -> str | None:
46
+ seen: dict[str, str] = {}
47
+ for t in tools:
48
+ name = t.get("name")
49
+ if isinstance(name, str) and name and name not in seen:
50
+ seen[name] = tool_hash(t)
51
+ if not seen:
52
+ return None
53
+ return _sha("\n".join(sorted(f"{n}\u0000{h}" for n, h in seen.items())))