Skip to content

Commit 8a785b2

Browse files
committed
chore: refactor imports for better organization in tool_code.py
1 parent 3de7249 commit 8a785b2

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

apps/chat/views/chat.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from chat.serializers.chat_authentication import AnonymousAuthenticationSerializer, ApplicationProfileSerializer, \
2323
AuthProfileSerializer
2424
from common.auth import TokenAuth
25+
from common.auth.mcp_auth_token import mcp_token_required
2526
from common.constants.permission_constants import ChatAuth
2627
from common.exception.app_exception import AppAuthenticationFailed
2728
from common.result import result
@@ -175,6 +176,7 @@ class OpenView(APIView):
175176
responses=None,
176177
tags=[_('Chat')] # type: ignore
177178
)
179+
@mcp_token_required # 添加MCP令牌验证
178180
def get(self, request: Request):
179181
return result.success(OpenChatSerializers(
180182
data={'application_id': request.auth.application_id,

apps/common/utils/tool_code.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import base64
44
import getpass
55
import gzip
6+
import hashlib
7+
import hmac
68
import json
79
import os
810
import pwd
@@ -235,6 +237,15 @@ def get_tool_mcp_config(self, code, params, name, description):
235237

236238
def get_app_mcp_config(self, api_key, name, description):
237239
chat_path = CONFIG.get_chat_path()
240+
# 生成内部令牌(基于时间戳+密钥+api_key)
241+
timestamp = int(time.time())
242+
secret = CONFIG.get('MCP_INTERNAL_SECRET', 'your-secret-key')
243+
token_data = f"{api_key}:{timestamp}"
244+
internal_token = hmac.new(
245+
secret.encode(),
246+
token_data.encode(),
247+
hashlib.sha256
248+
).hexdigest()
238249
_code = f'''
239250
from typing import Optional
240251
@@ -244,7 +255,9 @@ def _get_chat_id() -> Optional[str]:
244255
url = f"http://127.0.0.1:8080{chat_path}/api/open"
245256
headers = {{
246257
'accept': '*/*',
247-
'Authorization': f'Bearer {api_key}'
258+
'Authorization': f'Bearer {api_key}',
259+
'X-MCP-Token': '{internal_token}', # 添加内部令牌
260+
'X-MCP-Timestamp': '{timestamp}'
248261
}}
249262
try:
250263
resp = requests.get(url, headers=headers, timeout=10)
@@ -258,7 +271,12 @@ def _chat_with_ai(chat_id: str, message: str) -> Optional[str]:
258271
import requests
259272
260273
url = f"http://127.0.0.1:8080{chat_path}/api/chat_message/{{chat_id}}"
261-
headers = {{"Content-Type": "application/json", "Authorization": f'Bearer {api_key}'}}
274+
headers = {{
275+
'Content-Type': 'application/json',
276+
'Authorization': f'Bearer {api_key}',
277+
'X-MCP-Token': '{internal_token}', # 添加内部令牌
278+
'X-MCP-Timestamp': '{timestamp}'
279+
}}
262280
payload = {{
263281
"message": message,
264282
"re_chat": False,

0 commit comments

Comments
 (0)