forked from namejiahui/mcp-boss-zp
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathboss_zhipin_fastmcp_v2.py
More file actions
1269 lines (1046 loc) · 47.6 KB
/
boss_zhipin_fastmcp_v2.py
File metadata and controls
1269 lines (1046 loc) · 47.6 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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Boss直聘 FastMCP 服务器
基于FastMCP文档重新开发的现代化MCP服务器
"""
import asyncio
import json
import os
import time
import base64
import threading
from dataclasses import dataclass, asdict
from typing import Any, Dict, List, Optional, Union
from pathlib import Path
import requests
from fastmcp import FastMCP, Context
from fastmcp.server.dependencies import get_http_request
from starlette.requests import Request
from starlette.responses import JSONResponse, FileResponse
from starlette.staticfiles import StaticFiles
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from Crypto.Random import get_random_bytes
from playwright.async_api import async_playwright
# 数据模型定义
@dataclass
class LoginStatus:
"""登录状态数据模型"""
is_logged_in: bool = False
cookie: Optional[str] = None
bst: Optional[str] = None
qr_id: Optional[str] = None
login_step: str = "idle" # idle, qr_generated, scanned, confirmed, security_check, logged_in
image_url: Optional[str] = None
error_message: Optional[str] = None
@dataclass
class JobSearchConfig:
"""职位搜索配置"""
experience_options: List[str]
job_type_options: List[str]
salary_options: List[str]
default_params: Dict[str, Any]
@dataclass
class JobInfo:
"""职位信息数据模型"""
job_id: str
title: str
company: str
salary: str
location: str
experience: str
education: str
security_id: Optional[str] = None
@dataclass
class GreetingRequest:
"""打招呼请求数据模型"""
security_id: str
job_id: str
message: str = "您好,我对这个职位很感兴趣,希望可以进一步沟通"
# 全局状态管理
class BossZhipinState:
"""Boss直聘全局状态管理"""
def __init__(self):
self.login_status = LoginStatus()
self.session = None
self.static_dir = Path("static")
self.static_dir.mkdir(exist_ok=True)
def get_session(self) -> requests.Session:
"""获取或创建HTTP会话"""
if self.session is None:
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Referer': 'https://www.zhipin.com/web/user/?ka=header-login',
'Origin': 'https://www.zhipin.com'
})
return self.session
def update_login_status(self, **kwargs):
"""更新登录状态"""
for key, value in kwargs.items():
if hasattr(self.login_status, key):
setattr(self.login_status, key, value)
def reset_login(self):
"""重置登录状态"""
self.login_status = LoginStatus()
if self.session:
self.session.cookies.clear()
self.session = None
# 全局状态实例
state = BossZhipinState()
# 后台线程函数:在独立线程中调用scan接口,不阻塞主线程
def background_scan_monitor(qr_id: str):
"""在后台线程中监控扫码状态和确认状态,不阻塞主线程"""
try:
session = state.get_session()
scan_url = f"https://www.zhipin.com/wapi/zppassport/qrcode/scan?uuid={qr_id}"
confirm_url = f"https://www.zhipin.com/wapi/zppassport/qrcode/scanLogin?qrId={qr_id}&status=1"
# 阶段1:等待扫码(长轮询)
print(f"[后台监控] 开始监控扫码状态,QR ID: {qr_id}")
scan_count = 0
while True:
if state.login_status.login_step == "logged_in":
print(f"[后台监控] 已登录,停止监控")
return
try:
scan_count += 1
print(f"[后台监控] 第{scan_count}次调用scan接口")
resp = session.get(scan_url, timeout=35)
# 检查响应内容,而不只是状态码
if resp.status_code == 200:
json_data = resp.json()
if json_data.get("scaned"):
print(f"[后台监控] ✅ 检测到用户已扫码,进入确认阶段")
state.update_login_status(login_step="scanned")
break # 退出扫码循环,进入确认阶段
elif json_data.get("msg") == "timeout":
print(f"[后台监控] ⏱️ 等待扫码超时,继续轮询... ({scan_count})")
else:
print(f"[后台监控] 🔄 轮询中... ({scan_count}) - {json_data}")
else:
print(f"[后台监控] ⚠️ 未知扫码状态码: {resp.status_code}")
except requests.exceptions.ReadTimeout:
print(f"[后台监控] ⏱️ 等待扫码超时,继续轮询... ({scan_count})")
continue
except Exception as e:
print(f"[后台监控] ❌ 调用scan接口出错: {e}")
time.sleep(2)
time.sleep(1)
# 阶段2:等待确认(长轮询)
if state.login_status.login_step == "scanned":
print(f"[后台监控] 开始监控确认状态")
confirm_count = 0
while True:
try:
confirm_count += 1
print(f"[后台监控] 第{confirm_count}次调用confirm接口")
resp = session.get(confirm_url, timeout=35)
# 检查响应内容
if resp.status_code == 200:
print(f"[后台监控] ✅ 用户已确认登录,获取Cookie")
# 获取最终Cookie
i_str = "8048b8676fb7d3d8952276e6e98e0bde.f2dc7a63c4b0fbfa4b51a07e2710cf83.fef7e750fc3a1e6327e8a880915aee9c.ae00f848beb1aa591d71d5a80dd3bd95"
e_b64 = "clRwXUJBK1VKK0k0IWFbbQ=="
key_bytes = base64.b64decode(e_b64)
plaintext_bytes = i_str.encode('utf-8')
iv_bytes = get_random_bytes(16)
cipher = AES.new(key_bytes, AES.MODE_CBC, iv_bytes)
padded_plaintext = pad(plaintext_bytes, AES.block_size)
ciphertext_bytes = cipher.encrypt(padded_plaintext)
result_bytes = iv_bytes + ciphertext_bytes
fp = base64.b64encode(result_bytes).decode('utf-8')
dispatcher_url = f"https://www.zhipin.com/wapi/zppassport/qrcode/dispatcher?qrId={qr_id}&pk=header-login&fp={fp}"
cookie_resp = session.get(dispatcher_url, allow_redirects=False)
# 解析Cookie
set_cookie_headers = cookie_resp.headers.get('Set-Cookie', '')
cookie_str = ''
bst_value = ''
if set_cookie_headers:
cookies = {}
cookie_parts = set_cookie_headers.split(',')
for part in cookie_parts:
if '=' in part:
name_value = part.strip().split(';')[0].strip()
if '=' in name_value:
name, value = name_value.split('=', 1)
cookies[name.strip()] = value.strip()
cookie_str = '; '.join([f"{k}={v}" for k, v in cookies.items()])
# if 'wt2' in cookies:
# cookie_str = f"wt2={cookies['wt2']}"
if 'bst' in cookies:
bst_value = cookies['bst']
# 阶段3:使用无头浏览器完成安全验证
print(f"[后台监控] 开始安全验证流程...")
state.update_login_status(login_step="security_check")
# 在新的事件循环中运行异步安全验证
try:
# 创建新的事件循环(因为我们在同步线程中)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# 运行安全验证
final_cookie_str = loop.run_until_complete(
BossZhipinAPI.complete_security_check(cookie_str)
)
loop.close()
print(f"[后台监控] ✅ 安全验证完成")
# 使用最终 Cookie 更新 session
for cookie_pair in final_cookie_str.split('; '):
if '=' in cookie_pair:
name, value = cookie_pair.split('=', 1)
session.cookies.set(name, value)
# 更新状态为最终 Cookie
state.update_login_status(
is_logged_in=True,
cookie=final_cookie_str,
bst=bst_value,
login_step="logged_in"
)
print(f"[后台监控] 🎉 登录成功!最终 Cookie 已保存")
except Exception as e:
print(f"[后台监控] ⚠️ 安全验证失败,使用初始 Cookie: {e}")
# 如果安全验证失败,仍然使用初始 Cookie
if cookie_str:
for cookie_pair in cookie_str.split('; '):
if '=' in cookie_pair:
name, value = cookie_pair.split('=', 1)
session.cookies.set(name, value)
state.update_login_status(
is_logged_in=True,
cookie=cookie_str,
bst=bst_value,
login_step="logged_in"
)
print(f"[后台监控] 🎉 登录成功!初始 Cookie 已保存")
return
else:
# 检查响应内容
json_data = resp.json()
if json_data.get("msg") == "timeout":
print(f"[后台监控] ⏱️ 等待确认超时,继续轮询... ({confirm_count})")
else:
print(f"[后台监控] 🔄 轮询中... ({confirm_count}) - {json_data}")
except requests.exceptions.ReadTimeout:
print(f"[后台监控] ⏱️ 等待确认超时,继续轮询... ({confirm_count})")
continue
except Exception as e:
print(f"[后台监控] ❌ 调用confirm接口出错: {e}")
time.sleep(2)
time.sleep(1)
except Exception as e:
print(f"[后台监控] ❌ 监控线程异常: {e}")
finally:
print(f"[后台监控] 监控线程结束")
# Boss直聘API工具类
class BossZhipinAPI:
"""Boss直聘API操作类"""
@staticmethod
def generate_fp(i_str: str, e_b64: str) -> str:
"""生成设备指纹参数"""
key_bytes = base64.b64decode(e_b64)
plaintext_bytes = i_str.encode('utf-8')
iv_bytes = get_random_bytes(16)
cipher = AES.new(key_bytes, AES.MODE_CBC, iv_bytes)
padded_plaintext = pad(plaintext_bytes, AES.block_size)
ciphertext_bytes = cipher.encrypt(padded_plaintext)
result_bytes = iv_bytes + ciphertext_bytes
return base64.b64encode(result_bytes).decode('utf-8')
@staticmethod
async def complete_security_check(initial_cookie: str) -> str:
"""使用无头浏览器完成安全验证,获取最终 Cookie
Args:
initial_cookie: 从 dispatcher 接口获取的初始 Cookie
Returns:
包含 __zp_stoken__ 的最终 Cookie 字符串
"""
# 固定的 security-check URL 参数
security_check_url = (
"https://www.zhipin.com/web/common/security-check.html?"
"seed=ttttZij2JIIK%2BxUw73%2B6ZmzsaYKTbDQuIH6OR6Bm54o%3D"
"&name=e331459e"
"&ts=1762256958405"
"&callbackUrl=https%3A%2F%2Fwww.zhipin.com%2Fweb%2Fgeek%2Fjobs"
)
print(f"[安全验证] 开始使用无头浏览器完成安全验证")
try:
async with async_playwright() as p:
# 启动无头浏览器
browser = await p.chromium.launch(headless=True)
context = await browser.new_context()
# 解析并设置初始 Cookie
cookies = []
for cookie_pair in initial_cookie.split('; '):
if '=' in cookie_pair:
name, value = cookie_pair.split('=', 1)
cookies.append({
'name': name,
'value': value,
'domain': '.zhipin.com',
'path': '/'
})
await context.add_cookies(cookies)
print(f"[安全验证] 已设置初始 Cookie,共 {len(cookies)} 个")
# 访问 security-check 页面
page = await context.new_page()
print(f"[安全验证] 正在访问 security-check 页面...")
await page.goto(security_check_url, wait_until='domcontentloaded')
# 等待网络空闲
print(f"[安全验证] 等待网络空闲...")
try:
await page.wait_for_load_state('networkidle', timeout=30000)
print(f"[安全验证] ✅ 网络已空闲")
except Exception as e:
print(f"[安全验证] ⚠️ 等待网络空闲超时: {e}")
# 额外等待,确保 JS 执行完成并设置 Cookie
print(f"[安全验证] 额外等待 3 秒,确保 Cookie 完全设置...")
await asyncio.sleep(3)
# 方法1:通过 JS 直接从页面读取 Cookie
print(f"[安全验证] 通过 JavaScript 读取页面 Cookie...")
js_cookies = await page.evaluate("() => document.cookie")
print(f"[安全验证] JS 获取的 Cookie: {js_cookies[:200]}...")
# 方法2:通过 Playwright API 获取 Cookie
print(f"[安全验证] 通过 Playwright API 获取 Cookie...")
final_cookies = await context.cookies()
playwright_cookie_str = '; '.join([f"{c['name']}={c['value']}" for c in final_cookies])
print(f"[安全验证] Playwright API 获取的 Cookie: {playwright_cookie_str[:200]}...")
# 使用 JS 读取的 Cookie(这是浏览器中真实的 Cookie)
final_cookie_str = js_cookies
# 检查是否有 __zp_stoken__
has_stoken = '__zp_stoken__' in js_cookies
if has_stoken:
# 从 Cookie 字符串中提取 __zp_stoken__ 的值
for cookie_pair in js_cookies.split('; '):
if cookie_pair.startswith('__zp_stoken__='):
stoken_value = cookie_pair.split('=', 1)[1]
print(f"[安全验证] ✅ 成功获取 __zp_stoken__: {stoken_value[:20]}...")
break
else:
print(f"[安全验证] ⚠️ 未找到 __zp_stoken__")
print(f"[安全验证] ✅ 安全验证完成")
# 关闭浏览器
await browser.close()
return final_cookie_str
except Exception as e:
print(f"[安全验证] ❌ 安全验证失败: {e}")
# 如果失败,返回初始 Cookie
return initial_cookie
@staticmethod
async def get_randkey(session: requests.Session) -> str:
"""获取登录随机密钥"""
url = "https://www.zhipin.com/wapi/zppassport/captcha/randkey"
resp = session.post(url)
resp.raise_for_status()
return resp.json()["zpData"]["qrId"]
@staticmethod
def get_randkey_sync(session: requests.Session) -> str:
"""获取登录随机密钥(同步版本)"""
url = "https://www.zhipin.com/wapi/zppassport/captcha/randkey"
resp = session.post(url)
resp.raise_for_status()
return resp.json()["zpData"]["qrId"]
@staticmethod
async def get_qrcode(session: requests.Session, qr_id: str) -> bytes:
"""获取二维码图片数据"""
url = f"https://www.zhipin.com/wapi/zpweixin/qrcode/getqrcode?content={qr_id}"
resp = session.get(url)
resp.raise_for_status()
return resp.content
@staticmethod
def get_qrcode_sync(session: requests.Session, qr_id: str) -> bytes:
"""获取二维码图片数据(同步版本)"""
url = f"https://www.zhipin.com/wapi/zpweixin/qrcode/getqrcode?content={qr_id}"
resp = session.get(url)
resp.raise_for_status()
return resp.content
@staticmethod
async def check_scan_status(session: requests.Session, qr_id: str) -> int:
"""检查扫码状态"""
url = f"https://www.zhipin.com/wapi/zppassport/qrcode/scan?uuid={qr_id}"
resp = session.get(url, timeout=60) # 使用短超时避免长时间阻塞
return resp.status_code
@staticmethod
async def check_login_confirmation(session: requests.Session, qr_id: str) -> int:
"""检查登录确认状态"""
url = f"https://www.zhipin.com/wapi/zppassport/qrcode/scanLogin?qrId={qr_id}&status=1"
resp = session.get(url, timeout=60) # 使用短超时避免长时间阻塞
return resp.status_code
@staticmethod
async def get_final_cookie(session: requests.Session, qr_id: str) -> tuple[str, str]:
"""获取最终登录Cookie"""
# 使用与 login_verifier.py 相同的参数和URL
i_str = "8048b8676fb7d3d8952276e6e98e0bde.f2dc7a63c4b0fbfa4b51a07e2710cf83.fef7e750fc3a1e6327e8a880915aee9c.ae00f848beb1aa591d71d5a80dd3bd95"
e_b64 = "clRwXUJBK1VKK0k0IWFbbQ=="
# 生成fp参数
fp = BossZhipinAPI.generate_fp(i_str, e_b64)
# 使用正确的 dispatcher URL
dispatcher_url = f"https://www.zhipin.com/wapi/zppassport/qrcode/dispatcher?qrId={qr_id}&pk=header-login&fp={fp}"
resp = session.get(dispatcher_url, allow_redirects=False)
# 解析Set-Cookie头
set_cookie_headers = resp.headers.get('Set-Cookie', '')
cookie_str = ''
bst_value = ''
if set_cookie_headers:
# 解析Cookie
cookies = {}
cookie_parts = set_cookie_headers.split(',')
for part in cookie_parts:
if '=' in part:
name_value = part.strip().split(';')[0].strip()
if '=' in name_value:
name, value = name_value.split('=', 1)
cookies[name.strip()] = value.strip()
# 构建cookie字符串
cookie_str = '; '.join([f"{k}={v}" for k, v in cookies.items()])
# 查找特定的cookie值
if 'wt2' in cookies:
cookie_str = f"wt2={cookies['wt2']}"
if 'bst' in cookies:
bst_value = cookies['bst']
# 设置Cookie到会话
if cookie_str:
session.headers['Cookie'] = cookie_str
return cookie_str, bst_value
@staticmethod
def setup_api_headers(session: requests.Session, cookie: str, bst: str):
"""设置API请求头"""
session.headers.update({
'Cookie': cookie,
'zp_token': bst,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
'Referer': 'https://www.zhipin.com/web/user/?ka=header-login',
'Origin': 'https://www.zhipin.com'
})
# 参数映射表(参考 TypeScript 版本)
EXPERIENCE_MAP = {
'在校生': 108,
'应届生': 102,
'不限': 101,
'一年以内': 103,
'一到三年': 104,
'三到五年': 105,
'五到十年': 106,
'十年以上': 107
}
JOB_TYPE_MAP = {
'全职': 1901,
'兼职': 1903,
}
SALARY_MAP = {
'3k以下': 402,
'3-5k': 403,
'5-10k': 404,
'10-20k': 405,
'20-50k': 406,
'50以上': 407,
}
@staticmethod
async def get_job_list(session: requests.Session, params: dict) -> dict:
"""获取职位列表"""
url = "https://www.zhipin.com/wapi/zpgeek/pc/recommend/job/list.json"
# 转换文本参数为代码
converted_params = {}
if 'experience' in params and params['experience'] in BossZhipinAPI.EXPERIENCE_MAP:
converted_params['experience'] = BossZhipinAPI.EXPERIENCE_MAP[params['experience']]
if 'jobType' in params and params['jobType'] in BossZhipinAPI.JOB_TYPE_MAP:
converted_params['jobType'] = BossZhipinAPI.JOB_TYPE_MAP[params['jobType']]
if 'salary' in params and params['salary'] in BossZhipinAPI.SALARY_MAP:
converted_params['salary'] = BossZhipinAPI.SALARY_MAP[params['salary']]
# 设置默认参数
default_params = {
"page": 1,
"pageSize": 15,
"_": int(time.time() * 1000) # 时间戳
}
default_params.update(converted_params)
# 添加其他参数(如 encryptExpectId 等)
for key in ['page', 'pageSize', 'encryptExpectId']:
if key in params:
default_params[key] = params[key]
try:
resp = session.get(url, params=default_params, timeout=10)
resp.raise_for_status()
data = resp.json()
if data.get("code") != 0:
raise Exception(f"API错误: {data.get('message', '未知错误')}")
zp_data = data.get("zpData", {})
job_list = zp_data.get("jobList", [])
# 转换为标准格式
jobs = []
for job in job_list:
job_info = {
"securityId": job.get("securityId"),
"encryptBossId": job.get("encryptBossId"),
"jobDegree": job.get("jobDegree"),
"jobName": job.get("jobName"),
"lid": job.get("lid"),
"salaryDesc": job.get("salaryDesc"),
"jobLabels": job.get("jobLabels", []),
"skills": job.get("skills", []),
"jobExperience": job.get("jobExperience"),
"cityName": job.get("cityName"),
"areaDistrict": job.get("areaDistrict"),
"encryptBrandId": job.get("encryptBrandId"),
"brandName": job.get("brandName"),
"brandScaleName": job.get("brandScaleName"),
"industry": job.get("industry"),
"contact": job.get("contact", False),
"showTopPosition": job.get("showTopPosition", False)
}
jobs.append(job_info)
return {
"status": "success",
"data": {
"hasMore": zp_data.get("hasMore", False),
"jobList": jobs,
"total": len(jobs)
}
}
except requests.RequestException as e:
return {
"status": "error",
"message": f"网络请求失败: {str(e)}"
}
except Exception as e:
return {
"status": "error",
"message": f"获取职位失败: {str(e)}"
}
@staticmethod
async def greet_boss(session: requests.Session, security_id: str, job_id: str) -> dict:
"""向HR发送打招呼"""
url = "https://www.zhipin.com/wapi/zpgeek/friend/add.json"
params = {
"securityId": security_id,
"jobId": job_id
}
try:
resp = session.get(url, params=params, timeout=10)
resp.raise_for_status()
data = resp.json()
if data.get("code") != 0:
raise Exception(f"API错误: {data.get('message', '未知错误')}")
zp_data = data.get("zpData", {})
return {
"status": "success",
"message": "打招呼发送成功",
"data": {
"showGreeting": zp_data.get("showGreeting", False),
"securityId": zp_data.get("securityId"),
"bossSource": zp_data.get("bossSource"),
"source": zp_data.get("source"),
"encBossId": zp_data.get("encBossId")
}
}
except requests.RequestException as e:
return {
"status": "error",
"message": f"网络请求失败: {str(e)}"
}
except Exception as e:
return {
"status": "error",
"message": f"发送打招呼失败: {str(e)}"
}
# 创建FastMCP服务器实例
mcp = FastMCP(
name="Boss直聘 MCP Server",
host="127.0.0.1",
port=8000,
log_level="info"
)
# 静态文件路由
@mcp.custom_route("/static/{filename:path}", methods=["GET"])
async def serve_static_file(request: Request) -> FileResponse:
"""提供静态文件服务"""
filename = request.path_params["filename"]
file_path = state.static_dir / filename
if file_path.exists() and file_path.is_file():
return FileResponse(str(file_path))
return JSONResponse(
{"error": "文件未找到", "filename": filename},
status_code=404
)
# Resources 定义
@mcp.resource("boss-zp://status")
async def get_server_status() -> str:
"""获取服务器状态"""
return json.dumps({
"server": "Boss直聘 MCP Server",
"version": "2.0.0",
"status": "running",
"login_status": asdict(state.login_status)
}, ensure_ascii=False, indent=2)
@mcp.resource("boss-zp://config")
async def get_job_config() -> str:
"""获取职位搜索配置"""
config = {
"experience": BossZhipinAPI.EXPERIENCE_MAP,
"jobType": BossZhipinAPI.JOB_TYPE_MAP,
"salary": BossZhipinAPI.SALARY_MAP,
"default_params": {
"experience": "不限",
"jobType": "全职",
"salary": "不限",
"page": 1
}
}
return json.dumps(config, ensure_ascii=False, indent=2)
@mcp.resource("boss-zp://login/start")
async def start_login(ctx: Context) -> str:
"""启动登录流程"""
try:
await ctx.info("开始启动Boss直聘登录流程")
# 重置登录状态
state.reset_login()
# 获取会话
session = state.get_session()
# 步骤1:获取随机密钥(使用同步方式)
qr_id = BossZhipinAPI.get_randkey_sync(session)
state.update_login_status(qr_id=qr_id, login_step="qr_generated")
# 步骤2:获取二维码(使用同步方式)
qr_image_data = BossZhipinAPI.get_qrcode_sync(session, qr_id)
# 保存二维码图片
filename = f"qrcode_{qr_id}.png"
filepath = state.static_dir / filename
with open(filepath, "wb") as f:
f.write(qr_image_data)
# 生成图片URL
image_url = f"http://127.0.0.1:8000/static/{filename}"
state.update_login_status(image_url=image_url)
await ctx.info(f"二维码已生成,QR ID: {qr_id}")
return json.dumps({
"status": "success",
"message": "二维码已生成,请访问以下URL查看二维码图片",
"qr_id": qr_id,
"image_url": image_url,
"login_step": "qr_generated"
}, ensure_ascii=False, indent=2)
except Exception as e:
error_msg = f"启动登录流程失败: {str(e)}"
await ctx.error(error_msg)
state.update_login_status(error_message=error_msg)
return json.dumps({
"status": "error",
"message": error_msg
}, ensure_ascii=False, indent=2)
@mcp.resource("boss-zp://login/info")
async def get_login_info(ctx: Context) -> str:
"""获取当前登录状态和Cookie信息"""
try:
login_status = state.login_status
# 构建响应信息
result = {
"is_logged_in": login_status.is_logged_in,
"login_step": login_status.login_step,
"qr_id": login_status.qr_id,
"image_url": login_status.image_url,
"error_message": login_status.error_message
}
# 如果已登录,添加Cookie信息
if login_status.is_logged_in:
result["cookie"] = login_status.cookie
result["bst"] = login_status.bst
# 解析Cookie显示详细信息
if login_status.cookie:
cookies_dict = {}
for cookie_pair in login_status.cookie.split('; '):
if '=' in cookie_pair:
name, value = cookie_pair.split('=', 1)
cookies_dict[name] = value
result["cookies_detail"] = cookies_dict
await ctx.info("✅ 已登录")
else:
await ctx.info(f"⏳ 当前状态: {login_status.login_step}")
return json.dumps(result, ensure_ascii=False, indent=2)
except Exception as e:
error_msg = f"获取登录信息失败: {str(e)}"
await ctx.error(error_msg)
return json.dumps({
"status": "error",
"message": error_msg
}, ensure_ascii=False, indent=2)
@mcp.resource("boss-zp://jobs/{page}/{experience}/{job_type}/{salary}")
async def get_recommend_jobs(
page: int,
experience: str,
job_type: str,
salary: str,
ctx: Context
) -> str:
"""获取推荐职位"""
try:
if not state.login_status.is_logged_in:
return json.dumps({
"error": "未登录",
"message": "请先完成登录再获取职位信息"
}, ensure_ascii=False, indent=2)
await ctx.info(f"获取推荐职位: 页码{page}, 经验{experience}, 类型{job_type}, 薪资{salary}")
session = state.get_session()
headers = {
'Cookie': state.login_status.cookie,
'Origin': 'https://www.zhipin.com',
'Referer': 'https://www.zhipin.com/web/geek/job',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
}
# TODO: 实现具体的职位获取API调用
# 这里暂时返回示例数据
jobs = [
JobInfo(
job_id="example_job_1",
title="高级Python开发工程师",
company="示例科技公司",
salary="15-25k",
location="北京",
experience=experience,
education="本科",
security_id="example_security_1"
),
JobInfo(
job_id="example_job_2",
title="全栈开发工程师",
company="示例互联网公司",
salary="20-35k",
location="上海",
experience=experience,
education="本科",
security_id="example_security_2"
)
]
result = {
"status": "success",
"data": {
"page": page,
"experience": experience,
"job_type": job_type,
"salary": salary,
"total": len(jobs),
"jobs": [asdict(job) for job in jobs]
}
}
await ctx.info(f"成功获取 {len(jobs)} 个职位")
return json.dumps(result, ensure_ascii=False, indent=2)
except Exception as e:
error_msg = f"获取职位失败: {str(e)}"
await ctx.error(error_msg)
return json.dumps({
"error": "获取职位失败",
"message": error_msg
}, ensure_ascii=False, indent=2)
# Tools 定义
@mcp.tool()
async def login_full_auto(ctx: Context) -> str:
"""完全自动化登录流程,生成二维码并在后台监控扫码状态(无交互版本)"""
try:
await ctx.info("开始自动化登录流程")
# 启动登录并生成二维码
session = state.get_session()
qr_id = await BossZhipinAPI.get_randkey(session)
state.update_login_status(qr_id=qr_id, login_step="qr_generated")
# 获取二维码
qr_image_data = await BossZhipinAPI.get_qrcode(session, qr_id)
# 保存二维码图片
filename = f"qrcode_{qr_id}.png"
filepath = state.static_dir / filename
with open(filepath, "wb") as f:
f.write(qr_image_data)
# 生成图片URL
image_url = f"http://127.0.0.1:8000/static/{filename}"
state.update_login_status(image_url=image_url)
# 启动后台线程监控扫码状态,不阻塞主线程
monitor_thread = threading.Thread(target=background_scan_monitor, args=(qr_id,), daemon=True)
monitor_thread.start()
await ctx.info(f"二维码已生成: {image_url}")
await ctx.info("后台监控线程已启动,二维码将保持有效1分钟")
return json.dumps({
"status": "qr_generated",
"message": "二维码已生成,后台监控已启动",
"qr_id": qr_id,
"image_url": image_url,
"login_step": "qr_generated",
"next_action": "请使用Boss直聘APP扫码,后台会自动监控登录状态。可通过 boss-zp://login/info 或 get_login_info_tool 查看登录进度和Cookie"
}, ensure_ascii=False, indent=2)
except Exception as e:
error_msg = f"自动登录失败: {str(e)}"
await ctx.error(error_msg)
return json.dumps({
"status": "error",
"message": error_msg
}, ensure_ascii=False, indent=2)
@mcp.tool()
async def login_start_interactive(ctx: Context) -> str:
"""交互式启动登录流程,引导用户完成扫码和确认"""
try:
await ctx.info("开始交互式登录流程")
while True: # 外层循环处理整个登录流程重试
while True: # 内层循环处理重新生成二维码的情况
# 步骤1:启动登录并生成二维码
session = state.get_session()
qr_id = await BossZhipinAPI.get_randkey(session)
state.update_login_status(qr_id=qr_id, login_step="qr_generated")
# 获取二维码
qr_image_data = await BossZhipinAPI.get_qrcode(session, qr_id)
# 保存二维码图片
filename = f"qrcode_{qr_id}.png"
filepath = state.static_dir / filename
with open(filepath, "wb") as f:
f.write(qr_image_data)
# 生成图片URL
image_url = f"http://127.0.0.1:8000/static/{filename}"
state.update_login_status(image_url=image_url)
# 显示二维码信息
await ctx.info("=" * 50)
await ctx.info("🔥 Boss直聘登录二维码已生成!")
await ctx.info(f"📱 二维码图片URL: {image_url}")
await ctx.info(f"🆔 QR ID: {qr_id}")
await ctx.info("=" * 50)
# 步骤2:询问用户是否已扫码
scan_result = await ctx.elicit(
"请使用Boss直聘APP扫描上方的二维码图片,扫描完成后请选择'已扫码'",
response_type=["已扫码", "重新生成二维码", "取消登录"]
)
if scan_result.action != "accept" or scan_result.data not in ["已扫码", "重新生成二维码"]:
return json.dumps({
"status": "cancelled",
"message": "用户取消了登录流程"
}, ensure_ascii=False, indent=2)
# 如果用户选择重新生成二维码,继续内层循环
if scan_result.data == "重新生成二维码":
await ctx.info("正在重新生成二维码...")
state.reset_login()
continue
# 步骤3:检查扫码状态
await ctx.info("🔍 正在验证扫码状态...")
status_code = await BossZhipinAPI.check_scan_status(session, qr_id)
if status_code == 200:
scan_check = {"status": "scanned"}
elif status_code == 409:
scan_check = {"status": "waiting"}
else:
scan_check = {"status": "error", "message": f"未知状态: {status_code}"}
if scan_check["status"] != "scanned":
await ctx.warning("⚠️ 未检测到扫码状态,请确认是否已成功扫码")
# 给用户重试机会
retry_result = await ctx.elicit(