| 9 | |
| 10 | |
| 11 | class MCPToolHandler: |
| 12 | def __init__(self, auth_header): |
| 13 | app_key = QuerySet(ApplicationApiKey).filter(secret_key=auth_header, is_active=True).first() |
| 14 | if not app_key: |
| 15 | raise PermissionError("Invalid API Key") |
| 16 | |
| 17 | self.application = QuerySet(Application).filter(id=app_key.application_id, is_publish=True).first() |
| 18 | if not self.application: |
| 19 | raise PermissionError("Application is not found or not published") |
| 20 | |
| 21 | def initialize(self): |
| 22 | return { |
| 23 | "protocolVersion": "2025-06-18", |
| 24 | "serverInfo": { |
| 25 | "name": "maxkb-mcp", |
| 26 | "version": "1.0.0" |
| 27 | }, |
| 28 | "capabilities": { |
| 29 | "tools": {} |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | def list_tools(self): |
| 34 | return { |
| 35 | "tools": [ |
| 36 | { |
| 37 | "name": f'agent_{str(self.application.id)[:8]}', |
| 38 | "description": f'{self.application.name} {self.application.desc}', |
| 39 | "inputSchema": { |
| 40 | "type": "object", |
| 41 | "properties": { |
| 42 | "message": {"type": "string", "description": "The message to send to the AI."}, |
| 43 | }, |
| 44 | "required": ["message"] |
| 45 | } |
| 46 | } |
| 47 | ] |
| 48 | } |
| 49 | |
| 50 | def _get_chat_id(self): |
| 51 | from application.models import ChatUserType |
| 52 | from chat.serializers.chat import OpenChatSerializers |
| 53 | from common.init import init_template |
| 54 | |
| 55 | init_template.run() |
| 56 | |
| 57 | return OpenChatSerializers(data={ |
| 58 | 'application_id': self.application.id, |
| 59 | 'chat_user_id': str(uuid.uuid7()), |
| 60 | 'chat_user_type': ChatUserType.ANONYMOUS_USER, |
| 61 | 'ip_address': '-', |
| 62 | 'source': {"type": ChatSourceChoices.ONLINE.value}, |
| 63 | 'debug': False |
| 64 | }).open() |
| 65 | |
| 66 | def call_tool(self, params): |
| 67 | name = params["name"] |
| 68 | args = params.get("arguments", {}) |