gatecore-langchain 0.1.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,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,11 @@
1
+ gatecore_langchain/__init__.py,sha256=Q4itQagK8Vhx9pnYZEucz85cXMHmlpoW6LbakErEVJw,450
2
+ gatecore_langchain/config.py,sha256=7zvFMxZTb56HTMnP1AJHsUwsdQYz7Q7EF8T21l5M3dM,3408
3
+ gatecore_langchain/exceptions.py,sha256=O6grBxCwfJybd2zcVh4dg1ICmfdCaY714Og0vTz_ydo,523
4
+ gatecore_langchain/execution.py,sha256=IovVW6gQc57K4uoHm29yXl9uyQkvMPCof1rf6Oxkal0,3990
5
+ gatecore_langchain/toolkit.py,sha256=zunZOsz5yoxiF2vDgUBgFcZ_TPtKUoZGz2pi0TqYSIU,3349
6
+ gatecore_langchain/transport.py,sha256=Y9O7n_o9PApbD-dof8di5YkKoiqQcpkPrTVSYjkG3D4,1950
7
+ gatecore_langchain-0.1.0.dist-info/licenses/LICENSE,sha256=B1WbsXkrxx8-VNkK_0d5z6DkwGlsEUBnQj6_ElW3BmE,1072
8
+ gatecore_langchain-0.1.0.dist-info/METADATA,sha256=kXKpQu8Em4JMLAgSHQlKjeJNkuuzgBc6F-eBY7qD3UE,2987
9
+ gatecore_langchain-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
10
+ gatecore_langchain-0.1.0.dist-info/top_level.txt,sha256=npeyFSUqVoPm7twmpkEysHqcOB5fMDDD-0YL9bQX0Dc,19
11
+ gatecore_langchain-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ gatecore_langchain