ath-sdk-python 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.
ath_sdk/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ # -*- coding: utf-8 -*-
2
+ """ATH SDK —— 智能体可信握手客户端(ATH 1.0)"""
3
+ from .client import ATHConnector, ATHError, connect, __version__
4
+
5
+ __all__ = ["ATHConnector", "ATHError", "connect", "__version__"]
6
+
7
+
8
+ def __getattr__(name):
9
+ # LangChain 集成为可选增强:仅在显式导入时才要求已安装 langchain-core
10
+ if name in ("ATHAgentTool", "make_ath_tools"):
11
+ from . import langchain_tool as _lt
12
+ return getattr(_lt, name)
13
+ raise AttributeError("module %r has no attribute %r" % (__name__, name))
ath_sdk/__main__.py ADDED
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """命令行自检:python -m ath_sdk --gateway https://api.example.com"""
4
+ import argparse
5
+ import json
6
+ import os
7
+ import sys
8
+
9
+ from .client import ATHConnector, ATHError
10
+
11
+
12
+ def main():
13
+ ap = argparse.ArgumentParser(description="ATH 1.0 客户端自检")
14
+ ap.add_argument("--gateway", default=os.environ.get("ATH_GATEWAY", ""),
15
+ help="ATH 网关地址(或环境变量 ATH_GATEWAY)")
16
+ ap.add_argument("--action", choices=["discover", "handshake"], default="discover",
17
+ help="discover=只读发现文档;handshake=发现+握手互验(需凭证)")
18
+ args = ap.parse_args()
19
+ if not args.gateway:
20
+ sys.exit("请通过 --gateway 或环境变量 ATH_GATEWAY 指定网关地址")
21
+ try:
22
+ c = ATHConnector(args.gateway)
23
+ doc = c.discover()
24
+ if args.action == "discover":
25
+ print(json.dumps(doc, ensure_ascii=False, indent=2))
26
+ return
27
+ c.handshake()
28
+ print("握手互验通过")
29
+ except ATHError as e:
30
+ sys.exit("自检失败: %s (status=%s)" % (e, e.status))
31
+
32
+
33
+ if __name__ == "__main__":
34
+ main()
ath_sdk/client.py ADDED
@@ -0,0 +1,226 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """ATH SDK —— 智能体可信握手客户端(ATH 1.0,纯标准库,零第三方依赖)
4
+
5
+ 一个文件即可拷走使用:本模块不依赖包内其他文件。
6
+ 九步可信握手:发现 → 注册 → 握手互验 → 授权请求 → 三方交集确认 → 令牌 → 受保护访问 → 吊销。
7
+
8
+ 快速上手:
9
+ from ath_sdk import ATHConnector, connect
10
+
11
+ agent = connect(
12
+ gateway="https://api.example.com", # ATH 网关地址
13
+ client_id="...", client_secret="...", client_did="did:ath:...",
14
+ user_id="user-xxx",
15
+ confirm_credential="...", # 网关运营方就本次请求签发的确认凭证
16
+ )
17
+ agent.protected("/ath/protected/ping") # 带令牌访问受保护资源
18
+
19
+ 未注册的智能体先用注册凭证注册(见 register());
20
+ 确认凭证经网关运营方的带外通道(如邮箱)就每次授权请求动态获取。
21
+ """
22
+ import hashlib
23
+ import hmac
24
+ import json
25
+ import os
26
+ import time
27
+ import urllib.error
28
+ import urllib.request
29
+
30
+ __version__ = "0.1.0"
31
+
32
+ DEFAULT_TIMEOUT = 10
33
+
34
+
35
+ class ATHError(RuntimeError):
36
+ """ATH 流程错误,携带 HTTP 状态码与响应体,便于定位协议偏离点。"""
37
+
38
+ def __init__(self, message, status=None, response=None):
39
+ super().__init__(message)
40
+ self.status = status
41
+ self.response = response
42
+
43
+
44
+ class ATHConnector:
45
+ """ATH 1.0 客户端。一个实例对应一个网关接入身份与会话状态。"""
46
+
47
+ def __init__(self, gateway, client_id=None, client_secret=None,
48
+ client_did=None, timeout=DEFAULT_TIMEOUT):
49
+ if not gateway:
50
+ raise ATHError("缺少网关地址:请传入 gateway 或设置环境变量 ATH_GATEWAY")
51
+ self.gateway = gateway.rstrip("/")
52
+ self.client_id = client_id or os.environ.get("ATH_CLIENT_ID", "")
53
+ self.client_secret = client_secret or os.environ.get("ATH_CLIENT_SECRET", "")
54
+ self.client_did = client_did or os.environ.get("ATH_CLIENT_DID", "")
55
+ self.timeout = timeout
56
+ self.hs_id = None
57
+ self.scopes_supported = []
58
+ self.request_id = None
59
+ self.final_scopes = []
60
+ self._token = None
61
+ self._token_exp = 0.0
62
+
63
+ # ---- 底层 HTTP ----
64
+ def _request(self, method, path, body=None, headers=None):
65
+ req = urllib.request.Request(
66
+ self.gateway + path,
67
+ json.dumps(body).encode() if body is not None else None,
68
+ headers=headers or {}, method=method)
69
+ try:
70
+ with urllib.request.urlopen(req, timeout=self.timeout) as r:
71
+ return r.status, json.loads(r.read().decode("utf-8"))
72
+ except urllib.error.HTTPError as e:
73
+ try:
74
+ return e.code, json.loads(e.read().decode("utf-8"))
75
+ except Exception:
76
+ return e.code, {}
77
+ except urllib.error.URLError as e:
78
+ raise ATHError("网络错误: %s" % e.reason)
79
+
80
+ def _post(self, path, body=None, headers=None):
81
+ return self._request("POST", path, body, headers)
82
+
83
+ def _get(self, path, headers=None):
84
+ return self._request("GET", path, None, headers)
85
+
86
+ # ---- 步骤 0:发现 ----
87
+ def discover(self):
88
+ """读取网关发现文档(/.well-known/ath.json),记录支持的权限。"""
89
+ status, doc = self._get("/.well-known/ath.json")
90
+ if status != 200:
91
+ raise ATHError("发现文档不可达", status, doc)
92
+ self.scopes_supported = [s for p in doc.get("supported_providers", [])
93
+ for s in p.get("scopes_supported", [])]
94
+ return doc
95
+
96
+ # ---- 注册(需网关运营方发放的注册凭证)----
97
+ def register(self, account, registration_credential, scopes=None):
98
+ """用注册凭证注册,取得 client_id / client_secret / DID。
99
+
100
+ 注册凭证 = HMAC-SHA256(注册密钥, "register:" + 账号名),只对固定账号名有效,
101
+ 由网关运营方发放(演示凭证或邮箱申请)。
102
+ """
103
+ status, resp = self._post("/ath/agents/register", {
104
+ "name": account,
105
+ "registration_proof": registration_credential,
106
+ "scopes": scopes or ["a2a:discover"],
107
+ })
108
+ if status != 200:
109
+ raise ATHError("注册失败", status, resp)
110
+ self.client_id = resp.get("client_id", self.client_id)
111
+ self.client_secret = resp.get("client_secret", self.client_secret)
112
+ self.client_did = resp.get("did", self.client_did)
113
+ return resp
114
+
115
+ # ---- 步骤 1-4:握手与身份互验 ----
116
+ def handshake(self):
117
+ """发起握手并完成身份证明(proof = HMAC-SHA256(client_secret, 服务端 nonce))。"""
118
+ if not (self.client_id and self.client_secret and self.client_did):
119
+ raise ATHError("缺少客户端凭证,请先 register() 或配置 ATH_CLIENT_* 环境变量")
120
+ status, hr = self._post("/ath/handshake/init",
121
+ {"client_did": self.client_did,
122
+ "nonce": os.urandom(16).hex()})
123
+ if status != 200 or hr.get("type") != "handshake_response":
124
+ raise ATHError("握手发起失败", status, hr)
125
+ self.hs_id = hr["hs_id"]
126
+ proof = hmac.new(self.client_secret.encode(), hr["nonce"].encode(),
127
+ hashlib.sha256).hexdigest()
128
+ status, ir = self._post("/ath/handshake/verify",
129
+ {"hs_id": self.hs_id, "client_id": self.client_id,
130
+ "proof": proof})
131
+ if status != 200 or not ir.get("success"):
132
+ raise ATHError("身份验证未通过", status, ir)
133
+ return ir
134
+
135
+ # ---- 步骤 5-6:授权请求 ----
136
+ def request_scopes(self, scopes, user_id):
137
+ """请求权限,返回 request_id。越权项由网关三方交集拦截。"""
138
+ if not self.hs_id:
139
+ raise ATHError("请先完成 handshake()")
140
+ status, ar = self._post("/ath/auth/request",
141
+ {"hs_id": self.hs_id, "client_id": self.client_id,
142
+ "user_id": user_id, "scopes": list(scopes)})
143
+ if status != 200:
144
+ raise ATHError("授权请求失败", status, ar)
145
+ self.request_id = ar["request_id"]
146
+ return self.request_id
147
+
148
+ # ---- 步骤 7-8:用户确认(三方权限交集)----
149
+ def confirm(self, approved_scopes, confirm_credential=None):
150
+ """用户侧确认,返回三方交集后的最终权限。
151
+
152
+ confirm_credential 为网关运营方就本次请求动态签发的确认凭证
153
+ (HMAC-SHA256(确认密钥, "confirm:" + request_id + ":" + user_id)),
154
+ 经邮箱等带外通道获取;网关未启用确认证明校验时可省略。
155
+ """
156
+ if not self.request_id:
157
+ raise ATHError("请先 request_scopes()")
158
+ body = {"request_id": self.request_id, "approved": True,
159
+ "scopes": list(approved_scopes)}
160
+ if confirm_credential:
161
+ body["confirmation_proof"] = confirm_credential
162
+ status, pa = self._post("/ath/auth/confirm", body)
163
+ if status != 200:
164
+ raise ATHError("授权确认失败", status, pa)
165
+ self.final_scopes = pa.get("scope_intersection", {}).get("final", [])
166
+ return self.final_scopes
167
+
168
+ # ---- 步骤 9:令牌 ----
169
+ def get_token(self):
170
+ """凭 request_id 换取访问令牌(默认 TTL 3600s,自动缓存)。"""
171
+ if self._token and time.time() < self._token_exp - 30:
172
+ return self._token
173
+ if not self.request_id:
174
+ raise ATHError("请先完成授权确认")
175
+ # P7 对齐: 令牌颁发绑定客户端身份——client_id + 对 request_id 的
176
+ # client_secret 证明, 防止凭泄露的 request_id 截取令牌
177
+ client_proof = hmac.new(self.client_secret.encode(),
178
+ ("token:" + self.request_id).encode(),
179
+ hashlib.sha256).hexdigest()
180
+ status, tr = self._post("/ath/token", {"request_id": self.request_id,
181
+ "client_id": self.client_id,
182
+ "client_proof": client_proof})
183
+ if status != 200 or not tr.get("access_token", "").startswith("ath_"):
184
+ raise ATHError("令牌颁发失败", status, tr)
185
+ self._token = tr["access_token"]
186
+ self._token_exp = time.time() + int(tr.get("expires_in", 3600))
187
+ return self._token
188
+
189
+ # ---- 受保护访问与吊销 ----
190
+ def protected(self, path):
191
+ """带令牌访问受保护端点(如 /ath/protected/ping)。"""
192
+ token = self.get_token()
193
+ status, resp = self._get(path, {"Authorization": "Bearer " + token})
194
+ if status != 200:
195
+ raise ATHError("受保护访问失败", status, resp)
196
+ return resp
197
+
198
+ def revoke(self):
199
+ """吊销当前令牌,吊销后立即失效。"""
200
+ if not self._token:
201
+ return
202
+ self._post("/ath/token/revoke", {},
203
+ {"Authorization": "Bearer " + self._token})
204
+ self._token = None
205
+ self._token_exp = 0.0
206
+
207
+ # ---- 一步到位 ----
208
+ def ready(self, scopes=("a2a:discover",), user_id="user-default",
209
+ confirm_credential=None):
210
+ """发现 → 握手 → 授权 → 确认 → 令牌,返回自身(已就绪)。"""
211
+ self.discover()
212
+ self.handshake()
213
+ self.request_scopes(scopes, user_id)
214
+ self.confirm(scopes, confirm_credential=confirm_credential)
215
+ self.get_token()
216
+ return self
217
+
218
+
219
+ def connect(gateway, scopes=("a2a:discover",), user_id="user-default",
220
+ client_id=None, client_secret=None, client_did=None,
221
+ confirm_credential=None, timeout=DEFAULT_TIMEOUT):
222
+ """一步到位:创建客户端并完成到令牌为止的全流程,返回已就绪的 ATHConnector。"""
223
+ c = ATHConnector(gateway, client_id=client_id, client_secret=client_secret,
224
+ client_did=client_did, timeout=timeout)
225
+ return c.ready(scopes=scopes, user_id=user_id,
226
+ confirm_credential=confirm_credential)
@@ -0,0 +1,109 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """ATH SDK —— LangChain 工具集成(可选增强)
4
+
5
+ 把已就绪的 ATHConnector 包装成 LangChain 智能体可直接调用的工具,
6
+ 让 AI 智能体在可信握手治理下访问受保护资源。
7
+
8
+ 主包保持零依赖:未安装 langchain-core 时,本模块以独立模式工作
9
+ (工具逻辑完整可用,只是不能直接挂进 LangChain 智能体);
10
+ 安装后(pip install "athsdk[langchain]")自动成为标准 LangChain 工具。
11
+
12
+ 用法:
13
+ from ath_sdk import connect
14
+ from ath_sdk.langchain_tool import ATHAgentTool
15
+
16
+ agent = connect("https://gateway.example.com", client_id=..., client_secret=...)
17
+ tool = ATHAgentTool(connector=agent)
18
+ # 独立调用:tool.invoke({"path": "/ath/protected/ping"})
19
+ # LangChain 智能体:tools = make_ath_tools(agent) 后传入 create_react_agent 等
20
+ """
21
+ import json
22
+
23
+ from .client import ATHConnector, ATHError
24
+
25
+ __all__ = ["ATHAgentTool", "make_ath_tools"]
26
+
27
+ _IMPORT_HINT = (
28
+ "要挂进 LangChain 智能体需安装 langchain-core:"
29
+ 'pip install "athsdk[langchain]"(或 pip install langchain-core);'
30
+ "独立调用工具逻辑无需安装。"
31
+ )
32
+
33
+ try:
34
+ from langchain_core.tools import BaseTool
35
+ except ImportError: # pragma: no cover - 依赖缺失时走独立模式
36
+ try:
37
+ from langchain.tools import BaseTool # 旧版 langchain 兜底
38
+ except ImportError:
39
+ BaseTool = None
40
+
41
+
42
+ class _ATHToolCore:
43
+ """工具核心逻辑:路径校验、鉴权转发、错误回包。与框架无关。"""
44
+
45
+ name = "ath_request"
46
+ description = (
47
+ "通过 ATH 可信握手协议访问网关受保护资源。"
48
+ "输入为 JSON:{\"path\": \"/ath/protected/ping\"}。"
49
+ "仅可访问网关发现文档中列出的受保护端点。"
50
+ )
51
+
52
+ def __init__(self, connector, allowed_prefixes=("/ath/protected/",)):
53
+ if not hasattr(connector, "protected"):
54
+ raise TypeError("connector 须提供 protected(path) 方法(ATHConnector 或兼容实现)")
55
+ self.connector = connector
56
+ self.allowed_prefixes = tuple(allowed_prefixes)
57
+
58
+ def _run(self, query):
59
+ try:
60
+ args = json.loads(query) if isinstance(query, str) else dict(query)
61
+ except (json.JSONDecodeError, TypeError):
62
+ return json.dumps({"error": "输入须为 JSON 对象,含 path 字段"},
63
+ ensure_ascii=False)
64
+ path = args.get("path", "")
65
+ if not path.startswith("/"):
66
+ return json.dumps({"error": "path 必须以 / 开头"}, ensure_ascii=False)
67
+ if self.allowed_prefixes and not path.startswith(self.allowed_prefixes):
68
+ return json.dumps({
69
+ "error": "path 不在允许范围内,仅可访问:%s"
70
+ % ", ".join(self.allowed_prefixes),
71
+ }, ensure_ascii=False)
72
+ try:
73
+ resp = self.connector.protected(path)
74
+ return json.dumps(resp, ensure_ascii=False)
75
+ except ATHError as e:
76
+ return json.dumps({"error": str(e), "status": e.status},
77
+ ensure_ascii=False)
78
+
79
+ def invoke(self, query):
80
+ """独立模式下的调用入口;挂进 LangChain 后由框架接管。"""
81
+ return self._run(query)
82
+
83
+
84
+ if BaseTool is not None:
85
+ class ATHAgentTool(_ATHToolCore, BaseTool):
86
+ """LangChain 工具:经 ATH 可信握手访问网关受保护端点。"""
87
+
88
+ connector: object
89
+ allowed_prefixes: tuple
90
+
91
+ def __init__(self, connector, allowed_prefixes=("/ath/protected/",)):
92
+ _ATHToolCore.__init__(self, connector, allowed_prefixes)
93
+ super().__init__(connector=connector,
94
+ allowed_prefixes=self.allowed_prefixes)
95
+ else:
96
+ class ATHAgentTool(_ATHToolCore):
97
+ """独立模式工具:逻辑完整可用,挂 LangChain 需安装 langchain-core。"""
98
+
99
+ def __init__(self, connector, allowed_prefixes=("/ath/protected/",)):
100
+ _ATHToolCore.__init__(self, connector, allowed_prefixes)
101
+
102
+
103
+ def make_ath_tools(connector, allowed_prefixes=("/ath/protected/",)):
104
+ """把 ATHConnector 包装为工具列表(已就绪的连接器)。
105
+
106
+ allowed_prefixes 限定智能体可访问的路径前缀,默认仅放行
107
+ /ath/protected/ 下的端点,防止智能体越权访问网关管理接口。
108
+ """
109
+ return [ATHAgentTool(connector, allowed_prefixes=allowed_prefixes)]
ath_sdk/mcp_server.py ADDED
@@ -0,0 +1,242 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """ATH SDK —— MCP 服务模块(可选增强)
4
+
5
+ 把 ATH 可信握手能力以标准 MCP(Model Context Protocol)服务对外提供,
6
+ 一份服务覆盖所有支持 MCP 的客户端与平台:DSH、华为九问、Dify、Coze、
7
+ Claude Desktop、Cursor、阿里百炼、百度千帆等。
8
+
9
+ 主包保持零依赖:本模块顶层不导入 mcp;
10
+ 构建 MCP 服务实例时才需要安装(pip install "athsdk[mcp]")。
11
+
12
+ 工具一览:
13
+ ath_handshake 发现 → 握手 → 授权 → 确认 → 令牌,一步就绪
14
+ ath_request 带令牌访问网关受保护端点(默认仅 /ath/protected/ 前缀)
15
+ ath_verify 校验当前会话令牌是否有效
16
+ ath_status 查看接入配置与令牌状态(不回显任何密钥)
17
+
18
+ 配置(环境变量):
19
+ ATH_GATEWAY 网关地址(必填)
20
+ ATH_CLIENT_ID / ATH_CLIENT_SECRET / ATH_CLIENT_DID 客户端凭证
21
+ ATH_USER_ID 授权主体用户(默认 user-default)
22
+ ATH_USER_CONFIRM_SECRET 用户确认密钥:设置后由本服务就每次授权请求
23
+ 现算确认证明(运营方与接入方同域部署时适用)
24
+ ATH_MCP_ALLOWED_PREFIXES 受保护路径白名单前缀(逗号分隔,默认 /ath/protected/)
25
+
26
+ 运行:
27
+ python -m ath_sdk.mcp_server # stdio(桌面客户端)
28
+ python -m ath_sdk.mcp_server --transport streamable-http --port 9131
29
+ """
30
+ import hashlib
31
+ import hmac
32
+ import json
33
+ import os
34
+ import time
35
+
36
+ from .client import ATHConnector, ATHError, __version__
37
+
38
+ __all__ = ["ATHMCPTools", "build_mcp_server", "main"]
39
+
40
+ _IMPORT_HINT = (
41
+ "构建 MCP 服务需安装官方 MCP Python SDK:"
42
+ 'pip install "athsdk[mcp]"(或 pip install mcp);'
43
+ "工具核心逻辑无需安装即可独立测试。"
44
+ )
45
+
46
+ DEFAULT_ALLOWED_PREFIXES = ("/ath/protected/",)
47
+
48
+
49
+ class ATHMCPTools:
50
+ """MCP 四工具的核心逻辑。与框架无关,可独立实例化与测试。
51
+
52
+ connector 可注入桩实现(测试)或预配置的 ATHConnector;
53
+ 缺省时按环境变量惰性创建。
54
+ """
55
+
56
+ def __init__(self, connector=None, allowed_prefixes=None,
57
+ user_confirm_secret=None):
58
+ self._connector = connector
59
+ prefixes = allowed_prefixes
60
+ if prefixes is None:
61
+ env = os.environ.get("ATH_MCP_ALLOWED_PREFIXES", "")
62
+ prefixes = [p.strip() for p in env.split(",") if p.strip()] \
63
+ if env else None
64
+ self.allowed_prefixes = tuple(prefixes or DEFAULT_ALLOWED_PREFIXES)
65
+ secret = user_confirm_secret
66
+ if secret is None:
67
+ secret = os.environ.get("ATH_USER_CONFIRM_SECRET", "")
68
+ self._confirm_secret = secret.encode() if secret else None
69
+
70
+ # ---- 连接器管理 ----
71
+ def _get_connector(self):
72
+ if self._connector is None:
73
+ gateway = os.environ.get("ATH_GATEWAY", "")
74
+ if not gateway:
75
+ raise ATHError("缺少网关地址:请设置 ATH_GATEWAY 环境变量")
76
+ self._connector = ATHConnector(gateway)
77
+ return self._connector
78
+
79
+ def _confirm_credential(self, request_id, user_id):
80
+ """就本次授权请求现算确认证明;未配置确认密钥时返回 None。"""
81
+ if not self._confirm_secret:
82
+ return None
83
+ return hmac.new(self._confirm_secret,
84
+ ("confirm:" + request_id + ":" + user_id).encode(),
85
+ hashlib.sha256).hexdigest()
86
+
87
+ def _run_full_flow(self, scopes, user_id):
88
+ """发现 → 握手 → 授权请求 → 确认 → 令牌。返回 (connector, 明细)。"""
89
+ c = self._get_connector()
90
+ detail = {"discover": False, "handshake": False,
91
+ "auth_request": False, "confirm": False, "token": False}
92
+ c.discover()
93
+ detail["discover"] = True
94
+ c.handshake()
95
+ detail["handshake"] = True
96
+ c.request_scopes(scopes, user_id)
97
+ detail["auth_request"] = True
98
+ c.confirm(scopes, confirm_credential=self._confirm_credential(
99
+ c.request_id, user_id))
100
+ detail["confirm"] = True
101
+ c.get_token()
102
+ detail["token"] = True
103
+ return c, detail
104
+
105
+ # ---- 工具 1:握手就绪 ----
106
+ def ath_handshake(self, scopes=None, user_id=None):
107
+ """执行完整九步流程到令牌就绪。返回 JSON 文本(不含任何密钥)。"""
108
+ scopes = list(scopes) if scopes else ["a2a:discover"]
109
+ user_id = user_id or os.environ.get("ATH_USER_ID", "user-default")
110
+ try:
111
+ c, detail = self._run_full_flow(scopes, user_id)
112
+ return json.dumps({
113
+ "ok": True, "steps": detail,
114
+ "hs_id": c.hs_id,
115
+ "final_scopes": c.final_scopes,
116
+ "expires_in": max(0, int(c._token_exp - time.time())),
117
+ }, ensure_ascii=False)
118
+ except ATHError as e:
119
+ return json.dumps({"ok": False, "error": str(e),
120
+ "status": e.status}, ensure_ascii=False)
121
+
122
+ # ---- 工具 2:受保护请求 ----
123
+ def ath_request(self, path):
124
+ """带令牌访问网关受保护端点。路径须在白名单前缀内。"""
125
+ if not isinstance(path, str) or not path.startswith("/"):
126
+ return json.dumps({"error": "path 必须以 / 开头"},
127
+ ensure_ascii=False)
128
+ if self.allowed_prefixes and not path.startswith(self.allowed_prefixes):
129
+ return json.dumps({
130
+ "error": "path 不在允许范围内,仅可访问:%s"
131
+ % ", ".join(self.allowed_prefixes),
132
+ }, ensure_ascii=False)
133
+ try:
134
+ resp = self._get_connector().protected(path)
135
+ return json.dumps(resp, ensure_ascii=False)
136
+ except ATHError as e:
137
+ return json.dumps({"error": str(e), "status": e.status},
138
+ ensure_ascii=False)
139
+
140
+ # ---- 工具 3:令牌校验 ----
141
+ def ath_verify(self):
142
+ """校验当前会话令牌是否有效(本地到期检查,不外发请求)。"""
143
+ try:
144
+ c = self._get_connector()
145
+ except ATHError as e:
146
+ return json.dumps({"verified": False, "error": str(e)},
147
+ ensure_ascii=False)
148
+ has_token = bool(c._token)
149
+ valid = has_token and time.time() < c._token_exp - 30
150
+ return json.dumps({
151
+ "verified": valid,
152
+ "has_token": has_token,
153
+ "expires_in": max(0, int(c._token_exp - time.time()))
154
+ if has_token else 0,
155
+ "hint": None if valid else "令牌缺失或已过期,请调用 ath_handshake 重新就绪",
156
+ }, ensure_ascii=False)
157
+
158
+ # ---- 工具 4:状态 ----
159
+ def ath_status(self):
160
+ """查看接入配置与状态。只报有无,不回显任何密钥。"""
161
+ gateway = os.environ.get("ATH_GATEWAY", "")
162
+ try:
163
+ c = self._get_connector()
164
+ except ATHError:
165
+ c = None
166
+ has_token = bool(c and c._token)
167
+ return json.dumps({
168
+ "sdk_version": __version__,
169
+ "gateway_configured": bool(gateway),
170
+ "client_id_configured": bool(c and c.client_id),
171
+ "did_configured": bool(c and c.client_did),
172
+ "confirm_secret_configured": bool(self._confirm_secret),
173
+ "token_cached": has_token,
174
+ "token_expires_in": max(0, int(c._token_exp - time.time()))
175
+ if has_token else 0,
176
+ "allowed_prefixes": list(self.allowed_prefixes),
177
+ }, ensure_ascii=False)
178
+
179
+
180
+ def build_mcp_server(name="athsdk", connector=None, allowed_prefixes=None):
181
+ """构建 FastMCP 服务实例。需要 mcp 包(pip install "athsdk[mcp]")。"""
182
+ try:
183
+ from mcp.server.fastmcp import FastMCP
184
+ except ImportError as e:
185
+ raise RuntimeError(_IMPORT_HINT) from e
186
+
187
+ tools = ATHMCPTools(connector=connector,
188
+ allowed_prefixes=allowed_prefixes)
189
+ mcp = FastMCP(name)
190
+
191
+ @mcp.tool()
192
+ def ath_handshake(scopes: list = None, user_id: str = None) -> str:
193
+ """执行 ATH 九步可信握手到令牌就绪(发现→握手→授权→确认→令牌)。"""
194
+ return tools.ath_handshake(scopes=scopes, user_id=user_id)
195
+
196
+ @mcp.tool()
197
+ def ath_request(path: str) -> str:
198
+ """带令牌访问网关受保护端点,如 /ath/protected/ping。"""
199
+ return tools.ath_request(path)
200
+
201
+ @mcp.tool()
202
+ def ath_verify() -> str:
203
+ """校验当前 ATH 会话令牌是否有效。"""
204
+ return tools.ath_verify()
205
+
206
+ @mcp.tool()
207
+ def ath_status() -> str:
208
+ """查看 ATH 接入配置与令牌状态(不回显密钥)。"""
209
+ return tools.ath_status()
210
+
211
+ return mcp
212
+
213
+
214
+ def main(argv=None):
215
+ """命令行入口:python -m ath_sdk.mcp_server [--transport ...] [--port ...]"""
216
+ import argparse
217
+ p = argparse.ArgumentParser(
218
+ prog="python -m ath_sdk.mcp_server",
219
+ description="ATH 可信握手 MCP 服务(stdio / streamable-http)")
220
+ p.add_argument("--transport", choices=["stdio", "streamable-http"],
221
+ default="stdio", help="传输方式,默认 stdio")
222
+ p.add_argument("--host", default="127.0.0.1",
223
+ help="streamable-http 监听地址")
224
+ p.add_argument("--port", type=int, default=9131,
225
+ help="streamable-http 监听端口")
226
+ p.add_argument("--name", default="athsdk", help="MCP 服务名")
227
+ args = p.parse_args(argv)
228
+
229
+ if args.transport == "streamable-http":
230
+ server = build_mcp_server(
231
+ name=args.name,
232
+ allowed_prefixes=None)
233
+ server.settings.host = args.host
234
+ server.settings.port = args.port
235
+ server.run(transport="streamable-http")
236
+ else:
237
+ server = build_mcp_server(name=args.name)
238
+ server.run()
239
+
240
+
241
+ if __name__ == "__main__":
242
+ main()
@@ -0,0 +1,184 @@
1
+ Metadata-Version: 2.4
2
+ Name: ath-sdk-python
3
+ Version: 0.1.0
4
+ Summary: ATH 1.0 智能体可信握手客户端 SDK(Agent Trust Handshake)——纯标准库,零第三方依赖
5
+ License: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/tanbopiao/ath-sdk-python
7
+ Project-URL: Conformance, https://github.com/tanbopiao/ath-conformance-suite
8
+ Keywords: ath,agent,handshake,authentication,security,a2a
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Security
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Requires-Python: >=3.8
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Provides-Extra: langchain
22
+ Requires-Dist: langchain-core>=0.1; extra == "langchain"
23
+ Provides-Extra: mcp
24
+ Requires-Dist: mcp<2,>=1.0; extra == "mcp"
25
+ Dynamic: license-file
26
+
27
+ <!-- mcp-name: io.github.tanbopiao/athsdk -->
28
+ # ATH SDK(Python)—— 智能体可信握手客户端
29
+
30
+ 对接 [ATH 1.0](https://www.caict.ac.cn)(智能体可信握手协议,Agent Trust Handshake Protocol,schema 0.1)网关的轻量客户端 SDK。
31
+
32
+ **纯 Python 标准库,零第三方依赖,Python 3.8+,核心就一个文件**——不想装包的话,把 [`ath_sdk/client.py`](ath_sdk/client.py) 直接拷进你的项目也能用。
33
+
34
+ ## 为什么需要它
35
+
36
+ 智能体之间、智能体与服务之间通信前,先「验明身份、讲清权限、再放行」——这就是 ATH 九步可信握手:
37
+
38
+ ```
39
+ 发现 → 注册 → 握手互验 → 授权请求 → 三方权限交集确认 → 令牌 → 受保护访问 → 吊销
40
+ ```
41
+
42
+ 三方权限交集(Agent 请求 ∩ 用户同意 ∩ 服务策略)保证:客户端要得再多,用户没同意、服务方不允许的权限都拿不到。
43
+
44
+ ## 安装
45
+
46
+ ```bash
47
+ pip install ath-sdk-python # 从 PyPI 安装
48
+ # 或直接拷贝单文件:
49
+ cp ath_sdk/client.py your_project/ath_client.py
50
+ ```
51
+
52
+ ## 十分钟上手
53
+
54
+ ```python
55
+ from ath_sdk import ATHConnector
56
+
57
+ agent = ATHConnector("https://gateway.example.com")
58
+
59
+ # 1. 注册(首次):用网关运营方发放的注册凭证
60
+ agent.register("your-account", "<注册凭证>", scopes=["a2a:discover"])
61
+ # 返回 client_id / client_secret / did,请妥善保存(client_secret 仅注册时返回一次)
62
+
63
+ # 2. 完成握手与授权(每次会话)
64
+ agent.discover()
65
+ agent.handshake()
66
+ agent.request_scopes(["a2a:discover"], user_id="user-xxx")
67
+
68
+ # 3. 用户确认:确认凭证由网关运营方就本次请求动态签发(邮箱等带外通道获取)
69
+ agent.confirm(["a2a:discover"], confirm_credential="<确认凭证>")
70
+
71
+ # 4. 拿令牌、访问受保护资源
72
+ agent.get_token()
73
+ agent.protected("/ath/protected/ping")
74
+
75
+ # 5. 用完即吊销
76
+ agent.revoke()
77
+ ```
78
+
79
+ 或一步到位:
80
+
81
+ ```python
82
+ from ath_sdk import connect
83
+
84
+ agent = connect("https://gateway.example.com",
85
+ client_id="...", client_secret="...", client_did="did:ath:...",
86
+ user_id="user-xxx", confirm_credential="<确认凭证>")
87
+ agent.protected("/ath/protected/ping")
88
+ ```
89
+
90
+ 已注册的凭证也可走环境变量:`ATH_CLIENT_ID` / `ATH_CLIENT_SECRET` / `ATH_CLIENT_DID`。
91
+
92
+ ## 命令行自检
93
+
94
+ ```bash
95
+ python -m ath_sdk --gateway https://gateway.example.com --action discover # 只读发现
96
+ python -m ath_sdk --gateway https://gateway.example.com --action handshake # 握手互验(需凭证)
97
+ ```
98
+
99
+ ## API 一览
100
+
101
+ | 方法 | 对应步骤 | 说明 |
102
+ | --- | --- | --- |
103
+ | `discover()` | 0 | 读取 `/.well-known/ath.json`,记录支持的权限 |
104
+ | `register(account, credential, scopes)` | — | 注册身份,取得 client_id / client_secret / DID |
105
+ | `handshake()` | 1–4 | 握手发起 + HMAC-SHA256 身份互验 |
106
+ | `request_scopes(scopes, user_id)` | 5–6 | 授权请求,返回 request_id |
107
+ | `confirm(scopes, confirm_credential)` | 7–8 | 用户确认,返回三方交集后的最终权限 |
108
+ | `get_token()` | 9 | 换取访问令牌(自动缓存,TTL 3600s) |
109
+ | `protected(path)` | — | 带令牌访问受保护端点 |
110
+ | `revoke()` | — | 吊销令牌,立即失效 |
111
+ | `ready(...)` / `connect(...)` | 0–9 | 一步到位 |
112
+
113
+ ## LangChain 智能体集成(可选)
114
+
115
+ 把已就绪的连接器包成 LangChain 工具,让 AI 智能体在可信握手治理下访问受保护资源:
116
+
117
+ ```bash
118
+ pip install "ath-sdk-python[langchain]" # 可选增强;不装也不影响主包零依赖
119
+ ```
120
+
121
+ ```python
122
+ from ath_sdk import connect
123
+ from ath_sdk.langchain_tool import make_ath_tools
124
+
125
+ agent = connect("https://gateway.example.com", client_id=..., client_secret=...)
126
+ tools = make_ath_tools(agent) # 默认仅放行 /ath/protected/ 前缀
127
+ # 传入 create_react_agent 等;或独立调用:tools[0].invoke({"path": "/ath/protected/ping"})
128
+ ```
129
+
130
+ 未安装 langchain-core 时工具以独立模式工作(逻辑完整,只是不能挂进智能体框架);
131
+ `allowed_prefixes` 参数可收窄智能体可访问的端点范围,防止越权。完整示例见 `examples/langchain_agent.py`。
132
+
133
+ ## MCP 服务(可选)
134
+
135
+ 把 ATH 能力以标准 MCP 服务对外提供,一份服务覆盖所有支持 MCP 的客户端与平台
136
+ (DSH、华为九问、Dify、Coze、Claude Desktop、Cursor、阿里百炼、百度千帆等):
137
+
138
+ ```bash
139
+ pip install "ath-sdk-python[mcp]" # 可选增强;不装也不影响主包零依赖
140
+
141
+ # stdio(桌面客户端 / DSH / 九问本地拉起)
142
+ ATH_GATEWAY=https://gateway.example.com \
143
+ ATH_CLIENT_ID=... ATH_CLIENT_SECRET=... ATH_CLIENT_DID=... \
144
+ python -m ath_sdk.mcp_server
145
+
146
+ # streamable-http(远程平台:百炼 / 千帆工作流 / Dify 等)
147
+ python -m ath_sdk.mcp_server --transport streamable-http --port 9131
148
+ ```
149
+
150
+ 四个工具:`ath_handshake`(九步到令牌一步就绪)、`ath_request`(带令牌访问受保护端点,
151
+ 默认仅放行 `/ath/protected/` 前缀)、`ath_verify`(令牌校验)、`ath_status`(配置与令牌状态,密钥零回显)。
152
+
153
+ 配置走环境变量:`ATH_GATEWAY`、`ATH_CLIENT_ID/SECRET/DID`、`ATH_USER_ID`、
154
+ `ATH_USER_CONFIRM_SECRET`(设置后由服务就每次授权请求现算确认证明)、
155
+ `ATH_MCP_ALLOWED_PREFIXES`(路径白名单,逗号分隔)。
156
+
157
+ ### 集成矩阵
158
+
159
+ | 接入面 | 方式 | 状态 |
160
+ | --- | --- | --- |
161
+ | LangChain / LangGraph | `athsdk[langchain]` 工具集成 | ✅ 已验证(真实网关端到端) |
162
+ | DeepSeek Harness(DSH) | `athsdk[mcp]` MCP 服务(stdio) | ✅ 已验证(dsh-mcp-client 桥接实测 9/9,见 [docs/dsh-integration.md](docs/dsh-integration.md)) |
163
+ | 九问(openJiuwen / JiuwenSwarm) | `athsdk[mcp]` MCP 服务(stdio) | ✅ 已验证(openjiuwen StdioClient 实测 8/8,见 [docs/jiuwen-integration.md](docs/jiuwen-integration.md)) |
164
+ | MCP 客户端与平台(Dify / Coze / Claude Desktop / Cursor / 百炼 / 千帆等) | `athsdk[mcp]` MCP 服务(stdio + streamable-http) | ✅ 已验证(本地网关端到端 8/8;配置样例见 [docs/clients-platforms.md](docs/clients-platforms.md)) |
165
+ | LlamaIndex / AutoGen / OpenAI Agents SDK / CrewAI | 各框架 MCP 客户端接入本服务 | 按需薄适配 |
166
+
167
+ ## 安全约定
168
+
169
+ - **凭证外置**:`client_secret` 只在注册响应中返回一次,SDK 不落盘、不打印;建议用环境变量传入。
170
+ - **确认凭证动态签发**:每次授权请求由网关运营方就 `request_id + user_id` 现算现发,无法预置或重放——这是三方权限交集设计的一部分。
171
+ - **最小权限**:只请求业务需要的 scope;越权项会被网关三方交集拦截。
172
+
173
+ ## 配套工具
174
+
175
+ - 一致性测试套件:[ath-conformance-suite](https://github.com/tanbopiao/ath-conformance-suite) —— 对任意 ATH 1.0 网关做端到端一致性验证(13 项检查,可接 CI)。
176
+ - 参考网关实现:[agent-community-gateway](https://github.com/tanbopiao/agent-community-gateway) —— ATH 1.0 网关的产品与评估文档集,含网关参考实现、演示接入指南与实测指标,本 SDK 的对接目标即此协议。
177
+
178
+ ## 声明
179
+
180
+ 本 SDK 是「对齐信通院 ATH 1.0 规范的实践者」实现的客户端库,非中国信通院官方组件;对接官方评估请以信通院发布为准。
181
+
182
+ ## License
183
+
184
+ Apache-2.0
@@ -0,0 +1,10 @@
1
+ ath_sdk/__init__.py,sha256=UC3obvA7dJjbmw5PdvSxGRD9K-3CrTECTuVYVtRIgGI,546
2
+ ath_sdk/__main__.py,sha256=Qe5nonLvE6HylMQEY74bZfL-mUxpQAUtrxT9vdLeDgU,1171
3
+ ath_sdk/client.py,sha256=U5sPwoaWWyQcRe1cbwEc6iAZ-kkaoK1o2P8IlA_3m6I,10296
4
+ ath_sdk/langchain_tool.py,sha256=vkK6PizNrPs7GEDFo-W2rFZB0Y07yGm323tP7ith_5c,4489
5
+ ath_sdk/mcp_server.py,sha256=cpvRryDJB1wBi8F08pNGILiXbgSnuqw4-j9Z3jM0TmQ,10047
6
+ ath_sdk_python-0.1.0.dist-info/licenses/LICENSE,sha256=fs2M4dMLiqJiMvXHyHjMpTvCc1R85S8WePlVFUdG5k8,709
7
+ ath_sdk_python-0.1.0.dist-info/METADATA,sha256=8Y3HAoKn12wzfpSxTLoFzOoVX3GMOFzSCY7BJeUq1pA,8444
8
+ ath_sdk_python-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ ath_sdk_python-0.1.0.dist-info/top_level.txt,sha256=tgxYBGbTHekjU6YZ_wSLzd2WdR4jo369XJBkp5-WG6k,8
10
+ ath_sdk_python-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,15 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
@@ -0,0 +1 @@
1
+ ath_sdk