MCP工具调用日志记录器

一个Python包,用于记录MCP工具调用的详细执行信息,提供自动拦截、日志记录和API集成功能。

  • by Anish701
  • Python
  • 本地部署
  • 3 星标
  • 更新于
在 GitHub 查看 Anish701/mcp-telemetry

使用说明

MCP遥测记录仪

一个用于记录MCP(模型上下文协议)工具调用的Python包,其中包含详细的执行信息。此软件包通过API集成提供工具执行的自动拦截和日志记录,以实现集中监控。

特性

  • 自动工具调用拦截:无缝封装MCP工具功能以捕获执行细节
  • 详细日志记录:捕获执行ID、时间戳、持续时间、状态和错误信息
  • API集成:将日志发布到指定的API终结点以进行集中收集
  • JSON输出:结构化日志输出,便于解析和分析
  • 错误处理:使用回退日志记录到stderr的优雅错误处理

通过pyproject.toml进行开发安装

将该包添加到pyproject.toml文件的依赖项数组中,如下所示:

"mcp-telemetry @ git+https://github.com/Anish701/mcp-telemetry.git"

以下是一个示例:

[tool.hatch.metadata]
allow-direct-references = true

[project]
name = "template-mcp-server"
version = "0.1.0"
description = "A template for Model Context Protocol (MCP) server development"
readme = "README.md"
keywords = ["mcp", "template", "server"]
requires-python = ">=3.12"
dependencies = [
    "fastmcp==2.10.4",
    "httpx==0.28.1",
    "pydantic==2.11.7",
    "pydantic-settings==2.10.1",
    "structlog==25.4.0",
    "python-dotenv==1.1.1",
    "fastapi==0.116.0",
    "uvicorn==0.35.0",
    "asyncpg==0.29.0",
    "psycopg2-binary==2.9.9",
    "itsdangerous==2.2.0",
    "requests-oauthlib==2.0.0",
    "mcp-telemetry @ git+https://github.com/Anish701/mcp-telemetry.git"
]

从pyproject.toml重新运行安装

uv pip install -r pyproject.toml

如果您收到与tool.hatch.metadata相关的任何错误,请在pyproject.toml顶部附近添加以下内容

[tool.hatch.metadata]
allow-direct-references = true

注: 在Containerfile中,负责安装依赖项的行(uv pip install)应该有一个--no cache标志,这样每次创建新映像时都会安装最新版本的包。Containerfile安装行应该看起来像这样,没有缓存:

RUN uv pip install --no-cache -r pyproject.toml

通过requirements.txt进行开发安装

将该包添加到requirements.txt文件中,如下所示:

git+https://github.com/Anish701/mcp-telemetry.git

从requirements.txt重新运行安装

pip install -r requirements.txt

从GitHub进行个人安装

您可以使用pip直接从GitHub安装此软件包:

pip install git+https://github.com/Anish701/mcp-telemetry.git

用法

基本用法

您将使用的主要功能是 enable_tool_logging 它会修补您的MCP实例,以自动记录所有工具调用。注意如何 /logs 路线包含在 api_url 参数。

from mcp_telemetry import enable_tool_logging
from fastmcp import FastMCP

# Create your MCP instance
mcp = FastMCP("My MCP Server", host="0.0.0.0", port=8000)

# Enable automatic logging for all tools
enable_tool_logging(
    mcp_instance=mcp, 
    server_name="My MCP Server",
    api_url="http://example-mcp-logs-deployment.openshiftapps.com/logs"
)

# Now all your @mcp.tool decorated functions will be automatically logged
@mcp.tool()
def my_tool(param1: str) -> str:
    """Example tool that will be logged automatically."""
    return f"Processed: {param1}"

使用类结构MCP(模板MCP服务器)

注意如何 enable_tool_logging 被称为 之前 MCP工具已注册。

class TemplateMCPServer:
    """Main Template MCP Server implementation following tools-first architecture.

    This server provides only tools, not resources or prompts, adhering to
    the tools-first architectural pattern for MCP servers.
    """

    def __init__(self):
        """Initialize the MCP server with template tools following tools-first architecture."""
        try:
            # Initialize FastMCP server
            self.mcp = FastMCP("template")

            # Force reconfigure all loggers after FastMCP initialization to ensure structured logging
            force_reconfigure_all_loggers(settings.PYTHON_LOG_LEVEL)

            enable_tool_logging(
                mcp_instance=self.mcp, 
                server_name="Template MCP Server", 
                api_url="http://example-mcp-logs-deployment.openshiftapps.com/logs"
            )

            self._register_mcp_tools()

            logger.info("Template MCP Server initialized successfully")

        except Exception as e:
            logger.error(f"Failed to initialize Template MCP Server: {e}")
            raise

日志输出格式

包将结构化JSON日志输出到配置的API,格式如下:

{
    "execution_id": "550e8400-e29b-41d4-a716-446655440000",
    "tool_name": "my_tool",
    "start_timestamp": "2025-01-15 10:30:45.123",
    "end_timestamp": "2025-01-15 10:30:45.456",
    "duration_ms": 333,
    "server_host": "My MCP Server",
    "status": "SUCCESS",
    "error_message": null
}

日志字段

  • execution_id:每个工具执行的唯一UUID
  • tool_name:执行的工具/功能的名称
  • start_timestamp:ISO格式的开始时间(毫秒)
  • end_timestamp:ISO格式的结束时间(毫秒)
  • duration_ms:执行持续时间(毫秒)
  • server_host:安装过程中提供的服务器名称
  • status:“成功”或“失败”
  • error_message:如果状态为“FAILURE”,则显示错误详细信息,否则为空

API集成

日志会自动作为JSON有效负载发布到配置的API端点。API应使用接受POST请求 Content-Type: application/json.

如果API发布失败,错误信息将记录到stderr:

{
    "LOGGER_ERROR": "Failed to post to API: Connection timeout",
    "API_URL": "https://api.example.com/logs",
    "TIMESTAMP": "2024-01-15 10:30:45.789"
}

错误处理

  • 工具执行错误在仍被记录的同时被正确传播
  • API故障记录到stderr,但不中断工具执行
  • API调用的网络超时设置为5秒