gatecore-langchain 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.
- gatecore_langchain-0.1.0/LICENSE +21 -0
- gatecore_langchain-0.1.0/PKG-INFO +84 -0
- gatecore_langchain-0.1.0/README.md +61 -0
- gatecore_langchain-0.1.0/pyproject.toml +42 -0
- gatecore_langchain-0.1.0/setup.cfg +4 -0
- gatecore_langchain-0.1.0/src/gatecore_langchain/__init__.py +18 -0
- gatecore_langchain-0.1.0/src/gatecore_langchain/config.py +83 -0
- gatecore_langchain-0.1.0/src/gatecore_langchain/exceptions.py +14 -0
- gatecore_langchain-0.1.0/src/gatecore_langchain/execution.py +118 -0
- gatecore_langchain-0.1.0/src/gatecore_langchain/toolkit.py +113 -0
- gatecore_langchain-0.1.0/src/gatecore_langchain/transport.py +55 -0
- gatecore_langchain-0.1.0/src/gatecore_langchain.egg-info/PKG-INFO +84 -0
- gatecore_langchain-0.1.0/src/gatecore_langchain.egg-info/SOURCES.txt +15 -0
- gatecore_langchain-0.1.0/src/gatecore_langchain.egg-info/dependency_links.txt +1 -0
- gatecore_langchain-0.1.0/src/gatecore_langchain.egg-info/requires.txt +4 -0
- gatecore_langchain-0.1.0/src/gatecore_langchain.egg-info/top_level.txt +1 -0
- gatecore_langchain-0.1.0/tests/test_adapter.py +375 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 GateCore AI LLC
|
|
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,84 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gatecore-langchain
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: LangChain tools for GateCore marketplace discovery, procurement, and governed execution
|
|
5
|
+
Author-email: GateCore AI LLC <hello@gatecoreai.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://gatecoreai.com
|
|
8
|
+
Project-URL: Repository, https://github.com/GateCoreAI-com/GateCoreAI
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: gatecore-sdk<0.2.0,>=0.1.0
|
|
19
|
+
Requires-Dist: httpx<0.29.0,>=0.27.2
|
|
20
|
+
Requires-Dist: langchain-core<1.5.0,>=1.4.9
|
|
21
|
+
Requires-Dist: mcp==1.28.1
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# gatecore-langchain
|
|
25
|
+
|
|
26
|
+
`gatecore-langchain` provides three LangChain tools for GateCore marketplace discovery and
|
|
27
|
+
procurement, plus helpers that execute a procured capability through GateCore's signed gateway.
|
|
28
|
+
The adapter contains transport and configuration only; GateCore services enforce identity,
|
|
29
|
+
policy, trust, pricing, funding, delegation, and settlement.
|
|
30
|
+
|
|
31
|
+
The MCP tools support public `full`-mode GateCore endpoints only. `read` mode passes the server's
|
|
32
|
+
fail-closed procurement error through unchanged. `off` mode is unsupported because it does not
|
|
33
|
+
replace the adapter's legacy placeholder identity with the MCP credential identity.
|
|
34
|
+
|
|
35
|
+
## Install from the GateCore monorepo
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
python -m pip install -e ./libs/sdk -e ./libs/adapters/gatecore-langchain
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Install from PyPI (effective on publish)
|
|
42
|
+
|
|
43
|
+
*Effective once `gatecore-sdk` and this package have a real PyPI release — see
|
|
44
|
+
`.github/workflows/publish-pypi.yml`. Until then, use the monorepo install above.*
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
python -m pip install gatecore-langchain
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Configuration
|
|
51
|
+
|
|
52
|
+
Discovery and procurement require:
|
|
53
|
+
|
|
54
|
+
```text
|
|
55
|
+
GATECORE_MCP_URL=https://mcp.example.com/mcp
|
|
56
|
+
GATECORE_MCP_KEY=gcmk_...
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`execute_procured` and `aexecute_procured` validate these variables lazily on first use:
|
|
60
|
+
|
|
61
|
+
```text
|
|
62
|
+
GATECORE_GATEWAY_URL=https://api.example.com
|
|
63
|
+
GATECORE_BEARER_TOKEN=...
|
|
64
|
+
GATECORE_AGENT_ID=agent:example
|
|
65
|
+
GATECORE_ACCESS_GRANT_ID=grant:example
|
|
66
|
+
GATECORE_KEY_ID=key:example
|
|
67
|
+
GATECORE_PRIVATE_KEY_PATH=/secure/path/agent-key.pem
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Set exactly one of `GATECORE_PRIVATE_KEY_PATH` or `GATECORE_PRIVATE_KEY_PEM`.
|
|
71
|
+
|
|
72
|
+
## Usage
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from gatecore_langchain import GateCoreToolkit, execute_procured
|
|
76
|
+
|
|
77
|
+
tools = GateCoreToolkit().get_tools()
|
|
78
|
+
procure_result = tools[2].invoke({"listing_id": "listing:example"})
|
|
79
|
+
decision = execute_procured(procure_result, {"query": "example"})
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
All tools are async-native through LangChain's async invocation methods. Their synchronous bridge
|
|
83
|
+
uses `asyncio.run()` and therefore must not be called from a thread that already owns a running
|
|
84
|
+
event loop; use `ainvoke()` in async applications.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# gatecore-langchain
|
|
2
|
+
|
|
3
|
+
`gatecore-langchain` provides three LangChain tools for GateCore marketplace discovery and
|
|
4
|
+
procurement, plus helpers that execute a procured capability through GateCore's signed gateway.
|
|
5
|
+
The adapter contains transport and configuration only; GateCore services enforce identity,
|
|
6
|
+
policy, trust, pricing, funding, delegation, and settlement.
|
|
7
|
+
|
|
8
|
+
The MCP tools support public `full`-mode GateCore endpoints only. `read` mode passes the server's
|
|
9
|
+
fail-closed procurement error through unchanged. `off` mode is unsupported because it does not
|
|
10
|
+
replace the adapter's legacy placeholder identity with the MCP credential identity.
|
|
11
|
+
|
|
12
|
+
## Install from the GateCore monorepo
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
python -m pip install -e ./libs/sdk -e ./libs/adapters/gatecore-langchain
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Install from PyPI (effective on publish)
|
|
19
|
+
|
|
20
|
+
*Effective once `gatecore-sdk` and this package have a real PyPI release — see
|
|
21
|
+
`.github/workflows/publish-pypi.yml`. Until then, use the monorepo install above.*
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
python -m pip install gatecore-langchain
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Configuration
|
|
28
|
+
|
|
29
|
+
Discovery and procurement require:
|
|
30
|
+
|
|
31
|
+
```text
|
|
32
|
+
GATECORE_MCP_URL=https://mcp.example.com/mcp
|
|
33
|
+
GATECORE_MCP_KEY=gcmk_...
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`execute_procured` and `aexecute_procured` validate these variables lazily on first use:
|
|
37
|
+
|
|
38
|
+
```text
|
|
39
|
+
GATECORE_GATEWAY_URL=https://api.example.com
|
|
40
|
+
GATECORE_BEARER_TOKEN=...
|
|
41
|
+
GATECORE_AGENT_ID=agent:example
|
|
42
|
+
GATECORE_ACCESS_GRANT_ID=grant:example
|
|
43
|
+
GATECORE_KEY_ID=key:example
|
|
44
|
+
GATECORE_PRIVATE_KEY_PATH=/secure/path/agent-key.pem
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Set exactly one of `GATECORE_PRIVATE_KEY_PATH` or `GATECORE_PRIVATE_KEY_PEM`.
|
|
48
|
+
|
|
49
|
+
## Usage
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from gatecore_langchain import GateCoreToolkit, execute_procured
|
|
53
|
+
|
|
54
|
+
tools = GateCoreToolkit().get_tools()
|
|
55
|
+
procure_result = tools[2].invoke({"listing_id": "listing:example"})
|
|
56
|
+
decision = execute_procured(procure_result, {"query": "example"})
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
All tools are async-native through LangChain's async invocation methods. Their synchronous bridge
|
|
60
|
+
uses `asyncio.run()` and therefore must not be called from a thread that already owns a running
|
|
61
|
+
event loop; use `ainvoke()` in async applications.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
# setuptools>=77 is required (not just >=68) because this package declares its
|
|
3
|
+
# license as a PEP 639 SPDX expression string (`license = "MIT"` below); that
|
|
4
|
+
# form was only added in setuptools 77.0.0 — older setuptools versions reject
|
|
5
|
+
# it. See ADR-049.
|
|
6
|
+
requires = ["setuptools>=77"]
|
|
7
|
+
build-backend = "setuptools.build_meta"
|
|
8
|
+
|
|
9
|
+
[project]
|
|
10
|
+
name = "gatecore-langchain"
|
|
11
|
+
version = "0.1.0"
|
|
12
|
+
description = "LangChain tools for GateCore marketplace discovery, procurement, and governed execution"
|
|
13
|
+
readme = "README.md"
|
|
14
|
+
license = "MIT"
|
|
15
|
+
requires-python = ">=3.10"
|
|
16
|
+
authors = [
|
|
17
|
+
{ name = "GateCore AI LLC", email = "hello@gatecoreai.com" },
|
|
18
|
+
]
|
|
19
|
+
classifiers = [
|
|
20
|
+
"Development Status :: 4 - Beta",
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
"Programming Language :: Python :: 3.13",
|
|
26
|
+
]
|
|
27
|
+
dependencies = [
|
|
28
|
+
"gatecore-sdk>=0.1.0,<0.2.0",
|
|
29
|
+
"httpx>=0.27.2,<0.29.0",
|
|
30
|
+
"langchain-core>=1.4.9,<1.5.0",
|
|
31
|
+
"mcp==1.28.1",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Homepage = "https://gatecoreai.com"
|
|
36
|
+
Repository = "https://github.com/GateCoreAI-com/GateCoreAI"
|
|
37
|
+
|
|
38
|
+
[tool.setuptools.packages.find]
|
|
39
|
+
where = ["src"]
|
|
40
|
+
|
|
41
|
+
[tool.uv.sources]
|
|
42
|
+
gatecore-sdk = { path = "../../sdk", editable = true }
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from .config import GateCoreConfig
|
|
2
|
+
from .exceptions import (
|
|
3
|
+
GateCoreConfigError,
|
|
4
|
+
GateCoreProcurementDenied,
|
|
5
|
+
GateCoreProcurementPending,
|
|
6
|
+
)
|
|
7
|
+
from .execution import aexecute_procured, execute_procured
|
|
8
|
+
from .toolkit import GateCoreToolkit
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"GateCoreConfig",
|
|
12
|
+
"GateCoreConfigError",
|
|
13
|
+
"GateCoreProcurementDenied",
|
|
14
|
+
"GateCoreProcurementPending",
|
|
15
|
+
"GateCoreToolkit",
|
|
16
|
+
"aexecute_procured",
|
|
17
|
+
"execute_procured",
|
|
18
|
+
]
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from urllib.parse import urlsplit
|
|
7
|
+
|
|
8
|
+
from .exceptions import GateCoreConfigError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class GateCoreConfig:
|
|
13
|
+
mcp_url: str | None = None
|
|
14
|
+
mcp_key: str | None = field(default=None, repr=False)
|
|
15
|
+
gateway_url: str | None = None
|
|
16
|
+
bearer_token: str | None = field(default=None, repr=False)
|
|
17
|
+
agent_id: str | None = None
|
|
18
|
+
access_grant_id: str | None = None
|
|
19
|
+
key_id: str | None = None
|
|
20
|
+
private_key_pem: str | None = field(default=None, repr=False)
|
|
21
|
+
private_key_path: str | None = field(default=None, repr=False)
|
|
22
|
+
|
|
23
|
+
@classmethod
|
|
24
|
+
def from_env(cls) -> "GateCoreConfig":
|
|
25
|
+
return cls(
|
|
26
|
+
mcp_url=os.getenv("GATECORE_MCP_URL"),
|
|
27
|
+
mcp_key=os.getenv("GATECORE_MCP_KEY"),
|
|
28
|
+
gateway_url=os.getenv("GATECORE_GATEWAY_URL"),
|
|
29
|
+
bearer_token=os.getenv("GATECORE_BEARER_TOKEN"),
|
|
30
|
+
agent_id=os.getenv("GATECORE_AGENT_ID"),
|
|
31
|
+
access_grant_id=os.getenv("GATECORE_ACCESS_GRANT_ID"),
|
|
32
|
+
key_id=os.getenv("GATECORE_KEY_ID"),
|
|
33
|
+
private_key_pem=os.getenv("GATECORE_PRIVATE_KEY_PEM"),
|
|
34
|
+
private_key_path=os.getenv("GATECORE_PRIVATE_KEY_PATH"),
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
def require_mcp(self) -> tuple[str, str]:
|
|
38
|
+
mcp_url = _url(self.mcp_url, "GATECORE_MCP_URL")
|
|
39
|
+
mcp_key = _required(self.mcp_key, "GATECORE_MCP_KEY")
|
|
40
|
+
if not mcp_key.startswith("gcmk_"):
|
|
41
|
+
raise GateCoreConfigError("GATECORE_MCP_KEY is invalid")
|
|
42
|
+
return mcp_url, mcp_key
|
|
43
|
+
|
|
44
|
+
def require_execute(self) -> tuple[str, str, str, str, str, str]:
|
|
45
|
+
gateway_url = _url(self.gateway_url, "GATECORE_GATEWAY_URL")
|
|
46
|
+
bearer_token = _required(self.bearer_token, "GATECORE_BEARER_TOKEN")
|
|
47
|
+
agent_id = _required(self.agent_id, "GATECORE_AGENT_ID")
|
|
48
|
+
access_grant_id = _required(self.access_grant_id, "GATECORE_ACCESS_GRANT_ID")
|
|
49
|
+
key_id = _required(self.key_id, "GATECORE_KEY_ID")
|
|
50
|
+
|
|
51
|
+
if bool(self.private_key_pem) == bool(self.private_key_path):
|
|
52
|
+
raise GateCoreConfigError(
|
|
53
|
+
"exactly one of GATECORE_PRIVATE_KEY_PEM or GATECORE_PRIVATE_KEY_PATH is required"
|
|
54
|
+
)
|
|
55
|
+
if self.private_key_pem:
|
|
56
|
+
private_key = self.private_key_pem
|
|
57
|
+
else:
|
|
58
|
+
try:
|
|
59
|
+
private_key = Path(self.private_key_path or "").read_text()
|
|
60
|
+
except (OSError, UnicodeError) as exc:
|
|
61
|
+
raise GateCoreConfigError("GATECORE_PRIVATE_KEY_PATH is invalid") from exc
|
|
62
|
+
if not private_key.strip():
|
|
63
|
+
variable = (
|
|
64
|
+
"GATECORE_PRIVATE_KEY_PEM"
|
|
65
|
+
if self.private_key_pem is not None
|
|
66
|
+
else "GATECORE_PRIVATE_KEY_PATH"
|
|
67
|
+
)
|
|
68
|
+
raise GateCoreConfigError(f"{variable} is invalid")
|
|
69
|
+
return gateway_url, bearer_token, agent_id, access_grant_id, key_id, private_key
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _required(value: str | None, variable: str) -> str:
|
|
73
|
+
if value is None or not value.strip():
|
|
74
|
+
raise GateCoreConfigError(f"{variable} is required")
|
|
75
|
+
return value.strip()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _url(value: str | None, variable: str) -> str:
|
|
79
|
+
normalized = _required(value, variable)
|
|
80
|
+
parsed = urlsplit(normalized)
|
|
81
|
+
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
|
82
|
+
raise GateCoreConfigError(f"{variable} is invalid")
|
|
83
|
+
return normalized
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
class GateCoreConfigError(RuntimeError):
|
|
2
|
+
"""GateCore adapter configuration is missing or invalid."""
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class GateCoreProcurementPending(RuntimeError):
|
|
6
|
+
"""The procurement requires operator review before it can execute."""
|
|
7
|
+
|
|
8
|
+
def __init__(self, procurement_id: str | None):
|
|
9
|
+
self.procurement_id = procurement_id
|
|
10
|
+
super().__init__("GateCore procurement is pending review")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class GateCoreProcurementDenied(RuntimeError):
|
|
14
|
+
"""The procurement was denied or did not yield an executable delegation."""
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import binascii
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
from gatecore_sdk._common.client import GateCoreClient
|
|
10
|
+
|
|
11
|
+
from .config import GateCoreConfig
|
|
12
|
+
from .exceptions import (
|
|
13
|
+
GateCoreConfigError,
|
|
14
|
+
GateCoreProcurementDenied,
|
|
15
|
+
GateCoreProcurementPending,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
_CLAIM_FIELDS = ("target_type", "target_id", "operation", "max_price_cents", "currency")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def execute_procured(
|
|
22
|
+
procure_result: dict,
|
|
23
|
+
payload: dict,
|
|
24
|
+
*,
|
|
25
|
+
context: dict | None = None,
|
|
26
|
+
config: GateCoreConfig | None = None,
|
|
27
|
+
) -> dict:
|
|
28
|
+
"""Execute a PROCURE decision once through the signed GateCore gateway path."""
|
|
29
|
+
client, request = _signed_request(procure_result, payload, context, config)
|
|
30
|
+
return client.execute(request)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
async def aexecute_procured(
|
|
34
|
+
procure_result: dict,
|
|
35
|
+
payload: dict,
|
|
36
|
+
*,
|
|
37
|
+
context: dict | None = None,
|
|
38
|
+
config: GateCoreConfig | None = None,
|
|
39
|
+
) -> dict:
|
|
40
|
+
"""Async twin of :func:`execute_procured`; performs one request and never retries."""
|
|
41
|
+
client, request = _signed_request(procure_result, payload, context, config)
|
|
42
|
+
async with httpx.AsyncClient(timeout=10.0) as http:
|
|
43
|
+
response = await http.post(
|
|
44
|
+
f"{client.base_url}/v1/execute",
|
|
45
|
+
json=request,
|
|
46
|
+
headers=client.headers,
|
|
47
|
+
)
|
|
48
|
+
response.raise_for_status()
|
|
49
|
+
return response.json()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _signed_request(
|
|
53
|
+
procure_result: dict,
|
|
54
|
+
payload: dict,
|
|
55
|
+
context: dict | None,
|
|
56
|
+
config: GateCoreConfig | None,
|
|
57
|
+
) -> tuple[GateCoreClient, dict[str, Any]]:
|
|
58
|
+
delegation = procure_result.get("gateway_delegation") or {}
|
|
59
|
+
procurement_id = delegation.get("procurement_id") or procure_result.get("procurement_id")
|
|
60
|
+
if procure_result.get("action") == "REVIEW":
|
|
61
|
+
raise GateCoreProcurementPending(procurement_id)
|
|
62
|
+
token = delegation.get("delegation_token")
|
|
63
|
+
if procure_result.get("action") != "PROCURE" or not isinstance(token, str) or not token:
|
|
64
|
+
raise GateCoreProcurementDenied(
|
|
65
|
+
"GateCore procurement was denied or has no delegation token"
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
claims = _decode_claims(token)
|
|
69
|
+
cfg = config or GateCoreConfig.from_env()
|
|
70
|
+
(
|
|
71
|
+
gateway_url,
|
|
72
|
+
bearer_token,
|
|
73
|
+
agent_id,
|
|
74
|
+
access_grant_id,
|
|
75
|
+
key_id,
|
|
76
|
+
private_key,
|
|
77
|
+
) = cfg.require_execute()
|
|
78
|
+
client = GateCoreClient(base_url=gateway_url, bearer_token=bearer_token)
|
|
79
|
+
request_context = dict(context or {})
|
|
80
|
+
request_context["delegation_token"] = token
|
|
81
|
+
request = client.build_request(
|
|
82
|
+
origin_entity_id=agent_id,
|
|
83
|
+
target_type=claims["target_type"],
|
|
84
|
+
target_id=claims["target_id"],
|
|
85
|
+
operation=claims["operation"],
|
|
86
|
+
payload=payload,
|
|
87
|
+
context=request_context,
|
|
88
|
+
max_price_cents=claims["max_price_cents"],
|
|
89
|
+
access_grant_id=access_grant_id,
|
|
90
|
+
key_id=key_id,
|
|
91
|
+
)
|
|
92
|
+
request["currency"] = claims["currency"]
|
|
93
|
+
try:
|
|
94
|
+
request = client.sign_request(request, private_key_pem=private_key)
|
|
95
|
+
except (TypeError, ValueError, RuntimeError) as exc:
|
|
96
|
+
variable = (
|
|
97
|
+
"GATECORE_PRIVATE_KEY_PEM"
|
|
98
|
+
if cfg.private_key_pem is not None
|
|
99
|
+
else "GATECORE_PRIVATE_KEY_PATH"
|
|
100
|
+
)
|
|
101
|
+
raise GateCoreConfigError(f"{variable} is invalid") from exc
|
|
102
|
+
return client, request
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _decode_claims(token: str) -> dict[str, Any]:
|
|
106
|
+
try:
|
|
107
|
+
prefix, claims_part, _signature = token.split(".")
|
|
108
|
+
if prefix != "GCDT1":
|
|
109
|
+
raise ValueError
|
|
110
|
+
padding = "=" * (-len(claims_part) % 4)
|
|
111
|
+
claims = json.loads(base64.urlsafe_b64decode(claims_part + padding))
|
|
112
|
+
if not isinstance(claims, dict) or any(field not in claims for field in _CLAIM_FIELDS):
|
|
113
|
+
raise ValueError
|
|
114
|
+
return claims
|
|
115
|
+
except (ValueError, TypeError, binascii.Error, json.JSONDecodeError, UnicodeDecodeError) as exc:
|
|
116
|
+
raise GateCoreProcurementDenied(
|
|
117
|
+
"GateCore procurement delegation token is malformed"
|
|
118
|
+
) from exc
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Type
|
|
4
|
+
|
|
5
|
+
from langchain_core.tools import BaseTool
|
|
6
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
7
|
+
|
|
8
|
+
from .config import GateCoreConfig
|
|
9
|
+
from .transport import _McpTransport, _sync
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class _DiscoverInput(BaseModel):
|
|
13
|
+
query: str | None = None
|
|
14
|
+
tags: list[str] | None = None
|
|
15
|
+
max_price_cents: int | None = None
|
|
16
|
+
min_trust: float | None = None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _GetListingInput(BaseModel):
|
|
20
|
+
listing_id: str
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _ProcureInput(BaseModel):
|
|
24
|
+
listing_id: str
|
|
25
|
+
scopes: list[str] | None = None
|
|
26
|
+
max_price_cents: int | None = None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _GateCoreTool(BaseTool):
|
|
30
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
31
|
+
|
|
32
|
+
transport: Any = Field(exclude=True, repr=False)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _DiscoverTool(_GateCoreTool):
|
|
36
|
+
name: str = "gatecore_discover_listings"
|
|
37
|
+
description: str = "Discover published governed capabilities in the GateCore marketplace."
|
|
38
|
+
args_schema: Type[BaseModel] = _DiscoverInput
|
|
39
|
+
|
|
40
|
+
async def _arun(
|
|
41
|
+
self,
|
|
42
|
+
query: str | None = None,
|
|
43
|
+
tags: list[str] | None = None,
|
|
44
|
+
max_price_cents: int | None = None,
|
|
45
|
+
min_trust: float | None = None,
|
|
46
|
+
) -> list:
|
|
47
|
+
return await self.transport.call(
|
|
48
|
+
"discover_listings",
|
|
49
|
+
{
|
|
50
|
+
"query": query,
|
|
51
|
+
"tags": tags,
|
|
52
|
+
"max_price_cents": max_price_cents,
|
|
53
|
+
"min_trust": min_trust,
|
|
54
|
+
},
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
def _run(self, **kwargs: Any) -> list:
|
|
58
|
+
return _sync(self._arun(**kwargs))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _GetListingTool(_GateCoreTool):
|
|
62
|
+
name: str = "gatecore_get_listing"
|
|
63
|
+
description: str = "Fetch one published GateCore marketplace listing and its governed contract."
|
|
64
|
+
args_schema: Type[BaseModel] = _GetListingInput
|
|
65
|
+
|
|
66
|
+
async def _arun(self, listing_id: str) -> dict:
|
|
67
|
+
return await self.transport.call("get_listing", {"listing_id": listing_id})
|
|
68
|
+
|
|
69
|
+
def _run(self, **kwargs: Any) -> dict:
|
|
70
|
+
return _sync(self._arun(**kwargs))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class _ProcureTool(_GateCoreTool):
|
|
74
|
+
name: str = "gatecore_procure"
|
|
75
|
+
description: str = (
|
|
76
|
+
"Request governed procurement from a public full-mode GateCore MCP endpoint. "
|
|
77
|
+
"Identity and trust are derived from the configured MCP key."
|
|
78
|
+
)
|
|
79
|
+
args_schema: Type[BaseModel] = _ProcureInput
|
|
80
|
+
|
|
81
|
+
async def _arun(
|
|
82
|
+
self,
|
|
83
|
+
listing_id: str,
|
|
84
|
+
scopes: list[str] | None = None,
|
|
85
|
+
max_price_cents: int | None = None,
|
|
86
|
+
) -> dict:
|
|
87
|
+
return await self.transport.call(
|
|
88
|
+
"procure",
|
|
89
|
+
{
|
|
90
|
+
"listing_id": listing_id,
|
|
91
|
+
"requester_agent_id": "adapter:langchain",
|
|
92
|
+
"requester_trust": 0.0,
|
|
93
|
+
"scopes": scopes,
|
|
94
|
+
"max_price_cents": max_price_cents,
|
|
95
|
+
},
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
def _run(self, **kwargs: Any) -> dict:
|
|
99
|
+
return _sync(self._arun(**kwargs))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class GateCoreToolkit:
|
|
103
|
+
"""LangChain tools for a public full-mode GateCore MCP endpoint."""
|
|
104
|
+
|
|
105
|
+
def __init__(self, config: GateCoreConfig | None = None):
|
|
106
|
+
self._transport = _McpTransport(config or GateCoreConfig.from_env())
|
|
107
|
+
|
|
108
|
+
def get_tools(self) -> list[BaseTool]:
|
|
109
|
+
return [
|
|
110
|
+
_DiscoverTool(transport=self._transport),
|
|
111
|
+
_GetListingTool(transport=self._transport),
|
|
112
|
+
_ProcureTool(transport=self._transport),
|
|
113
|
+
]
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
from typing import Any, Coroutine
|
|
6
|
+
|
|
7
|
+
from mcp import ClientSession
|
|
8
|
+
from mcp.client.streamable_http import streamablehttp_client
|
|
9
|
+
|
|
10
|
+
from .config import GateCoreConfig
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class _McpTransport:
|
|
14
|
+
def __init__(self, config: GateCoreConfig):
|
|
15
|
+
self._url, self._key = config.require_mcp()
|
|
16
|
+
|
|
17
|
+
async def call(self, tool_name: str, arguments: dict[str, Any]) -> Any:
|
|
18
|
+
headers = {"X-GateCore-MCP-Key": self._key}
|
|
19
|
+
async with streamablehttp_client(self._url, headers=headers) as (read, write, _):
|
|
20
|
+
async with ClientSession(read, write) as session:
|
|
21
|
+
await session.initialize()
|
|
22
|
+
result = await session.call_tool(tool_name, arguments)
|
|
23
|
+
blocks = _blocks(result)
|
|
24
|
+
if getattr(result, "isError", False):
|
|
25
|
+
message = blocks[0] if blocks else "GateCore MCP tool failed"
|
|
26
|
+
raise RuntimeError(message if isinstance(message, str) else json.dumps(message))
|
|
27
|
+
if tool_name == "discover_listings":
|
|
28
|
+
return blocks
|
|
29
|
+
return blocks[0] if blocks else None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _blocks(result: Any) -> list[Any]:
|
|
33
|
+
structured = getattr(result, "structuredContent", None)
|
|
34
|
+
if isinstance(structured, dict) and set(structured) == {"result"}:
|
|
35
|
+
value = structured["result"]
|
|
36
|
+
return value if isinstance(value, list) else [value]
|
|
37
|
+
blocks: list[Any] = []
|
|
38
|
+
for item in getattr(result, "content", []) or []:
|
|
39
|
+
text = getattr(item, "text", None)
|
|
40
|
+
if text is None:
|
|
41
|
+
continue
|
|
42
|
+
try:
|
|
43
|
+
blocks.append(json.loads(text))
|
|
44
|
+
except (TypeError, ValueError):
|
|
45
|
+
blocks.append(text)
|
|
46
|
+
return blocks
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _sync(coro: Coroutine[Any, Any, Any]) -> Any:
|
|
50
|
+
try:
|
|
51
|
+
asyncio.get_running_loop()
|
|
52
|
+
except RuntimeError:
|
|
53
|
+
return asyncio.run(coro)
|
|
54
|
+
coro.close()
|
|
55
|
+
raise RuntimeError("use the async LangChain tool API inside a running event loop")
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gatecore-langchain
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: LangChain tools for GateCore marketplace discovery, procurement, and governed execution
|
|
5
|
+
Author-email: GateCore AI LLC <hello@gatecoreai.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://gatecoreai.com
|
|
8
|
+
Project-URL: Repository, https://github.com/GateCoreAI-com/GateCoreAI
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: gatecore-sdk<0.2.0,>=0.1.0
|
|
19
|
+
Requires-Dist: httpx<0.29.0,>=0.27.2
|
|
20
|
+
Requires-Dist: langchain-core<1.5.0,>=1.4.9
|
|
21
|
+
Requires-Dist: mcp==1.28.1
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# gatecore-langchain
|
|
25
|
+
|
|
26
|
+
`gatecore-langchain` provides three LangChain tools for GateCore marketplace discovery and
|
|
27
|
+
procurement, plus helpers that execute a procured capability through GateCore's signed gateway.
|
|
28
|
+
The adapter contains transport and configuration only; GateCore services enforce identity,
|
|
29
|
+
policy, trust, pricing, funding, delegation, and settlement.
|
|
30
|
+
|
|
31
|
+
The MCP tools support public `full`-mode GateCore endpoints only. `read` mode passes the server's
|
|
32
|
+
fail-closed procurement error through unchanged. `off` mode is unsupported because it does not
|
|
33
|
+
replace the adapter's legacy placeholder identity with the MCP credential identity.
|
|
34
|
+
|
|
35
|
+
## Install from the GateCore monorepo
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
python -m pip install -e ./libs/sdk -e ./libs/adapters/gatecore-langchain
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Install from PyPI (effective on publish)
|
|
42
|
+
|
|
43
|
+
*Effective once `gatecore-sdk` and this package have a real PyPI release — see
|
|
44
|
+
`.github/workflows/publish-pypi.yml`. Until then, use the monorepo install above.*
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
python -m pip install gatecore-langchain
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Configuration
|
|
51
|
+
|
|
52
|
+
Discovery and procurement require:
|
|
53
|
+
|
|
54
|
+
```text
|
|
55
|
+
GATECORE_MCP_URL=https://mcp.example.com/mcp
|
|
56
|
+
GATECORE_MCP_KEY=gcmk_...
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`execute_procured` and `aexecute_procured` validate these variables lazily on first use:
|
|
60
|
+
|
|
61
|
+
```text
|
|
62
|
+
GATECORE_GATEWAY_URL=https://api.example.com
|
|
63
|
+
GATECORE_BEARER_TOKEN=...
|
|
64
|
+
GATECORE_AGENT_ID=agent:example
|
|
65
|
+
GATECORE_ACCESS_GRANT_ID=grant:example
|
|
66
|
+
GATECORE_KEY_ID=key:example
|
|
67
|
+
GATECORE_PRIVATE_KEY_PATH=/secure/path/agent-key.pem
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Set exactly one of `GATECORE_PRIVATE_KEY_PATH` or `GATECORE_PRIVATE_KEY_PEM`.
|
|
71
|
+
|
|
72
|
+
## Usage
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
from gatecore_langchain import GateCoreToolkit, execute_procured
|
|
76
|
+
|
|
77
|
+
tools = GateCoreToolkit().get_tools()
|
|
78
|
+
procure_result = tools[2].invoke({"listing_id": "listing:example"})
|
|
79
|
+
decision = execute_procured(procure_result, {"query": "example"})
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
All tools are async-native through LangChain's async invocation methods. Their synchronous bridge
|
|
83
|
+
uses `asyncio.run()` and therefore must not be called from a thread that already owns a running
|
|
84
|
+
event loop; use `ainvoke()` in async applications.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/gatecore_langchain/__init__.py
|
|
5
|
+
src/gatecore_langchain/config.py
|
|
6
|
+
src/gatecore_langchain/exceptions.py
|
|
7
|
+
src/gatecore_langchain/execution.py
|
|
8
|
+
src/gatecore_langchain/toolkit.py
|
|
9
|
+
src/gatecore_langchain/transport.py
|
|
10
|
+
src/gatecore_langchain.egg-info/PKG-INFO
|
|
11
|
+
src/gatecore_langchain.egg-info/SOURCES.txt
|
|
12
|
+
src/gatecore_langchain.egg-info/dependency_links.txt
|
|
13
|
+
src/gatecore_langchain.egg-info/requires.txt
|
|
14
|
+
src/gatecore_langchain.egg-info/top_level.txt
|
|
15
|
+
tests/test_adapter.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
gatecore_langchain
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import base64
|
|
5
|
+
import json
|
|
6
|
+
from contextlib import asynccontextmanager
|
|
7
|
+
from types import SimpleNamespace
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
from cryptography.hazmat.primitives import serialization
|
|
11
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
12
|
+
from gatecore_sdk._common.client import canonical_request_payload
|
|
13
|
+
|
|
14
|
+
import gatecore_langchain.execution as execution_module
|
|
15
|
+
import gatecore_langchain.transport as transport_module
|
|
16
|
+
import gatecore_langchain
|
|
17
|
+
from gatecore_langchain import (
|
|
18
|
+
GateCoreConfig,
|
|
19
|
+
GateCoreConfigError,
|
|
20
|
+
GateCoreProcurementDenied,
|
|
21
|
+
GateCoreProcurementPending,
|
|
22
|
+
GateCoreToolkit,
|
|
23
|
+
aexecute_procured,
|
|
24
|
+
execute_procured,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _private_pem() -> tuple[str, Ed25519PrivateKey]:
|
|
29
|
+
key = Ed25519PrivateKey.generate()
|
|
30
|
+
pem = key.private_bytes(
|
|
31
|
+
encoding=serialization.Encoding.PEM,
|
|
32
|
+
format=serialization.PrivateFormat.PKCS8,
|
|
33
|
+
encryption_algorithm=serialization.NoEncryption(),
|
|
34
|
+
).decode()
|
|
35
|
+
return pem, key
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _config(private_pem: str, **overrides) -> GateCoreConfig:
|
|
39
|
+
values = {
|
|
40
|
+
"mcp_url": "https://mcp.example/mcp",
|
|
41
|
+
"mcp_key": "gcmk_test_secret",
|
|
42
|
+
"gateway_url": "https://gateway.example",
|
|
43
|
+
"bearer_token": "bearer_secret",
|
|
44
|
+
"agent_id": "agent:langchain",
|
|
45
|
+
"access_grant_id": "grant:langchain",
|
|
46
|
+
"key_id": "key:langchain",
|
|
47
|
+
"private_key_pem": private_pem,
|
|
48
|
+
}
|
|
49
|
+
values.update(overrides)
|
|
50
|
+
return GateCoreConfig(**values)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _token(**overrides) -> tuple[str, dict]:
|
|
54
|
+
claims = {
|
|
55
|
+
"target_type": "tool",
|
|
56
|
+
"target_id": "tool:search",
|
|
57
|
+
"operation": "search",
|
|
58
|
+
"max_price_cents": 17,
|
|
59
|
+
"currency": "EUR",
|
|
60
|
+
}
|
|
61
|
+
claims.update(overrides)
|
|
62
|
+
encoded = base64.urlsafe_b64encode(
|
|
63
|
+
json.dumps(claims, separators=(",", ":")).encode()
|
|
64
|
+
).decode().rstrip("=")
|
|
65
|
+
return f"GCDT1.{encoded}.signature", claims
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _procure_result(token: str, *, action: str = "PROCURE") -> dict:
|
|
69
|
+
return {
|
|
70
|
+
"action": action,
|
|
71
|
+
"gateway_delegation": {
|
|
72
|
+
"procurement_id": "proc_test",
|
|
73
|
+
"delegation_token": token,
|
|
74
|
+
},
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _install_fake_mcp(monkeypatch, results: dict[str, object]):
|
|
79
|
+
calls: list[tuple[str, dict]] = []
|
|
80
|
+
connection: dict[str, object] = {}
|
|
81
|
+
|
|
82
|
+
@asynccontextmanager
|
|
83
|
+
async def fake_stream(url, *, headers):
|
|
84
|
+
connection.update(url=url, headers=headers)
|
|
85
|
+
yield "read", "write", None
|
|
86
|
+
|
|
87
|
+
class FakeSession:
|
|
88
|
+
def __init__(self, read, write):
|
|
89
|
+
assert (read, write) == ("read", "write")
|
|
90
|
+
|
|
91
|
+
async def __aenter__(self):
|
|
92
|
+
return self
|
|
93
|
+
|
|
94
|
+
async def __aexit__(self, *_args):
|
|
95
|
+
return None
|
|
96
|
+
|
|
97
|
+
async def initialize(self):
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
async def call_tool(self, name, arguments):
|
|
101
|
+
calls.append((name, arguments))
|
|
102
|
+
value = results[name]
|
|
103
|
+
if isinstance(value, _ServerError):
|
|
104
|
+
return SimpleNamespace(
|
|
105
|
+
structuredContent=None,
|
|
106
|
+
content=[SimpleNamespace(text=value.message)],
|
|
107
|
+
isError=True,
|
|
108
|
+
)
|
|
109
|
+
return SimpleNamespace(
|
|
110
|
+
structuredContent={"result": value},
|
|
111
|
+
content=[],
|
|
112
|
+
isError=False,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
monkeypatch.setattr(transport_module, "streamablehttp_client", fake_stream)
|
|
116
|
+
monkeypatch.setattr(transport_module, "ClientSession", FakeSession)
|
|
117
|
+
return calls, connection
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class _Response:
|
|
121
|
+
def __init__(self, body: dict):
|
|
122
|
+
self._body = body
|
|
123
|
+
|
|
124
|
+
def raise_for_status(self):
|
|
125
|
+
return None
|
|
126
|
+
|
|
127
|
+
def json(self):
|
|
128
|
+
return self._body
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class _ServerError:
|
|
132
|
+
def __init__(self, message: str):
|
|
133
|
+
self.message = message
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_1_toolkit_exposes_exact_names_and_schemas():
|
|
137
|
+
assert set(gatecore_langchain.__all__) == {
|
|
138
|
+
"GateCoreConfig",
|
|
139
|
+
"GateCoreConfigError",
|
|
140
|
+
"GateCoreProcurementDenied",
|
|
141
|
+
"GateCoreProcurementPending",
|
|
142
|
+
"GateCoreToolkit",
|
|
143
|
+
"aexecute_procured",
|
|
144
|
+
"execute_procured",
|
|
145
|
+
}
|
|
146
|
+
tools = GateCoreToolkit(
|
|
147
|
+
GateCoreConfig(mcp_url="https://mcp.example/mcp", mcp_key="gcmk_test")
|
|
148
|
+
).get_tools()
|
|
149
|
+
assert [tool.name for tool in tools] == [
|
|
150
|
+
"gatecore_discover_listings",
|
|
151
|
+
"gatecore_get_listing",
|
|
152
|
+
"gatecore_procure",
|
|
153
|
+
]
|
|
154
|
+
assert [
|
|
155
|
+
set(tool.get_input_schema().model_json_schema()["properties"]) for tool in tools
|
|
156
|
+
] == [
|
|
157
|
+
{"query", "tags", "max_price_cents", "min_trust"},
|
|
158
|
+
{"listing_id"},
|
|
159
|
+
{"listing_id", "scopes", "max_price_cents"},
|
|
160
|
+
]
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def test_2_procure_injects_placeholders_and_locked_header(monkeypatch):
|
|
164
|
+
results = {"procure": {"action": "PROCURE"}}
|
|
165
|
+
calls, connection = _install_fake_mcp(monkeypatch, results)
|
|
166
|
+
tool = GateCoreToolkit(
|
|
167
|
+
GateCoreConfig(mcp_url="https://mcp.example/mcp", mcp_key="gcmk_locked")
|
|
168
|
+
).get_tools()[2]
|
|
169
|
+
assert asyncio.run(
|
|
170
|
+
tool.ainvoke(
|
|
171
|
+
{"listing_id": "listing:1", "scopes": ["docs:read"], "max_price_cents": 25}
|
|
172
|
+
)
|
|
173
|
+
) == {"action": "PROCURE"}
|
|
174
|
+
assert connection == {
|
|
175
|
+
"url": "https://mcp.example/mcp",
|
|
176
|
+
"headers": {"X-GateCore-MCP-Key": "gcmk_locked"},
|
|
177
|
+
}
|
|
178
|
+
assert calls == [
|
|
179
|
+
(
|
|
180
|
+
"procure",
|
|
181
|
+
{
|
|
182
|
+
"listing_id": "listing:1",
|
|
183
|
+
"requester_agent_id": "adapter:langchain",
|
|
184
|
+
"requester_trust": 0.0,
|
|
185
|
+
"scopes": ["docs:read"],
|
|
186
|
+
"max_price_cents": 25,
|
|
187
|
+
},
|
|
188
|
+
)
|
|
189
|
+
]
|
|
190
|
+
server_message = "MCP key required: register via GateCore"
|
|
191
|
+
results["procure"] = _ServerError(server_message)
|
|
192
|
+
with pytest.raises(RuntimeError) as error:
|
|
193
|
+
asyncio.run(tool.ainvoke({"listing_id": "listing:1"}))
|
|
194
|
+
assert str(error.value) == server_message
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def test_3_discover_and_get_pass_parameters_through(monkeypatch):
|
|
198
|
+
calls, _ = _install_fake_mcp(
|
|
199
|
+
monkeypatch,
|
|
200
|
+
{
|
|
201
|
+
"discover_listings": [{"listing_id": "listing:1"}],
|
|
202
|
+
"get_listing": {"listing_id": "listing:1"},
|
|
203
|
+
},
|
|
204
|
+
)
|
|
205
|
+
discover, get_listing, _ = GateCoreToolkit(
|
|
206
|
+
GateCoreConfig(mcp_url="https://mcp.example/mcp", mcp_key="gcmk_test")
|
|
207
|
+
).get_tools()
|
|
208
|
+
assert asyncio.run(
|
|
209
|
+
discover.ainvoke(
|
|
210
|
+
{
|
|
211
|
+
"query": "search",
|
|
212
|
+
"tags": ["docs"],
|
|
213
|
+
"max_price_cents": 90,
|
|
214
|
+
"min_trust": 0.75,
|
|
215
|
+
}
|
|
216
|
+
)
|
|
217
|
+
) == [{"listing_id": "listing:1"}]
|
|
218
|
+
assert asyncio.run(get_listing.ainvoke({"listing_id": "listing:1"})) == {
|
|
219
|
+
"listing_id": "listing:1"
|
|
220
|
+
}
|
|
221
|
+
assert calls == [
|
|
222
|
+
(
|
|
223
|
+
"discover_listings",
|
|
224
|
+
{
|
|
225
|
+
"query": "search",
|
|
226
|
+
"tags": ["docs"],
|
|
227
|
+
"max_price_cents": 90,
|
|
228
|
+
"min_trust": 0.75,
|
|
229
|
+
},
|
|
230
|
+
),
|
|
231
|
+
("get_listing", {"listing_id": "listing:1"}),
|
|
232
|
+
]
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def test_4_execute_maps_claims_context_and_sdk_signature(monkeypatch):
|
|
236
|
+
private_pem, private_key = _private_pem()
|
|
237
|
+
token, claims = _token()
|
|
238
|
+
captured: dict = {}
|
|
239
|
+
|
|
240
|
+
def fake_post(url, *, json, headers, timeout):
|
|
241
|
+
captured.update(url=url, request=json, headers=headers, timeout=timeout)
|
|
242
|
+
return _Response({"decision": {"action": "ALLOW"}, "execution_status": "EXECUTED"})
|
|
243
|
+
|
|
244
|
+
monkeypatch.setattr("gatecore_sdk._common.client.httpx.post", fake_post)
|
|
245
|
+
result = execute_procured(
|
|
246
|
+
_procure_result(token),
|
|
247
|
+
{"query": "hello"},
|
|
248
|
+
context={"trace_id": "trace-1", "delegation_token": "caller-cannot-override"},
|
|
249
|
+
config=_config(private_pem),
|
|
250
|
+
)
|
|
251
|
+
assert result == {"decision": {"action": "ALLOW"}, "execution_status": "EXECUTED"}
|
|
252
|
+
request = captured["request"]
|
|
253
|
+
assert captured["url"] == "https://gateway.example/v1/execute"
|
|
254
|
+
assert captured["headers"] == {"Authorization": "Bearer bearer_secret"}
|
|
255
|
+
assert captured["timeout"] == 10.0
|
|
256
|
+
assert request["origin_entity_id"] == "agent:langchain"
|
|
257
|
+
assert request["access_grant_id"] == "grant:langchain"
|
|
258
|
+
assert request["key_id"] == "key:langchain"
|
|
259
|
+
for field in ("target_type", "target_id", "operation", "max_price_cents", "currency"):
|
|
260
|
+
assert request[field] == claims[field]
|
|
261
|
+
assert request["context"] == {"trace_id": "trace-1", "delegation_token": token}
|
|
262
|
+
signature = base64.urlsafe_b64decode(request["signature"] + "==")
|
|
263
|
+
private_key.public_key().verify(signature, canonical_request_payload(request))
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def test_5_review_and_denied_results_raise_locked_exceptions():
|
|
267
|
+
token, _ = _token()
|
|
268
|
+
with pytest.raises(GateCoreProcurementPending) as pending:
|
|
269
|
+
execute_procured(_procure_result(token, action="REVIEW"), {}, config=GateCoreConfig())
|
|
270
|
+
assert pending.value.procurement_id == "proc_test"
|
|
271
|
+
with pytest.raises(GateCoreProcurementDenied):
|
|
272
|
+
execute_procured({"action": "DENY"}, {}, config=GateCoreConfig())
|
|
273
|
+
with pytest.raises(GateCoreProcurementDenied):
|
|
274
|
+
execute_procured(
|
|
275
|
+
{"action": "PROCURE", "gateway_delegation": {}},
|
|
276
|
+
{},
|
|
277
|
+
config=GateCoreConfig(),
|
|
278
|
+
)
|
|
279
|
+
with pytest.raises(
|
|
280
|
+
GateCoreProcurementDenied,
|
|
281
|
+
match="GateCore procurement delegation token is malformed",
|
|
282
|
+
):
|
|
283
|
+
execute_procured(
|
|
284
|
+
_procure_result("GCDT1.a.signature"),
|
|
285
|
+
{},
|
|
286
|
+
config=GateCoreConfig(),
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def test_6_missing_environment_fails_closed_and_names_variable(monkeypatch):
|
|
291
|
+
for variable in (
|
|
292
|
+
"GATECORE_MCP_URL",
|
|
293
|
+
"GATECORE_MCP_KEY",
|
|
294
|
+
"GATECORE_GATEWAY_URL",
|
|
295
|
+
"GATECORE_BEARER_TOKEN",
|
|
296
|
+
"GATECORE_AGENT_ID",
|
|
297
|
+
"GATECORE_ACCESS_GRANT_ID",
|
|
298
|
+
"GATECORE_KEY_ID",
|
|
299
|
+
"GATECORE_PRIVATE_KEY_PEM",
|
|
300
|
+
"GATECORE_PRIVATE_KEY_PATH",
|
|
301
|
+
):
|
|
302
|
+
monkeypatch.delenv(variable, raising=False)
|
|
303
|
+
with pytest.raises(GateCoreConfigError, match="GATECORE_MCP_URL"):
|
|
304
|
+
GateCoreToolkit()
|
|
305
|
+
with pytest.raises(GateCoreConfigError, match="GATECORE_MCP_KEY"):
|
|
306
|
+
GateCoreToolkit(
|
|
307
|
+
GateCoreConfig(
|
|
308
|
+
mcp_url="https://mcp.example/mcp",
|
|
309
|
+
mcp_key="not-an-mcp-key",
|
|
310
|
+
)
|
|
311
|
+
)
|
|
312
|
+
with pytest.raises(GateCoreConfigError, match="GATECORE_GATEWAY_URL"):
|
|
313
|
+
GateCoreConfig(gateway_url="not-a-url").require_execute()
|
|
314
|
+
token, _ = _token()
|
|
315
|
+
with pytest.raises(GateCoreConfigError, match="GATECORE_GATEWAY_URL"):
|
|
316
|
+
execute_procured(_procure_result(token), {}, config=GateCoreConfig())
|
|
317
|
+
private_pem, _ = _private_pem()
|
|
318
|
+
with pytest.raises(GateCoreConfigError, match="GATECORE_PRIVATE_KEY_PEM"):
|
|
319
|
+
_config(private_pem, private_key_path="also-set.pem").require_execute()
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def test_7_sync_async_parity_for_procure_and_execute(monkeypatch):
|
|
323
|
+
calls, _ = _install_fake_mcp(monkeypatch, {"procure": {"action": "PROCURE"}})
|
|
324
|
+
tool = GateCoreToolkit(
|
|
325
|
+
GateCoreConfig(mcp_url="https://mcp.example/mcp", mcp_key="gcmk_test")
|
|
326
|
+
).get_tools()[2]
|
|
327
|
+
arguments = {"listing_id": "listing:1", "scopes": ["a"], "max_price_cents": 4}
|
|
328
|
+
assert tool.invoke(arguments) == asyncio.run(tool.ainvoke(arguments))
|
|
329
|
+
assert len(calls) == 2
|
|
330
|
+
|
|
331
|
+
private_pem, _ = _private_pem()
|
|
332
|
+
token, _ = _token()
|
|
333
|
+
posts: list[str] = []
|
|
334
|
+
|
|
335
|
+
def fake_post(url, **_kwargs):
|
|
336
|
+
posts.append("sync")
|
|
337
|
+
return _Response({"execution_status": "EXECUTED"})
|
|
338
|
+
|
|
339
|
+
class FakeAsyncClient:
|
|
340
|
+
def __init__(self, *, timeout):
|
|
341
|
+
assert timeout == 10.0
|
|
342
|
+
|
|
343
|
+
async def __aenter__(self):
|
|
344
|
+
return self
|
|
345
|
+
|
|
346
|
+
async def __aexit__(self, *_args):
|
|
347
|
+
return None
|
|
348
|
+
|
|
349
|
+
async def post(self, url, **_kwargs):
|
|
350
|
+
posts.append("async")
|
|
351
|
+
return _Response({"execution_status": "EXECUTED"})
|
|
352
|
+
|
|
353
|
+
monkeypatch.setattr("gatecore_sdk._common.client.httpx.post", fake_post)
|
|
354
|
+
monkeypatch.setattr(execution_module.httpx, "AsyncClient", FakeAsyncClient)
|
|
355
|
+
procure_result = _procure_result(token)
|
|
356
|
+
config = _config(private_pem)
|
|
357
|
+
assert execute_procured(procure_result, {}, config=config) == asyncio.run(
|
|
358
|
+
aexecute_procured(procure_result, {}, config=config)
|
|
359
|
+
)
|
|
360
|
+
assert posts == ["sync", "async"]
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def test_8_key_material_never_appears_in_repr_logs_or_exceptions(caplog):
|
|
364
|
+
secret_pem = "PRIVATE_KEY_SUPER_SECRET"
|
|
365
|
+
config = _config(secret_pem)
|
|
366
|
+
rendered = repr(config)
|
|
367
|
+
assert secret_pem not in rendered
|
|
368
|
+
assert "gcmk_test_secret" not in rendered
|
|
369
|
+
assert "bearer_secret" not in rendered
|
|
370
|
+
token, _ = _token()
|
|
371
|
+
with pytest.raises(GateCoreConfigError) as error:
|
|
372
|
+
execute_procured(_procure_result(token), {}, config=config)
|
|
373
|
+
assert secret_pem not in str(error.value)
|
|
374
|
+
assert secret_pem not in repr(error.value)
|
|
375
|
+
assert secret_pem not in caplog.text
|