Repository navigation
Expand file tree
/
Copy pathclient.py
More file actions
314 lines (265 loc) · 11.4 KB
/
Copy pathclient.py
File metadata and controls
314 lines (265 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""
FeishuAPI — Base class for Feishu API wrappers with auto-auth.
Provides authenticated HTTP requests via Device Flow OAuth (UAT).
Service-specific subclasses define their own scopes and convenience methods.
Usage:
class MyService(FeishuAPI):
SCOPES = ["my:scope:read"]
BASE_PATH = "/open-apis/my/v1"
"""
import json
import logging
import time
import uuid
from typing import Optional
import requests
from feishu_bridge.api.auth import FeishuAuth
log = logging.getLogger("feishu-api")
# MCP endpoint for Feishu (used by Docs)
MCP_ENDPOINT = "https://mcp.feishu.cn/mcp"
class FeishuAPIError(Exception):
"""Raised when a Feishu API returns an error."""
def __init__(self, code: int, msg: str, path: str = ""):
self.code = code
self.msg = msg
self.path = path
super().__init__(f"Feishu API error {code}: {msg} (path={path})")
class FeishuAPI:
"""Base class for Feishu API wrappers with auto-auth via Device Flow OAuth.
Subclasses should define:
SCOPES: list[str] — required OAuth scopes
BASE_PATH: str — API path prefix (e.g., "/open-apis/task/v2")
"""
SCOPES: list[str] = []
BASE_PATH: str = ""
def __init__(self, app_id: str, app_secret: str, lark_client=None,
token_override: str = None):
self.auth = FeishuAuth(app_id, app_secret, lark_client)
self.app_id = app_id
self.app_secret = app_secret
self._token_override = token_override
def get_token(self, chat_id: str, user_open_id: str) -> Optional[str]:
"""Get a valid UAT, triggering auth flow if needed.
If token_override was set at init time, returns it directly
(used by CLI where auth file provides a pre-authed token).
"""
if self._token_override is not None:
return self._token_override
return self.auth.ensure_user_token(chat_id, user_open_id, self.SCOPES)
def get_cached_token(self, user_open_id: str) -> Optional[str]:
"""Return a valid UAT from cache/refresh only — never prompts.
Used by background features (auto-fetch URLs) that should not
interrupt the user with an auth card. Does NOT check scopes —
auto-fetch only performs reads, and the server enforces scope
boundaries, so any valid token is sufficient here.
"""
if self._token_override is not None:
return self._token_override
return self.auth.get_valid_token(user_open_id)
def cleanup_auth_card(self, user_open_id: str) -> bool:
"""Delete the auth card sent during OAuth flow (if any).
Call after delivering the main result so the auth card doesn't
remain as the last visible message in chat.
"""
return self.auth.cleanup_auth_card(user_open_id)
# HTTP status codes that warrant automatic retry
_RETRYABLE_HTTP = {429, 500, 502, 503, 504}
_MAX_RETRIES = 3
def request(self, method: str, path: str, token: str,
params: dict = None, json_body: dict = None) -> dict:
"""Make an authenticated OAPI request with retry on transient errors.
Retries up to _MAX_RETRIES times on 429/5xx with exponential backoff.
"""
url = f"https://open.feishu.cn{self.BASE_PATH}{path}"
last_exc = None
for attempt in range(self._MAX_RETRIES + 1):
try:
headers = {"Authorization": f"Bearer {token}"}
if json_body is not None:
headers["Content-Type"] = "application/json; charset=utf-8"
resp = requests.request(
method, url,
headers=headers,
params=params,
json=json_body,
timeout=15,
)
except requests.exceptions.Timeout:
last_exc = FeishuAPIError(-1, "Request timeout", path)
if attempt < self._MAX_RETRIES:
time.sleep(2 ** attempt)
continue
raise last_exc
except requests.exceptions.ConnectionError as e:
last_exc = FeishuAPIError(-1, f"Connection error: {e}", path)
if attempt < self._MAX_RETRIES:
time.sleep(2 ** attempt)
continue
raise last_exc
# Retry on transient HTTP errors
if resp.status_code in self._RETRYABLE_HTTP and attempt < self._MAX_RETRIES:
retry_after = resp.headers.get("Retry-After")
try:
wait = int(retry_after) if retry_after else 2 ** attempt
except (TypeError, ValueError):
wait = 2 ** attempt
log.warning("HTTP %d on %s, retry %d/%d in %ds",
resp.status_code, path, attempt + 1,
self._MAX_RETRIES, wait)
time.sleep(min(wait, 30))
continue
try:
data = resp.json()
except (ValueError, requests.JSONDecodeError):
raise FeishuAPIError(
resp.status_code,
f"Non-JSON response: {resp.text[:200]}",
path,
)
if data.get("code") != 0:
code = data.get("code")
msg = data.get("msg", "Unknown error")
log.error("API error: code=%s msg=%s url=%s", code, msg, url)
raise FeishuAPIError(code, msg, path)
return data.get("data", {})
# Should not reach here, but just in case
raise last_exc or FeishuAPIError(-1, "Max retries exceeded", path)
def mcp_call(self, tool_name: str, args: dict, token: str) -> dict:
"""Call a Feishu MCP tool (JSON-RPC over HTTPS).
Used by Docs for Markdown read/write via mcp.feishu.cn.
Args:
tool_name: MCP tool name (e.g., "fetch-doc")
args: tool arguments
token: user access token
Returns:
Parsed result from MCP response.
"""
call_id = str(uuid.uuid4())
body = {
"jsonrpc": "2.0",
"id": call_id,
"method": "tools/call",
"params": {
"name": tool_name,
"arguments": args,
},
}
try:
resp = requests.post(
MCP_ENDPOINT,
headers={
"Content-Type": "application/json",
"X-Lark-MCP-UAT": token,
"X-Lark-MCP-Allowed-Tools": tool_name,
},
json=body,
timeout=30,
)
except requests.exceptions.Timeout:
raise FeishuAPIError(0, "MCP request timeout",
f"mcp/{tool_name}")
except requests.exceptions.ConnectionError as e:
raise FeishuAPIError(0, f"MCP connection error: {e}",
f"mcp/{tool_name}")
if not resp.ok:
raise FeishuAPIError(
resp.status_code,
f"MCP HTTP {resp.status_code}: {resp.text[:500]}",
f"mcp/{tool_name}",
)
try:
data = resp.json()
except (ValueError, requests.exceptions.JSONDecodeError):
raise FeishuAPIError(
resp.status_code,
f"Non-JSON MCP response: {resp.text[:200]}",
f"mcp/{tool_name}",
)
# Unwrap JSON-RPC envelope
if "error" in data:
err = data["error"]
raise FeishuAPIError(
err.get("code", -1),
err.get("message", "MCP error"),
f"mcp/{tool_name}",
)
result = data.get("result", data)
# Unwrap (some gateways double-wrap) — depth-limited
max_unwrap = 5
while max_unwrap > 0 and isinstance(result, dict) and "result" in result and "jsonrpc" not in result:
result = result["result"]
max_unwrap -= 1
# Extract text content from MCP response format
if isinstance(result, dict) and "content" in result:
content = result["content"]
if isinstance(content, list) and len(content) == 1:
text = content[0].get("text", "")
try:
return json.loads(text)
except (json.JSONDecodeError, TypeError):
return {"text": text}
# Multiple content blocks
texts = [c.get("text", "") for c in content if isinstance(c, dict)]
return {"texts": texts}
return result
# Drive API base path (independent of subclass BASE_PATH)
DRIVE_BASE = '/open-apis/drive/v1'
def _drive(self, method: str, path: str, token: str,
params: dict = None, json_body: dict = None) -> dict:
"""Drive API request, independent of BASE_PATH.
Used for cross-module operations like file deletion.
"""
url = f'https://open.feishu.cn{self.DRIVE_BASE}{path}'
last_exc = None
for attempt in range(self._MAX_RETRIES + 1):
try:
resp = requests.request(
method, url,
headers={
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json; charset=utf-8',
},
params=params,
json=json_body,
timeout=15,
)
except requests.exceptions.Timeout:
last_exc = FeishuAPIError(-1, 'Request timeout', path)
if attempt < self._MAX_RETRIES:
time.sleep(2 ** attempt)
continue
raise last_exc
except requests.exceptions.ConnectionError as e:
last_exc = FeishuAPIError(-1, f'Connection error: {e}', path)
if attempt < self._MAX_RETRIES:
time.sleep(2 ** attempt)
continue
raise last_exc
if resp.status_code in self._RETRYABLE_HTTP and attempt < self._MAX_RETRIES:
retry_after = resp.headers.get('Retry-After')
try:
wait = int(retry_after) if retry_after else 2 ** attempt
except (TypeError, ValueError):
wait = 2 ** attempt
log.warning('HTTP %d on drive %s, retry %d/%d in %ds',
resp.status_code, path, attempt + 1,
self._MAX_RETRIES, wait)
time.sleep(min(wait, 30))
continue
try:
data = resp.json()
except (ValueError, requests.JSONDecodeError):
raise FeishuAPIError(
resp.status_code,
f'Non-JSON response: {resp.text[:200]}',
path,
)
if data.get('code') != 0:
code = data.get('code')
msg = data.get('msg', 'Unknown error')
log.error('Drive API error: code=%s msg=%s url=%s', code, msg, url)
raise FeishuAPIError(code, msg, path)
return data.get('data', {})
raise last_exc or FeishuAPIError(-1, 'Max retries exceeded', path)
def _auth_failed_message(self) -> str:
return "🔐 已发送授权卡片,请完成授权后重试。"