From c949aac52812e2ff293b65d6b648648e37782dd9 Mon Sep 17 00:00:00 2001 From: Liujian <824010343@qq.com> Date: Thu, 16 Oct 2025 10:03:10 +0800 Subject: [PATCH] fix bug --- scripts/resource/sql/version-1.1.0.sql | 2 +- .../admin_service/constants/sys_config_key.py | 4 +- .../admin_service/controllers/admin_stats.py | 70 +++++---- .../admin_service/controllers/sys_config.py | 14 ++ .../stats_mcp_service_date_repository.py | 140 ++++++++++++++++++ .../repositories/user_repository.py | 62 +++++++- .../services/billing_message_handler.py | 13 +- .../services/mcp_manager_service.py | 33 +---- .../admin_service/services/stats_service.py | 46 ++++++ services/admin_service/utils/ip.py | 46 ++++++ .../api_service/services/billing_service.py | 9 +- .../services/mcp_server_factory.py | 6 +- services/api_service/services/mcp_service.py | 27 ++-- .../api_service/services/mcp_tool_service.py | 4 +- services/api_service/utils/http_client.py | 52 +++---- .../common/models/stats_mcp_service_date.py | 46 ++++++ 16 files changed, 462 insertions(+), 112 deletions(-) create mode 100644 services/admin_service/repositories/stats_mcp_service_date_repository.py create mode 100644 services/admin_service/services/stats_service.py create mode 100644 services/admin_service/utils/ip.py create mode 100644 services/common/models/stats_mcp_service_date.py diff --git a/scripts/resource/sql/version-1.1.0.sql b/scripts/resource/sql/version-1.1.0.sql index 3d213d9..2eb636b 100644 --- a/scripts/resource/sql/version-1.1.0.sql +++ b/scripts/resource/sql/version-1.1.0.sql @@ -20,7 +20,7 @@ CREATE TABLE `onboarding_task` ( ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '新手引导任务表' ROW_FORMAT = DYNAMIC; CREATE TABLE `stats_mcp_service_date` ( - `stats_date` date NOT NULL, + `stats_date` DATETIME NOT NULL COMMENT '统计时间(小时,UTC)', `service_id` char(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, `call_count` int NOT NULL DEFAULT 0 COMMENT '调用次数', `created_at` timestamp NULL DEFAULT NULL, diff --git a/services/admin_service/constants/sys_config_key.py b/services/admin_service/constants/sys_config_key.py index 881ffa4..22911dc 100644 --- a/services/admin_service/constants/sys_config_key.py +++ b/services/admin_service/constants/sys_config_key.py @@ -39,4 +39,6 @@ KEY_FACEBOOK_DESCRIPTION = "facebook_description" KEY_FACEBOOK_IMAGE_URL = "facebook_image_url" KEY_SOCIAL_ACCOUNT_FACEBOOK_URL = "social_account_facebook_url" -KEY_SOCIAL_ACCOUNT_X_URL = "social_account_x_url" \ No newline at end of file +KEY_SOCIAL_ACCOUNT_X_URL = "social_account_x_url" + +KEY_CNAME_A_IP = "cname_a_ip" \ No newline at end of file diff --git a/services/admin_service/controllers/admin_stats.py b/services/admin_service/controllers/admin_stats.py index 2258458..af90674 100644 --- a/services/admin_service/controllers/admin_stats.py +++ b/services/admin_service/controllers/admin_stats.py @@ -8,37 +8,51 @@ from services.common.models.user import User from services.common.models.user_wallet import UserWallet from services.common.models.mcp_service import McpService from services.common.models.mcp_call_log import McpCallLog +from services.admin_service.services.stats_service import StatsService router = APIRouter() +def get_stats_service(db: Session = Depends(get_db)) -> StatsService: + return StatsService(db) -@router.get("/platform") -async def get_platform_overview(db: Session = Depends(get_db)): - """Get platform overview statistics and metrics.""" +@router.get("/stats/analytics") +async def stats( + stats_service: StatsService = Depends(get_stats_service) +): + """Get total number of registered users.""" try: - # Get total users (non-admin and not deleted) - total_user = db.query(User).filter(User.role_id != 1, User.is_deleted == 0).count() # Non-admin (role_id 1 is admin), not deleted - - # Get total balance - total_balance_result = db.query(func.sum(UserWallet.balance)).scalar() - total_balance = int(total_balance_result) if total_balance_result else 0 - - # Get total number of services - total_service = db.query(McpService).count() - - # Get today's invocation count - today = date.today() - today_invoke_count = db.query(McpCallLog).filter(func.date(McpCallLog.created_at) == today).count() - - # Build response data - response_data = { - "total_user": total_user, - "total_balance": total_balance, - "total_service": total_service, - "invoke_count": {"today": today_invoke_count}, - } - - return ResponseUtils.success(response_data) - + total_registered_users = stats_service.get_total_registered_users() + return ResponseUtils.success({"total_registered_users": total_registered_users}) except Exception as e: - return ResponseUtils.error(f"Failed to get platform overview: {str(e)}", 500) + return ResponseUtils.error(f"Failed to get total registered users: {str(e)}", 500) + +# @router.get("/platform") +# async def get_platform_overview(db: Session = Depends(get_db)): +# """Get platform overview statistics and metrics.""" +# try: +# # Get total users (non-admin and not deleted) +# total_user = db.query(User).filter(User.role_id != 1, User.is_deleted == 0).count() # Non-admin (role_id 1 is admin), not deleted + +# # Get total balance +# total_balance_result = db.query(func.sum(UserWallet.balance)).scalar() +# total_balance = int(total_balance_result) if total_balance_result else 0 + +# # Get total number of services +# total_service = db.query(McpService).count() + +# # Get today's invocation count +# today = date.today() +# today_invoke_count = db.query(McpCallLog).filter(func.date(McpCallLog.created_at) == today).count() + +# # Build response data +# response_data = { +# "total_user": total_user, +# "total_balance": total_balance, +# "total_service": total_service, +# "invoke_count": {"today": today_invoke_count}, +# } + +# return ResponseUtils.success(response_data) + +# except Exception as e: +# return ResponseUtils.error(f"Failed to get platform overview: {str(e)}", 500) diff --git a/services/admin_service/controllers/sys_config.py b/services/admin_service/controllers/sys_config.py index 8c18c92..828bcc7 100644 --- a/services/admin_service/controllers/sys_config.py +++ b/services/admin_service/controllers/sys_config.py @@ -1,5 +1,8 @@ from fastapi import APIRouter, Depends, Body import json +import socket +import urllib.request +from typing import Optional from sqlalchemy import false, table from sqlalchemy.orm import Session from services.common.database import get_db @@ -10,6 +13,7 @@ from services.admin_service.services.user_service import UserService from services.admin_service.services.platform_report_service import PlatformReportService from services.admin_service.constants import sys_config_key from services.common.logging_config import get_logger +from services.admin_service.utils.ip import get_public_ip, get_local_ip logger = get_logger(__name__) @@ -95,6 +99,15 @@ def get_sysconfig( small_values = sysconfig_service.get_all() large_values = sysconfig_service.get_all(large_keys, is_large=True) + + + cname_a_ip = small_values.get(sys_config_key.KEY_CNAME_A_IP, "") + if not cname_a_ip: + # 获取外网IP,若无法连接外网,则获取局域网IP + public_ip = get_public_ip() + cname_a_ip = public_ip if public_ip else get_local_ip() + sysconfig_service.set_value_by_key(sys_config_key.KEY_CNAME_A_IP, cname_a_ip,"CNAME A IP") + # 管理员用户名 admin_username = "" if admin_user and admin_user.name: @@ -124,6 +137,7 @@ def get_sysconfig( "facebook_image_url": small_values.get(sys_config_key.KEY_FACEBOOK_IMAGE_URL, ""), "social_account_facebook_url": small_values.get(sys_config_key.KEY_SOCIAL_ACCOUNT_FACEBOOK_URL, ""), "social_account_x_url": small_values.get(sys_config_key.KEY_SOCIAL_ACCOUNT_X_URL, ""), + "cname_a_ip": cname_a_ip, }, "account": { "username": admin_username, diff --git a/services/admin_service/repositories/stats_mcp_service_date_repository.py b/services/admin_service/repositories/stats_mcp_service_date_repository.py new file mode 100644 index 0000000..4e682dc --- /dev/null +++ b/services/admin_service/repositories/stats_mcp_service_date_repository.py @@ -0,0 +1,140 @@ +from datetime import date, datetime +from typing import Optional, List, Tuple, cast +from sqlalchemy.orm import Session +from sqlalchemy import func +from sqlalchemy.exc import IntegrityError +from sqlalchemy.dialects.mysql import insert as mysql_insert +from sqlalchemy.sql.schema import Table +from services.common.models.stats_mcp_service_date import StatsMcpServiceDate + + +class StatsMcpServiceDateRepository: + """MCP call log repository class""" + + def __init__(self, db: Session): + self.db = db + + def insert(self, service_id: str, stats_date: datetime, call_count: int = 1) -> StatsMcpServiceDate: + """Insert a new hourly stats record. + + Raises on duplicate primary key; use update or upsert if unsure. + """ + record = StatsMcpServiceDate() + record.service_id = service_id + record.stats_date = stats_date + record.call_count = call_count + self.db.add(record) + self.db.commit() + self.db.refresh(record) + return record + + def update(self, service_id: str, stats_date: datetime, call_count: int) -> Optional[StatsMcpServiceDate]: + """Update existing hourly stats record's call_count. + + Returns the updated record, or None if not found. + """ + record = ( + self.db.query(StatsMcpServiceDate) + .filter( + StatsMcpServiceDate.service_id == service_id, + StatsMcpServiceDate.stats_date == stats_date, + ) + .first() + ) + if not record: + return None + record.call_count = call_count + self.db.commit() + self.db.refresh(record) + return record + + def get_daily_counts( + self, + service_id: str, + start_date: Optional[date] = None, + end_date: Optional[date] = None, + ) -> List[Tuple[date, int]]: + """Get per-day aggregated call counts within optional date range. + + Aggregates hour-level records by DATE(stats_date). Returns list of (day, total_count). + """ + day_col = func.date(StatsMcpServiceDate.stats_date) + query = ( + self.db.query( + day_col.label("stats_day"), + func.coalesce(func.sum(StatsMcpServiceDate.call_count), 0).label("total_count"), + ) + .filter(StatsMcpServiceDate.service_id == service_id) + ) + if start_date is not None: + query = query.filter(day_col >= start_date) + if end_date is not None: + query = query.filter(day_col <= end_date) + rows = query.group_by(day_col).order_by(day_col.asc()).all() + return [(row.stats_day, int(row.total_count or 0)) for row in rows] + + def get_total_count( + self, + service_id: str, + start_date: Optional[date] = None, + end_date: Optional[date] = None, + ) -> int: + """Get total call count for a service within optional date range.""" + day_col = func.date(StatsMcpServiceDate.stats_date) + query = self.db.query(func.coalesce(func.sum(StatsMcpServiceDate.call_count), 0)).filter( + StatsMcpServiceDate.service_id == service_id + ) + if start_date is not None: + query = query.filter(day_col >= start_date) + if end_date is not None: + query = query.filter(day_col <= end_date) + total = query.scalar() + return int(total or 0) + + def increment(self, service_id: str, stats_date: datetime, inc: int = 1) -> None: + """Atomically increment call_count for (service_id, stats_date) under high concurrency. + + Implementation uses MySQL's ON DUPLICATE KEY UPDATE to avoid race conditions. + If the row does not exist, it will be inserted with call_count=inc; otherwise, call_count is increased. + """ + # Cast mapped table for typing compatibility with mysql_insert + table: Table = cast(Table, StatsMcpServiceDate.__table__) + stmt = mysql_insert(table).values( + service_id=service_id, + stats_date=stats_date, + call_count=inc, + created_at=func.current_timestamp(), + updated_at=func.current_timestamp(), + ) + ondup = stmt.on_duplicate_key_update( + call_count=table.c.call_count + inc, + updated_at=func.current_timestamp(), + ) + self.db.execute(ondup) + self.db.commit() + + def increment_fallback(self, service_id: str, stats_date: datetime, inc: int = 1) -> None: + """Fallback increment strategy without dialect-specific upsert. + + Tries to insert; on duplicate key, rolls back and performs an in-place atomic update: call_count = call_count + inc. + Suitable when MySQL dialect insert is not available. + """ + try: + # Try insert first + self.insert(service_id, stats_date, inc) + except IntegrityError: + # Record exists, perform atomic UPDATE + self.db.rollback() + self.db.query(StatsMcpServiceDate).filter( + StatsMcpServiceDate.service_id == service_id, + StatsMcpServiceDate.stats_date == stats_date, + ).update( + { + StatsMcpServiceDate.call_count: StatsMcpServiceDate.call_count + inc, + StatsMcpServiceDate.updated_at: func.current_timestamp(), + }, + synchronize_session=False, + ) + self.db.commit() + + \ No newline at end of file diff --git a/services/admin_service/repositories/user_repository.py b/services/admin_service/repositories/user_repository.py index 921cd22..e4c8a1e 100644 --- a/services/admin_service/repositories/user_repository.py +++ b/services/admin_service/repositories/user_repository.py @@ -1,5 +1,6 @@ from sqlalchemy.orm import Session -from datetime import datetime, timezone +from sqlalchemy import func, literal_column +from datetime import datetime, timezone, timedelta from typing import Optional, Tuple, List from services.common.models.user import User @@ -97,3 +98,62 @@ class UserRepository: self.db.commit() self.db.refresh(admin_user) return admin_user + + def get_registered_user_count(self, start_at: Optional[datetime] = None, end_at: Optional[datetime] = None) -> int: + """ + Get total number of registered users + + Args: + start_at (Optional[datetime], optional): Start time. Defaults to None. + end_at (Optional[datetime], optional): End time. Defaults to None. + + Returns: + int: Total number of registered users + """ + query = self.db.query(User).filter(User.role_id == 2) + + # Apply server timezone when filtering by time range + offset_td = datetime.now().astimezone().utcoffset() or timedelta(0) + offset_minutes = int(offset_td.total_seconds() // 60) + local_dt = func.timestampadd(literal_column('MINUTE'), offset_minutes, User.created_at) + + if start_at: + start_local = start_at.astimezone().replace(tzinfo=None) if start_at.tzinfo is not None else start_at + query = query.filter(local_dt >= start_local) + if end_at: + end_local = end_at.astimezone().replace(tzinfo=None) if end_at.tzinfo is not None else end_at + query = query.filter(local_dt <= end_local) + return query.count() + + def get_registered_user_trend(self, start_at: Optional[datetime] = None, end_at: Optional[datetime] = None) -> list: + """ + Get registered user trend by day + + Args: + start_at (Optional[datetime], optional): Start time. Defaults to None. + end_at (Optional[datetime], optional): End time. Defaults to None. + + Returns: + list: Registered user trend by day + """ + # Group by server-local day: shift UTC created_at by server TZ offset, then take DATE + offset_td = datetime.now().astimezone().utcoffset() or timedelta(0) + offset_minutes = int(offset_td.total_seconds() // 60) + local_dt = func.timestampadd(literal_column('MINUTE'), offset_minutes, User.created_at) + day_col = func.date(local_dt) + query = ( + self.db.query( + day_col.label("stats_day"), + func.count(User.id).label("registered_count"), + ) + .filter(User.role_id == 2) + ) + + if start_at is not None: + query = query.filter(User.created_at >= start_at) + if end_at is not None: + query = query.filter(User.created_at <= end_at) + + rows = query.group_by(day_col).order_by(day_col.asc()).all() + return [{"stats_day": row.stats_day, "count": int(row.registered_count or 0)} for row in rows] + \ No newline at end of file diff --git a/services/admin_service/services/billing_message_handler.py b/services/admin_service/services/billing_message_handler.py index 5ab2743..52f4573 100644 --- a/services/admin_service/services/billing_message_handler.py +++ b/services/admin_service/services/billing_message_handler.py @@ -6,6 +6,7 @@ import json import uuid import logging from datetime import datetime, timezone + from decimal import Decimal from typing import Optional from sqlalchemy.orm import Session @@ -14,6 +15,7 @@ from services.common.models.billing import BillingMessage from services.common.models.mcp_call_log import McpCallLog, ProcessStatus from services.common.models.user_wallet_history import UserWalletHistory, TransactionType, PaymentMethod from services.admin_service.repositories.mcp_call_log_repository import McpCallLogRepository +from services.admin_service.repositories.stats_mcp_service_date_repository import StatsMcpServiceDateRepository from services.admin_service.repositories.user_wallet_repository import UserWalletRepository from services.admin_service.repositories.user_wallet_history_repository import UserWalletHistoryRepository from services.common.redis import redis_client @@ -26,6 +28,7 @@ class BillingMessageHandler: def __init__(self, db: Session): self.db = db + self.stats_repo = StatsMcpServiceDateRepository(db) self.call_log_repo = McpCallLogRepository(db) self.wallet_repo = UserWalletRepository(db) self.wallet_history_repo = UserWalletHistoryRepository(db) @@ -59,7 +62,13 @@ class BillingMessageHandler: # Update record status to failed self.call_log_repo.update_status(call_log_id, ProcessStatus.FAILED, "Billing processing failed") return False - + # Update stats_mcp_service_date record + # 统计按小时分桶(UTC 时区),对齐到整点 + start_dt = billing_message.call_start_time + start_utc = start_dt.replace(tzinfo=timezone.utc) if start_dt.tzinfo is None else start_dt.astimezone(timezone.utc) + # Store as naive UTC datetime to match MySQL DATETIME behavior + stats_date = start_utc.replace(minute=0, second=0, microsecond=0, tzinfo=None) + self.stats_repo.increment(billing_message.service_id, stats_date, 1) # Update record status to processed self.call_log_repo.update_status(call_log_id, ProcessStatus.PROCESSED) logger.info(f"Billing message processed successfully - User ID: {billing_message.user_id}, Tool: {billing_message.tool_name}") @@ -204,6 +213,8 @@ class BillingMessageHandler: # Update API call record's actual deduction amount and associated history record ID self.call_log_repo.update_status(call_log_id, ProcessStatus.PROCESSED, None, history_id) + + # Update wallet balance cache in Redis self._update_wallet_cache(user_id, new_balance) diff --git a/services/admin_service/services/mcp_manager_service.py b/services/admin_service/services/mcp_manager_service.py index fc1fbb9..5bb0457 100644 --- a/services/admin_service/services/mcp_manager_service.py +++ b/services/admin_service/services/mcp_manager_service.py @@ -168,29 +168,10 @@ class McpManagerService: existing_service.headers = json.dumps(body["headers"]) else: existing_service.headers = "[]" - # if "auth_method" in body: - # auth_method_value = body["auth_method"] - # # If auth_method is None, empty string, or "none", default to free - # if auth_method_value is None or auth_method_value == "" or auth_method_value == "none": - # existing_service.auth_method = AuthMethod.FREE - # else: - # # Ensure the provided value is a valid AuthMethod value - # try: - # if isinstance(auth_method_value, str): - # existing_service.auth_method = AuthMethod(auth_method_value.lower()) - # else: - # existing_service.auth_method = auth_method_value - # except ValueError: - # # If the provided value is not a valid AuthMethod, default to FREE - # existing_service.auth_method = AuthMethod.FREE - # else: - # existing_service.auth_method = AuthMethod.FREE + if "base_url" in body and body["base_url"] is not None: existing_service.base_url = body["base_url"] - # if "auth_header" in body and body["auth_header"] is not None: - # existing_service.auth_header = body["auth_header"] - # if "auth_token" in body and body["auth_token"] is not None: - # existing_service.auth_token = body["auth_token"] + if "charge_type" in body and body["charge_type"] is not None: charge_type_value = body["charge_type"] try: @@ -287,12 +268,10 @@ class McpManagerService: service_info = { "id": service.id, "name": service.name, + "slug_name": service.slug_name, "short_description": service.short_description, "long_description": service.long_description, "base_url": service.base_url, - # "auth_method": service.auth_method.value if service.auth_method != AuthMethod.FREE else "none", - # "auth_header": service.auth_header, - # "auth_token": service.auth_token, "headers":json.loads(service.headers) if service.headers else [], "charge_type": service.charge_type.value if service.charge_type else None, "price": str(float(service.price)) if service.price and service.charge_type == ChargeType.PER_CALL else "0.00", @@ -344,10 +323,7 @@ class McpManagerService: mcp_service.slug_name = slug_name mcp_service.short_description = openapi_data.description[:255] if openapi_data.description else openapi_data.title mcp_service.long_description = openapi_data.description - # mcp_service.auth_method = AuthMethod.FREE # Default to free mcp_service.base_url = "" # Requires user configuration later - # mcp_service.auth_header = "" - # mcp_service.auth_token = "" mcp_service.headers = "[]" mcp_service.charge_type = ChargeType.FREE # Default to free mcp_service.price = 0.0 @@ -468,9 +444,6 @@ class McpManagerService: "short_description": temp_service.short_description, "long_description": temp_service.long_description, "base_url": temp_service.base_url, - # "auth_method": temp_service.auth_method.value if temp_service.auth_method else None, - # "auth_header": temp_service.auth_header, - # "auth_token": temp_service.auth_token, "headers": json.loads(temp_service.headers) if temp_service.headers else [], "charge_type": temp_service.charge_type.value if temp_service.charge_type else None, "price": str(float(temp_service.price)) if temp_service.price and temp_service.charge_type == ChargeType.PER_CALL else "0.00", diff --git a/services/admin_service/services/stats_service.py b/services/admin_service/services/stats_service.py new file mode 100644 index 0000000..22f2b49 --- /dev/null +++ b/services/admin_service/services/stats_service.py @@ -0,0 +1,46 @@ +from sqlalchemy.orm import Session +from typing import Optional, List +from services.common.database import SessionLocal +from datetime import datetime + +from services.common.models.user import User + +from services.admin_service.repositories.user_repository import UserRepository +from services.admin_service.repositories.user_wallet_repository import UserWalletRepository + +class StatsService: + def __init__(self, db: Session = SessionLocal()): + self.user_repository = UserRepository(db) + self.user_wallet_repository = UserWalletRepository(db) + + def get_total_registered_users(self) -> int: + """ + Get total number of registered users + + Returns: + int: Total number of registered users + """ + return self.user_repository.get_registered_user_count() + + def get_today_registered_user_count(self) -> int: + """ + Get today number of registered users + + Returns: + int: Today number of registered users + """ + return self.user_repository.get_registered_user_count(datetime.now()) + + def get_registered_user_count_by_day(self, start_at: Optional[datetime] = None, end_at: Optional[datetime] = None) -> List[dict]: + """ + Get registered user count by day + + Args: + start_at (Optional[datetime], optional): Start time. Defaults to None. + end_at (Optional[datetime], optional): End time. Defaults to None. + + Returns: + List[dict]: List of registered user count by day + """ + return self.user_repository.get_registered_user_trend(start_at, end_at) + diff --git a/services/admin_service/utils/ip.py b/services/admin_service/utils/ip.py new file mode 100644 index 0000000..d2fa6e4 --- /dev/null +++ b/services/admin_service/utils/ip.py @@ -0,0 +1,46 @@ +import socket +import json +import urllib.request +from typing import Optional +import logging + +logger = logging.getLogger(__name__) + +def get_public_ip(timeout: float = 2.0) -> Optional[str]: + providers = [ + "https://api.ipify.org?format=json", + "https://checkip.amazonaws.com", + "https://ifconfig.me/ip", + ] + for url in providers: + try: + with urllib.request.urlopen(url, timeout=timeout) as resp: + content = resp.read().decode("utf-8").strip() + if content.startswith("{"): + try: + data = json.loads(content) + ip = data.get("ip") + except Exception: + ip = None + else: + ip = content.split()[0] if content else None + if ip: + return ip + except Exception as e: + logger.debug(f"Public IP provider failed {url}: {e}") + return None + +def get_local_ip() -> str: + try: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.connect(("8.8.8.8", 80)) + ip = s.getsockname()[0] + s.close() + return ip + except Exception as e: + logger.debug(f"Local IP detection via socket failed: {e}") + try: + return socket.gethostbyname(socket.gethostname()) + except Exception as e: + logger.debug(f"Local IP detection via hostname failed: {e}") + return "127.0.0.1" \ No newline at end of file diff --git a/services/api_service/services/billing_service.py b/services/api_service/services/billing_service.py index ec67af2..4277394 100644 --- a/services/api_service/services/billing_service.py +++ b/services/api_service/services/billing_service.py @@ -196,8 +196,15 @@ class BillingService: if not service: raise ValueError(f"Service not found: {service_id}") - + if not service.price: + service.price = 0 + if not service.input_token_price: + service.input_token_price = 0 + if not service.output_token_price: + service.output_token_price = 0 price = Decimal(str(service.price)) + + input_token_price = Decimal(str(service.input_token_price)) output_token_price = Decimal(str(service.output_token_price)) charge_type = service.charge_type diff --git a/services/api_service/services/mcp_server_factory.py b/services/api_service/services/mcp_server_factory.py index 4fe887c..929ad20 100644 --- a/services/api_service/services/mcp_server_factory.py +++ b/services/api_service/services/mcp_server_factory.py @@ -177,11 +177,11 @@ class McpServerFactory: logger.info(f"Found tool configuration: {tool_config.name}") # Get service authentication info - auth_info = mcp_service.get_service_auth_info(service_id) - logger.debug(f"Authentication info: {auth_info}") + call_params = mcp_service.get_service_call_params(service_id) + logger.debug(f"Call params: {call_params}") # Execute tool - result = await self.tool_service.execute_tool(tool_config, arguments, auth_info) + result = await self.tool_service.execute_tool(tool_config, arguments, call_params) call_success = True logger.info(f"Tool call successful - User ID: {user_id}, Tool: {name}") diff --git a/services/api_service/services/mcp_service.py b/services/api_service/services/mcp_service.py index 64a1992..527f5cb 100644 --- a/services/api_service/services/mcp_service.py +++ b/services/api_service/services/mcp_service.py @@ -257,26 +257,17 @@ class McpService: Optional[McpServiceModel]: Service information, returns None if not found """ return self.service_repository.get_by_id(service_id) - - def get_service_auth_info(self, service_id: str) -> dict: - """ - Get service authentication information - - Args: - service_id: Service ID - - Returns: - dict: Dictionary containing base_url and authentication information - """ + def get_service_call_params(self, service_id: str) -> dict: service = self.service_repository.get_by_id(service_id) if not service: return {} - - auth_info = { + headers = {} + if service.headers: + for item in json.loads(service.headers): + if "name" in item and "value" in item: + headers[item["name"]] = item["value"] + return { "base_url": service.base_url or "", - "auth_method": service.auth_method.value if service.auth_method else "free", - "auth_header": service.auth_header or "", - "auth_token": service.auth_token or "" + "headers": headers } - - return auth_info + diff --git a/services/api_service/services/mcp_tool_service.py b/services/api_service/services/mcp_tool_service.py index b829971..3296947 100644 --- a/services/api_service/services/mcp_tool_service.py +++ b/services/api_service/services/mcp_tool_service.py @@ -17,7 +17,7 @@ class McpToolService: def __init__(self): self.http_builder = HttpRequestBuilder() - async def execute_tool(self, tool_config, arguments: dict, auth_info: dict) -> List[types.Content]: + async def execute_tool(self, tool_config, arguments: dict, call_params: dict) -> List[types.Content]: """ Execute tool call @@ -33,7 +33,7 @@ class McpToolService: logger.info(f"Starting tool execution: {tool_config.name}") # Build HTTP request - request_info = self.http_builder.build_request(tool_config, arguments, auth_info) + request_info = self.http_builder.build_request(tool_config, arguments, call_params) # Send HTTP request response_text = await self._send_http_request(request_info) diff --git a/services/api_service/utils/http_client.py b/services/api_service/utils/http_client.py index 7a7fd7e..08690f1 100644 --- a/services/api_service/utils/http_client.py +++ b/services/api_service/utils/http_client.py @@ -73,7 +73,7 @@ class HttpRequestBuilder: logger.warning(f"Failed to parse {param_type} parameters. Data: {params_str[:100]}...") return [] - def build_request(self, tool_config, arguments: dict, auth_info: dict) -> Dict[str, Any]: + def build_request(self, tool_config, arguments: dict, call_params: dict) -> Dict[str, Any]: """ Build HTTP request information @@ -89,12 +89,12 @@ class HttpRequestBuilder: logger.debug(f"Original path: {tool_config.path}") logger.debug(f"HTTP method: {tool_config.method.value}") logger.debug(f"Input arguments: {arguments}") - + logger.debug(f"Call parameters: {call_params}") # Build URL - url = self._build_url(tool_config, arguments, auth_info) + url = self._build_url(tool_config, arguments, call_params.get("base_url", "")) # Build headers - headers = self._build_headers(tool_config, arguments, auth_info) + headers = self._build_headers(tool_config, arguments, call_params.get("headers", {})) # Build query parameters query_params = self._build_query_params(tool_config, arguments) @@ -113,7 +113,7 @@ class HttpRequestBuilder: logger.debug(f"Built request information: {request_info}") return request_info - def _build_url(self, tool_config, arguments: dict, auth_info: dict) -> str: + def _build_url(self, tool_config, arguments: dict, base_url: str) -> str: """ Build request URL @@ -125,7 +125,6 @@ class HttpRequestBuilder: Returns: str: Complete request URL """ - base_url = auth_info.get("base_url", "") url = tool_config.path logger.debug(f"Service Base URL: {base_url}") @@ -177,7 +176,7 @@ class HttpRequestBuilder: return url - def _build_headers(self, tool_config, arguments: dict, auth_info: dict) -> Dict[str, str]: + def _build_headers(self, tool_config, arguments: dict, headers: dict) -> Dict[str, str]: """ Build request headers @@ -189,10 +188,11 @@ class HttpRequestBuilder: Returns: Dict[str, str]: Request headers dictionary """ - headers = {"User-Agent": "MCP Tool Server (XPack)"} + # headers = {"User-Agent": "MCP Tool Server (XPack)"} + headers["User-Agent"] = "MCP Tool Server (XPack)" # Add authentication headers - self._add_auth_headers(headers, auth_info) + # self._add_auth_headers(headers, auth_info) # Add custom headers self._add_custom_headers(tool_config, arguments, headers) @@ -200,25 +200,25 @@ class HttpRequestBuilder: logger.debug(f"Final request headers: {headers}") return headers - def _add_auth_headers(self, headers: Dict[str, str], auth_info: dict) -> None: - """ - Add authentication headers + # def _add_auth_headers(self, headers: Dict[str, str], auth_info: dict) -> None: + # """ + # Add authentication headers - Args: - headers: Request headers dictionary - auth_info: Authentication information - """ - auth_method = auth_info.get("auth_method", "free") - logger.debug(f"Authentication method: {auth_method}") + # Args: + # headers: Request headers dictionary + # auth_info: Authentication information + # """ + # auth_method = auth_info.get("auth_method", "free") + # logger.debug(f"Authentication method: {auth_method}") - if auth_method != "free": - auth_header = auth_info.get("auth_header") - auth_token = auth_info.get("auth_token") - if auth_header and auth_token: - headers[auth_header] = auth_token - # Hide token details, only show first few characters - token_display = auth_token[:8] + "..." if len(auth_token) > 8 else "***" - logger.debug(f"Added auth header: {auth_header} = {token_display}") + # if auth_method != "free": + # auth_header = auth_info.get("auth_header") + # auth_token = auth_info.get("auth_token") + # if auth_header and auth_token: + # headers[auth_header] = auth_token + # # Hide token details, only show first few characters + # token_display = auth_token[:8] + "..." if len(auth_token) > 8 else "***" + # logger.debug(f"Added auth header: {auth_header} = {token_display}") def _add_custom_headers(self, tool_config, arguments: dict, headers: Dict[str, str]) -> None: """ diff --git a/services/common/models/stats_mcp_service_date.py b/services/common/models/stats_mcp_service_date.py new file mode 100644 index 0000000..3cac697 --- /dev/null +++ b/services/common/models/stats_mcp_service_date.py @@ -0,0 +1,46 @@ + +from sqlalchemy import String, Integer, DateTime +from sqlalchemy.sql import func +from sqlalchemy.orm import Mapped, mapped_column +from services.common.models.base import Base +from datetime import datetime + + +class StatsMcpServiceDate(Base): + __tablename__ = "stats_mcp_service_date" + stats_date: Mapped[datetime] = mapped_column( + DateTime, + primary_key=True, + nullable=False, + comment="统计时间(精确到小时,UTC)", + ) + + service_id: Mapped[str] = mapped_column( + String(100), + primary_key=True, + nullable=False, + comment="服务ID", + ) + + call_count: Mapped[int] = mapped_column( + Integer, + nullable=False, + default=0, + comment="调用次数", + ) + + created_at: Mapped[datetime] = mapped_column( + DateTime, + nullable=True, + server_default=func.current_timestamp(), + comment="创建时间", + ) + + updated_at: Mapped[datetime] = mapped_column( + DateTime, + nullable=True, + server_default=func.current_timestamp(), + server_onupdate=func.current_timestamp(), + comment="更新时间", + ) + \ No newline at end of file