mcpstat 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mcpstat/__init__.py +82 -0
- mcpstat/core.py +371 -0
- mcpstat/database.py +506 -0
- mcpstat/logging.py +135 -0
- mcpstat/prompts.py +194 -0
- mcpstat/py.typed +1 -0
- mcpstat/tools.py +142 -0
- mcpstat/utils.py +141 -0
- mcpstat-0.1.0.dist-info/METADATA +457 -0
- mcpstat-0.1.0.dist-info/RECORD +12 -0
- mcpstat-0.1.0.dist-info/WHEEL +4 -0
- mcpstat-0.1.0.dist-info/licenses/LICENSE +21 -0
mcpstat/__init__.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""
|
|
2
|
+
MCPStat - Usage tracking and analytics for MCP servers.
|
|
3
|
+
https://github.com/tekkidev/mcpstat
|
|
4
|
+
|
|
5
|
+
Copyright (c) 2026 Vadim Bakhrenkov
|
|
6
|
+
SPDX-License-Identifier: MIT
|
|
7
|
+
|
|
8
|
+
A pure-stdlib Python package for adding SQLite-backed usage statistics,
|
|
9
|
+
optional file logging, and built-in analytics to Model Context Protocol servers.
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from mcp.server import Server
|
|
15
|
+
from mcpstat import MCPStat
|
|
16
|
+
|
|
17
|
+
app = Server("my-server")
|
|
18
|
+
stat = MCPStat("my-server") # That's it!
|
|
19
|
+
|
|
20
|
+
@app.call_tool()
|
|
21
|
+
async def handle_tool(name: str, arguments: dict):
|
|
22
|
+
await stat.record(name, "tool")
|
|
23
|
+
# ... your logic
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Features
|
|
27
|
+
|
|
28
|
+
- 📊 SQLite-backed usage tracking for tools, prompts, resources
|
|
29
|
+
- 📝 Optional file-based audit logging
|
|
30
|
+
- 🔧 Built-in stats query functions
|
|
31
|
+
- 💬 Stats prompt generator for LLM consumption
|
|
32
|
+
- 🏷️ Metadata enrichment (tags, descriptions)
|
|
33
|
+
- ⚡ Async-first, thread-safe design
|
|
34
|
+
- 🔒 No required dependencies (pure Python stdlib)
|
|
35
|
+
|
|
36
|
+
## Configuration
|
|
37
|
+
|
|
38
|
+
All settings are passed at initialization:
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
stat = MCPStat(
|
|
42
|
+
server_name="my-server",
|
|
43
|
+
db_path="./my_mcp_data.sqlite",
|
|
44
|
+
log_path="./my_mcp.log",
|
|
45
|
+
log_enabled=True,
|
|
46
|
+
metadata_presets={
|
|
47
|
+
"my_tool": {"tags": ["api"], "short": "My tool description"}
|
|
48
|
+
}
|
|
49
|
+
)
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Environment variables (optional override):
|
|
53
|
+
- `MCPSTAT_DB_PATH`: SQLite database path
|
|
54
|
+
- `MCPSTAT_LOG_PATH`: Log file path
|
|
55
|
+
- `MCPSTAT_LOG_ENABLED`: Enable file logging (true/1/yes)
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
from __future__ import annotations
|
|
59
|
+
|
|
60
|
+
__version__ = "0.1.0"
|
|
61
|
+
__author__ = "Vadim Bakhrenkov"
|
|
62
|
+
__license__ = "MIT"
|
|
63
|
+
|
|
64
|
+
from mcpstat.core import MCPStat
|
|
65
|
+
from mcpstat.database import MCPStatDatabase
|
|
66
|
+
from mcpstat.logging import MCPStatLogger
|
|
67
|
+
from mcpstat.prompts import build_prompt_definition, generate_stats_prompt
|
|
68
|
+
from mcpstat.tools import BuiltinToolsHandler, build_tool_definitions
|
|
69
|
+
from mcpstat.utils import derive_short_description, normalize_tags
|
|
70
|
+
|
|
71
|
+
__all__ = [
|
|
72
|
+
"BuiltinToolsHandler",
|
|
73
|
+
"MCPStat",
|
|
74
|
+
"MCPStatDatabase",
|
|
75
|
+
"MCPStatLogger",
|
|
76
|
+
"__version__",
|
|
77
|
+
"build_prompt_definition",
|
|
78
|
+
"build_tool_definitions",
|
|
79
|
+
"derive_short_description",
|
|
80
|
+
"generate_stats_prompt",
|
|
81
|
+
"normalize_tags",
|
|
82
|
+
]
|
mcpstat/core.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
"""
|
|
2
|
+
MCPStat - Usage tracking and analytics for MCP servers.
|
|
3
|
+
https://github.com/tekkidev/mcpstat
|
|
4
|
+
|
|
5
|
+
Copyright (c) 2026 Vadim Bakhrenkov
|
|
6
|
+
SPDX-License-Identifier: MIT
|
|
7
|
+
|
|
8
|
+
Core MCPStat class - the main entry point for mcpstat.
|
|
9
|
+
|
|
10
|
+
Provides a simple, unified API for usage tracking and analytics.
|
|
11
|
+
All configuration is passed at initialization time.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import sys
|
|
18
|
+
from typing import TYPE_CHECKING, Any
|
|
19
|
+
|
|
20
|
+
from mcpstat.database import MCPStatDatabase
|
|
21
|
+
from mcpstat.logging import MCPStatLogger
|
|
22
|
+
from mcpstat.utils import derive_short_description, normalize_tags
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from typing import Literal
|
|
26
|
+
|
|
27
|
+
# Default paths - descriptive names for discoverability
|
|
28
|
+
DEFAULT_DB_PATH = "./mcp_stat_data.sqlite"
|
|
29
|
+
DEFAULT_LOG_PATH = "./mcp_stat.log"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class MCPStat:
|
|
33
|
+
"""Main statistics tracking class for MCP servers.
|
|
34
|
+
|
|
35
|
+
Provides a unified API for:
|
|
36
|
+
- Recording tool/prompt/resource invocations
|
|
37
|
+
- Querying usage statistics
|
|
38
|
+
- Managing tool metadata
|
|
39
|
+
- Optional file-based audit logging
|
|
40
|
+
|
|
41
|
+
All configuration is passed at initialization - no config files needed.
|
|
42
|
+
Environment variables can override defaults.
|
|
43
|
+
|
|
44
|
+
Example:
|
|
45
|
+
```python
|
|
46
|
+
from mcpstat import MCPStat
|
|
47
|
+
|
|
48
|
+
# Basic usage
|
|
49
|
+
stat = MCPStat("my-server")
|
|
50
|
+
|
|
51
|
+
# With all options
|
|
52
|
+
stat = MCPStat(
|
|
53
|
+
server_name="my-server",
|
|
54
|
+
db_path="./stats.sqlite",
|
|
55
|
+
log_path="./usage.log",
|
|
56
|
+
log_enabled=True,
|
|
57
|
+
metadata_presets={
|
|
58
|
+
"my_tool": {"tags": ["api"], "short": "My description"}
|
|
59
|
+
}
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
# In your tool handler
|
|
63
|
+
@app.call_tool()
|
|
64
|
+
async def handle_tool(name: str, arguments: dict):
|
|
65
|
+
await stat.record(name, "tool")
|
|
66
|
+
# ... your logic
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Environment Variables:
|
|
70
|
+
MCPSTAT_DB_PATH: Override db_path
|
|
71
|
+
MCPSTAT_LOG_PATH: Override log_path
|
|
72
|
+
MCPSTAT_LOG_ENABLED: Override log_enabled (true/1/yes)
|
|
73
|
+
|
|
74
|
+
Thread Safety:
|
|
75
|
+
All async methods are thread-safe via asyncio.Lock in database layer.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
__slots__ = (
|
|
79
|
+
"_db",
|
|
80
|
+
"_logger",
|
|
81
|
+
"_tools_cache",
|
|
82
|
+
"cleanup_orphans",
|
|
83
|
+
"db_path",
|
|
84
|
+
"log_enabled",
|
|
85
|
+
"log_path",
|
|
86
|
+
"metadata_presets",
|
|
87
|
+
"server_name",
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
def __init__(
|
|
91
|
+
self,
|
|
92
|
+
server_name: str,
|
|
93
|
+
*,
|
|
94
|
+
db_path: str | None = None,
|
|
95
|
+
log_path: str | None = None,
|
|
96
|
+
log_enabled: bool | None = None,
|
|
97
|
+
metadata_presets: dict[str, dict[str, Any]] | None = None,
|
|
98
|
+
cleanup_orphans: bool = True,
|
|
99
|
+
) -> None:
|
|
100
|
+
"""Initialize MCP statistics tracking.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
server_name: Server identifier (used in prompts/descriptions)
|
|
104
|
+
db_path: Path to SQLite database (default: ./mcp_stat_data.sqlite)
|
|
105
|
+
log_path: Path to log file (default: ./mcp_stat.log)
|
|
106
|
+
log_enabled: Enable file logging (default: False, or env var)
|
|
107
|
+
metadata_presets: Pre-defined tool metadata {name: {tags, short}}
|
|
108
|
+
cleanup_orphans: Auto-remove metadata for unregistered tools
|
|
109
|
+
|
|
110
|
+
Environment Variable Overrides:
|
|
111
|
+
MCPSTAT_DB_PATH: Override db_path
|
|
112
|
+
MCPSTAT_LOG_PATH: Override log_path
|
|
113
|
+
MCPSTAT_LOG_ENABLED: Override log_enabled
|
|
114
|
+
"""
|
|
115
|
+
self.server_name = server_name
|
|
116
|
+
self.cleanup_orphans = cleanup_orphans
|
|
117
|
+
self.metadata_presets = metadata_presets or {}
|
|
118
|
+
self._tools_cache: list[Any] | None = None
|
|
119
|
+
|
|
120
|
+
# Resolve paths with env var overrides
|
|
121
|
+
self.db_path = os.getenv("MCPSTAT_DB_PATH", db_path or DEFAULT_DB_PATH)
|
|
122
|
+
self.log_path = os.getenv("MCPSTAT_LOG_PATH", log_path or DEFAULT_LOG_PATH)
|
|
123
|
+
|
|
124
|
+
# Resolve log_enabled with env var override
|
|
125
|
+
env_log = os.getenv("MCPSTAT_LOG_ENABLED", "").lower()
|
|
126
|
+
if env_log in ("true", "1", "yes"):
|
|
127
|
+
self.log_enabled = True
|
|
128
|
+
elif env_log in ("false", "0", "no"):
|
|
129
|
+
self.log_enabled = False
|
|
130
|
+
else:
|
|
131
|
+
self.log_enabled = log_enabled if log_enabled is not None else False
|
|
132
|
+
|
|
133
|
+
# Initialize components
|
|
134
|
+
self._db = MCPStatDatabase(self.db_path)
|
|
135
|
+
self._logger = MCPStatLogger(self.log_path if self.log_enabled else None)
|
|
136
|
+
|
|
137
|
+
async def record(
|
|
138
|
+
self,
|
|
139
|
+
name: str,
|
|
140
|
+
primitive_type: Literal['tool', 'prompt', 'resource'] = "tool",
|
|
141
|
+
*,
|
|
142
|
+
success: bool = True,
|
|
143
|
+
error_msg: str | None = None,
|
|
144
|
+
) -> None:
|
|
145
|
+
"""Record a tool/prompt/resource invocation.
|
|
146
|
+
|
|
147
|
+
Call this at the START of handlers to guarantee 100% coverage.
|
|
148
|
+
|
|
149
|
+
Args:
|
|
150
|
+
name: Name of the primitive being invoked
|
|
151
|
+
primitive_type: Type of MCP primitive
|
|
152
|
+
success: Whether invocation succeeded
|
|
153
|
+
error_msg: Error message for failures (logged only)
|
|
154
|
+
|
|
155
|
+
Example:
|
|
156
|
+
```python
|
|
157
|
+
@app.call_tool()
|
|
158
|
+
async def handle_tool(name: str, arguments: dict):
|
|
159
|
+
await stat.record(name, "tool")
|
|
160
|
+
# ... your logic
|
|
161
|
+
```
|
|
162
|
+
"""
|
|
163
|
+
# File logging (if enabled)
|
|
164
|
+
self._logger.log(name, primitive_type, success=success, error_msg=error_msg)
|
|
165
|
+
|
|
166
|
+
# SQLite tracking
|
|
167
|
+
try:
|
|
168
|
+
await self._db.record(name, primitive_type)
|
|
169
|
+
except Exception as exc:
|
|
170
|
+
# Never fail the main flow due to tracking
|
|
171
|
+
print(f"[mcpstat] SQLite tracking failed for {name}: {exc}", file=sys.stderr)
|
|
172
|
+
|
|
173
|
+
async def get_stats(
|
|
174
|
+
self,
|
|
175
|
+
*,
|
|
176
|
+
include_zero: bool = True,
|
|
177
|
+
limit: int | None = None,
|
|
178
|
+
type_filter: str | None = None,
|
|
179
|
+
) -> dict[str, Any]:
|
|
180
|
+
"""Get usage statistics.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
include_zero: Include items with zero calls
|
|
184
|
+
limit: Maximum results
|
|
185
|
+
type_filter: Filter by type (tool/prompt/resource)
|
|
186
|
+
|
|
187
|
+
Returns:
|
|
188
|
+
Usage statistics dictionary with stats list
|
|
189
|
+
"""
|
|
190
|
+
return await self._db.get_stats(
|
|
191
|
+
include_zero=include_zero,
|
|
192
|
+
limit=limit,
|
|
193
|
+
type_filter=type_filter,
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
async def get_by_type(self) -> dict[str, Any]:
|
|
197
|
+
"""Get usage statistics grouped by MCP primitive type.
|
|
198
|
+
|
|
199
|
+
Returns:
|
|
200
|
+
Dictionary with by_type grouping and summary
|
|
201
|
+
"""
|
|
202
|
+
return await self._db.get_by_type()
|
|
203
|
+
|
|
204
|
+
async def get_catalog(
|
|
205
|
+
self,
|
|
206
|
+
*,
|
|
207
|
+
tags: list[str] | None = None,
|
|
208
|
+
query: str | None = None,
|
|
209
|
+
include_usage: bool = True,
|
|
210
|
+
limit: int | None = None,
|
|
211
|
+
) -> dict[str, Any]:
|
|
212
|
+
"""Get tool catalog with filtering.
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
tags: Filter by tags (must have all)
|
|
216
|
+
query: Text search
|
|
217
|
+
include_usage: Include usage stats
|
|
218
|
+
limit: Maximum results
|
|
219
|
+
|
|
220
|
+
Returns:
|
|
221
|
+
Catalog dictionary with results
|
|
222
|
+
"""
|
|
223
|
+
return await self._db.get_catalog(
|
|
224
|
+
tags=tags,
|
|
225
|
+
query=query,
|
|
226
|
+
include_usage=include_usage,
|
|
227
|
+
limit=limit,
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
async def sync_tools(self, tools: list[Any]) -> None:
|
|
231
|
+
"""Synchronize tool metadata from MCP Tool objects.
|
|
232
|
+
|
|
233
|
+
Extracts metadata from Tool objects, applies presets,
|
|
234
|
+
and syncs with database.
|
|
235
|
+
|
|
236
|
+
Args:
|
|
237
|
+
tools: List of MCP Tool objects (with .name, .description)
|
|
238
|
+
"""
|
|
239
|
+
tool_dicts = []
|
|
240
|
+
|
|
241
|
+
for tool in tools:
|
|
242
|
+
name = tool.name
|
|
243
|
+
description = getattr(tool, "description", None)
|
|
244
|
+
|
|
245
|
+
# Check for preset metadata
|
|
246
|
+
preset = self.metadata_presets.get(name, {})
|
|
247
|
+
|
|
248
|
+
if preset:
|
|
249
|
+
tags = normalize_tags(preset.get("tags", []))
|
|
250
|
+
short = preset.get("short") or preset.get("short_description") or derive_short_description(description, name)
|
|
251
|
+
else:
|
|
252
|
+
# Generate tags from name (filter stopwords for auto-generated)
|
|
253
|
+
generated = name.replace("-", " ").replace("_", " ").split()
|
|
254
|
+
tags = normalize_tags([name, *generated], filter_stopwords=True)
|
|
255
|
+
short = derive_short_description(description, name)
|
|
256
|
+
|
|
257
|
+
if not tags:
|
|
258
|
+
tags = [name.lower()]
|
|
259
|
+
|
|
260
|
+
tool_dicts.append({
|
|
261
|
+
"name": name,
|
|
262
|
+
"description": description or "",
|
|
263
|
+
"tags": tags,
|
|
264
|
+
"short_description": short,
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
await self._db.sync_metadata(tool_dicts, cleanup_orphans=self.cleanup_orphans)
|
|
268
|
+
self._tools_cache = tools
|
|
269
|
+
|
|
270
|
+
async def sync_prompts(self, prompts: list[Any]) -> None:
|
|
271
|
+
"""Synchronize prompt metadata from MCP Prompt objects.
|
|
272
|
+
|
|
273
|
+
Similar to sync_tools but for prompts. Extracts metadata
|
|
274
|
+
and registers for tracking.
|
|
275
|
+
|
|
276
|
+
Args:
|
|
277
|
+
prompts: List of MCP Prompt objects (with .name, .description)
|
|
278
|
+
"""
|
|
279
|
+
for prompt in prompts:
|
|
280
|
+
name = prompt.name
|
|
281
|
+
description = getattr(prompt, "description", None)
|
|
282
|
+
preset = self.metadata_presets.get(name, {})
|
|
283
|
+
|
|
284
|
+
if preset:
|
|
285
|
+
tags = normalize_tags(preset.get("tags", []))
|
|
286
|
+
short = preset.get("short") or preset.get("short_description") or derive_short_description(description, name)
|
|
287
|
+
else:
|
|
288
|
+
tags = normalize_tags([name, "prompt"], filter_stopwords=True)
|
|
289
|
+
short = derive_short_description(description, name)
|
|
290
|
+
|
|
291
|
+
await self._db.update_metadata(
|
|
292
|
+
name,
|
|
293
|
+
tags=tags,
|
|
294
|
+
short_description=short,
|
|
295
|
+
full_description=description,
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
async def sync_resources(self, resources: list[Any]) -> None:
|
|
299
|
+
"""Synchronize resource metadata from MCP Resource objects.
|
|
300
|
+
|
|
301
|
+
Similar to sync_tools but for resources.
|
|
302
|
+
|
|
303
|
+
Args:
|
|
304
|
+
resources: List of MCP Resource objects (with .name, .description)
|
|
305
|
+
"""
|
|
306
|
+
for resource in resources:
|
|
307
|
+
name = getattr(resource, "name", None) or str(getattr(resource, "uri", "unknown"))
|
|
308
|
+
description = getattr(resource, "description", None)
|
|
309
|
+
preset = self.metadata_presets.get(name, {})
|
|
310
|
+
|
|
311
|
+
if preset:
|
|
312
|
+
tags = normalize_tags(preset.get("tags", []))
|
|
313
|
+
short = preset.get("short") or derive_short_description(description, name)
|
|
314
|
+
else:
|
|
315
|
+
tags = normalize_tags([name, "resource"], filter_stopwords=True)
|
|
316
|
+
short = derive_short_description(description, name)
|
|
317
|
+
|
|
318
|
+
await self._db.update_metadata(
|
|
319
|
+
name,
|
|
320
|
+
tags=tags,
|
|
321
|
+
short_description=short,
|
|
322
|
+
full_description=description,
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
async def register_metadata(
|
|
326
|
+
self,
|
|
327
|
+
name: str,
|
|
328
|
+
*,
|
|
329
|
+
tags: list[str],
|
|
330
|
+
short_description: str,
|
|
331
|
+
full_description: str | None = None,
|
|
332
|
+
) -> None:
|
|
333
|
+
"""Manually register metadata for a primitive.
|
|
334
|
+
|
|
335
|
+
Useful for non-standard primitives or custom tracking.
|
|
336
|
+
|
|
337
|
+
Args:
|
|
338
|
+
name: Primitive name
|
|
339
|
+
tags: List of tags
|
|
340
|
+
short_description: Brief description
|
|
341
|
+
full_description: Full description
|
|
342
|
+
"""
|
|
343
|
+
await self._db.update_metadata(
|
|
344
|
+
name,
|
|
345
|
+
tags=normalize_tags(tags),
|
|
346
|
+
short_description=short_description,
|
|
347
|
+
full_description=full_description,
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
def add_preset(
|
|
351
|
+
self,
|
|
352
|
+
name: str,
|
|
353
|
+
*,
|
|
354
|
+
tags: list[str],
|
|
355
|
+
short: str,
|
|
356
|
+
) -> None:
|
|
357
|
+
"""Add a metadata preset for future sync operations.
|
|
358
|
+
|
|
359
|
+
Args:
|
|
360
|
+
name: Tool name
|
|
361
|
+
tags: List of tags
|
|
362
|
+
short: Short description
|
|
363
|
+
"""
|
|
364
|
+
self.metadata_presets[name] = {"tags": tags, "short": short}
|
|
365
|
+
|
|
366
|
+
def close(self) -> None:
|
|
367
|
+
"""Release resources.
|
|
368
|
+
|
|
369
|
+
Call during server shutdown for clean resource release.
|
|
370
|
+
"""
|
|
371
|
+
self._logger.close()
|