mcpstat 0.2.2__tar.gz → 0.3.0__tar.gz

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.
Files changed (43) hide show
  1. {mcpstat-0.2.2 → mcpstat-0.3.0}/CHANGELOG.md +27 -4
  2. {mcpstat-0.2.2 → mcpstat-0.3.0}/PKG-INFO +69 -26
  3. {mcpstat-0.2.2 → mcpstat-0.3.0}/README.md +56 -18
  4. mcpstat-0.3.0/ThirdPartyNotices.md +95 -0
  5. mcpstat-0.3.0/build_package.py +35 -0
  6. {mcpstat-0.2.2 → mcpstat-0.3.0}/docs/api.md +61 -27
  7. mcpstat-0.3.0/docs/configuration.md +308 -0
  8. {mcpstat-0.2.2 → mcpstat-0.3.0}/docs/index.md +27 -18
  9. {mcpstat-0.2.2 → mcpstat-0.3.0}/docs/latency-tracking.md +32 -22
  10. mcpstat-0.3.0/docs/quickstart.md +334 -0
  11. {mcpstat-0.2.2 → mcpstat-0.3.0}/docs/token-tracking.md +21 -27
  12. mcpstat-0.3.0/examples/check_weather.py +101 -0
  13. {mcpstat-0.2.2 → mcpstat-0.3.0}/examples/example_server.py +75 -36
  14. {mcpstat-0.2.2 → mcpstat-0.3.0}/examples/minimal_server.py +45 -27
  15. mcpstat-0.3.0/examples/weather_server.py +66 -0
  16. mcpstat-0.2.2/llms.txt → mcpstat-0.3.0/llms-full.txt +43 -19
  17. mcpstat-0.3.0/llms.txt +39 -0
  18. {mcpstat-0.2.2 → mcpstat-0.3.0}/mcpstat/__init__.py +17 -12
  19. {mcpstat-0.2.2 → mcpstat-0.3.0}/mcpstat/core.py +72 -20
  20. mcpstat-0.3.0/mcpstat/database.py +541 -0
  21. mcpstat-0.3.0/mcpstat/logging.py +109 -0
  22. {mcpstat-0.2.2 → mcpstat-0.3.0}/mcpstat/prompts.py +5 -1
  23. mcpstat-0.3.0/mcpstat/sdk.py +33 -0
  24. mcpstat-0.3.0/mcpstat/server.py +456 -0
  25. {mcpstat-0.2.2 → mcpstat-0.3.0}/mcpstat/tools.py +7 -1
  26. {mcpstat-0.2.2 → mcpstat-0.3.0}/pyproject.toml +40 -14
  27. mcpstat-0.3.0/server.json +42 -0
  28. mcpstat-0.3.0/tests/conftest.py +93 -0
  29. {mcpstat-0.2.2 → mcpstat-0.3.0}/tests/test_documentation.py +1 -1
  30. {mcpstat-0.2.2 → mcpstat-0.3.0}/tests/test_mcpstat.py +18 -13
  31. mcpstat-0.3.0/tests/test_regressions.py +150 -0
  32. mcpstat-0.3.0/tests/test_sdk.py +114 -0
  33. mcpstat-0.3.0/tests/test_server.py +747 -0
  34. mcpstat-0.3.0/tests/verify_distribution.py +90 -0
  35. mcpstat-0.2.2/docs/configuration.md +0 -234
  36. mcpstat-0.2.2/docs/quickstart.md +0 -209
  37. mcpstat-0.2.2/mcpstat/database.py +0 -716
  38. mcpstat-0.2.2/mcpstat/logging.py +0 -135
  39. mcpstat-0.2.2/tests/conftest.py +0 -52
  40. {mcpstat-0.2.2 → mcpstat-0.3.0}/CODE_OF_CONDUCT.md +0 -0
  41. {mcpstat-0.2.2 → mcpstat-0.3.0}/LICENSE +0 -0
  42. {mcpstat-0.2.2 → mcpstat-0.3.0}/mcpstat/py.typed +0 -0
  43. {mcpstat-0.2.2 → mcpstat-0.3.0}/mcpstat/utils.py +0 -0
@@ -5,7 +5,32 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
- ## [Unreleased]
8
+ ## [0.3.0] - 2026-11-15
9
+
10
+ ### Added
11
+
12
+ - Bundled documentation and demo MCP server, `mcpstat` CLI, SDK v2 integration, and registry manifest.
13
+ - Persistent success, error, cancellation, and incomplete counters; explicit names for tracked handlers.
14
+ - Agent documentation index, full reference, and Markdown alternatives.
15
+
16
+ ### Changed
17
+
18
+ - Nonblocking SQLite operations, isolated server/primitive identities, and catalog synchronization
19
+ that preserves history and includes unused registrations.
20
+ - Rotating JSON Lines logs that omit exception messages; stricter analytics input validation.
21
+ - Inbound SDK tracing disabled in the bundled server and examples; `disable_sdk_tracing()`
22
+ provides the same control for existing SDK v2 servers.
23
+
24
+ ### Migration
25
+
26
+ - Back up databases before the automatic, one-way migration. Keep the server name stable;
27
+ restore the backup to downgrade.
28
+ - The SDK extras require MCP SDK >=2.3,<3; SDK v1 integrations need handler updates.
29
+ The core remains SDK-independent.
30
+ - Update log parsers for JSON Lines. Explicit query limits must be 1-1000; periods accept
31
+ only `all time`. Historical latency averages with unknown sample counts are `None`.
32
+
33
+ See the [upgrade guide](docs/configuration.md#upgrading-from-02x) for compatibility details.
9
34
 
10
35
  ## [0.2.2] - 2026-02-16
11
36
 
@@ -64,7 +89,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
64
89
  - GitHub community files: CONTRIBUTING.md, SECURITY.md, issue/PR templates
65
90
  - Tags System documentation with filtering examples
66
91
  - Expanded API Reference with complete code examples
67
- - Test coverage improved
68
92
 
69
93
  ### Changed
70
94
 
@@ -99,9 +123,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
99
123
  - No required dependencies (pure Python stdlib)
100
124
  - Optional `mcp` extra for MCP SDK integration
101
125
  - Full type annotations with strict mypy compliance (`py.typed` marker included)
102
- - Comprehensive test suite
103
126
 
104
- [Unreleased]: https://github.com/tekkidev/mcpstat/compare/v0.2.2...HEAD
127
+ [0.3.0]: https://github.com/tekkidev/mcpstat/compare/v0.2.2...v0.3.0
105
128
  [0.2.2]: https://github.com/tekkidev/mcpstat/compare/v0.2.1...v0.2.2
106
129
  [0.2.1]: https://github.com/tekkidev/mcpstat/compare/v0.1.2...v0.2.1
107
130
  [0.1.2]: https://github.com/tekkidev/mcpstat/compare/v0.1.1...v0.1.2
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mcpstat
3
- Version: 0.2.2
4
- Summary: Usage tracking, analytics, and file logging for MCP (Model Context Protocol) servers
3
+ Version: 0.3.0
4
+ Summary: Python MCP server observability: usage statistics, outcomes, latency, and optional file logging
5
5
  License: MIT
6
6
  License-File: LICENSE
7
7
  Keywords: mcp,model-context-protocol,statistics,analytics,usage-tracking,logging,ai,llm,agent,mcp-server,tool-tracking,observability,token-tracking,latency-tracking
@@ -19,6 +19,7 @@ Classifier: Programming Language :: Python :: 3.11
19
19
  Classifier: Programming Language :: Python :: 3.12
20
20
  Classifier: Programming Language :: Python :: 3.13
21
21
  Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
22
23
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
24
  Classifier: Topic :: System :: Logging
24
25
  Classifier: Topic :: System :: Monitoring
@@ -26,14 +27,18 @@ Classifier: Typing :: Typed
26
27
  Provides-Extra: all
27
28
  Provides-Extra: dev
28
29
  Provides-Extra: mcp
29
- Requires-Dist: mcp (>=1.0.0) ; extra == "mcp" or extra == "all"
30
- Requires-Dist: mypy (>=1.0) ; extra == "dev" or extra == "all"
31
- Requires-Dist: pytest (>=7.0) ; extra == "dev" or extra == "all"
32
- Requires-Dist: pytest-asyncio (>=0.21) ; extra == "dev" or extra == "all"
33
- Requires-Dist: pytest-cov (>=4.0) ; extra == "dev" or extra == "all"
34
- Requires-Dist: ruff (>=0.1) ; extra == "dev" or extra == "all"
30
+ Provides-Extra: server
31
+ Requires-Dist: jsonschema (>=4.26,<5) ; extra == "server" or extra == "mcp" or extra == "dev" or extra == "all"
32
+ Requires-Dist: mcp (>=2.3.0,<3) ; extra == "server" or extra == "mcp" or extra == "dev" or extra == "all"
33
+ Requires-Dist: mypy (>=2.4,<3) ; extra == "dev" or extra == "all"
34
+ Requires-Dist: platformdirs (>=4.9,<5) ; extra == "server" or extra == "mcp" or extra == "dev" or extra == "all"
35
+ Requires-Dist: pytest (>=8.3,<10) ; extra == "dev" or extra == "all"
36
+ Requires-Dist: pytest-asyncio (>=1.0,<2) ; extra == "dev" or extra == "all"
37
+ Requires-Dist: pytest-cov (>=6,<8) ; extra == "dev" or extra == "all"
38
+ Requires-Dist: ruff (>=0.17,<0.18) ; extra == "dev" or extra == "all"
35
39
  Project-URL: Author, https://vadim.dev
36
40
  Project-URL: Changelog, https://github.com/tekkidev/mcpstat/blob/main/CHANGELOG.md
41
+ Project-URL: Documentation, https://mcpstat.vadim.dev
37
42
  Project-URL: Homepage, https://github.com/tekkidev/mcpstat
38
43
  Project-URL: Issues, https://github.com/tekkidev/mcpstat/issues
39
44
  Project-URL: Repository, https://github.com/tekkidev/mcpstat
@@ -50,38 +55,68 @@ Description-Content-Type: text/markdown
50
55
  [![Security: bandit](https://img.shields.io/badge/security-bandit-yellow.svg)](https://github.com/PyCQA/bandit)
51
56
  [![Codecov](https://codecov.io/gh/tekkidev/mcpstat/branch/main/graph/badge.svg)](https://codecov.io/gh/tekkidev/mcpstat)
52
57
 
53
- **Usage tracking and analytics for MCP servers.** Pure Python, zero required dependencies.
58
+ **Python observability and usage analytics for MCP (Model Context Protocol) servers.**
54
59
 
55
- Track which tools get called, how often, and keep an audit trail - all in 3 lines of code.
60
+ Track tool, prompt, and resource calls, successful and failed invocations, and execution
61
+ latency in local SQLite storage. Add tracking to your existing Python MCP server and
62
+ expose its statistics as MCP tools that an assistant can query. Optional file logging
63
+ provides an audit trail.
56
64
 
57
65
  ## Installation
58
66
 
59
67
  ```bash
60
68
  pip install mcpstat
61
- ```
62
-
63
- With MCP SDK:
64
- ```bash
65
- pip install "mcpstat[mcp]"
69
+ pip install "mcpstat[server]" # Includes the SDK for the example below
66
70
  ```
67
71
 
68
72
  ## Quick Start
69
73
 
70
74
  ```python
71
- from mcp.server import Server
72
- from mcpstat import MCPStat
75
+ from mcp.server import MCPServer
76
+ from mcpstat import MCPStat, disable_sdk_tracing
73
77
 
74
- app = Server("my-server")
78
+ app = MCPServer("my-server")
79
+ disable_sdk_tracing(app)
75
80
  stat = MCPStat("my-server")
76
81
 
77
- @app.call_tool()
78
- @stat.track # ← One decorator does everything!
79
- async def handle_tool(name: str, arguments: dict):
80
- # Your logic here - latency tracked automatically
81
- return await my_logic(arguments)
82
+
83
+ @app.tool()
84
+ @stat.track(name="echo")
85
+ async def echo(message: str) -> str:
86
+ """Return a message, tracking usage and latency automatically."""
87
+ return message
88
+
89
+
90
+ @app.tool()
91
+ async def get_tool_usage_stats() -> dict:
92
+ """Return cumulative MCP usage statistics."""
93
+ return await stat.get_stats()
94
+
95
+
96
+ if __name__ == "__main__":
97
+ try:
98
+ app.run()
99
+ finally:
100
+ stat.close()
82
101
  ```
83
102
 
84
- Then ask your AI assistant: *"Give me MCP usage stats"*
103
+ Connect your assistant to this server, then ask: *"Give me MCP usage stats"*
104
+
105
+ For a complete request-to-statistics example, follow the
106
+ [weather server walkthrough](https://github.com/tekkidev/mcpstat/blob/main/docs/quickstart.md#verify-mcp-tool-usage-with-a-weather-server).
107
+ It demonstrates successful calls, an intentional failure, unused tools, and statistics
108
+ that persist after restarting the server.
109
+
110
+ ## Choose Your Integration
111
+
112
+ | Use case | Installation | What it tracks |
113
+ |----------|--------------|----------------|
114
+ | Add tracking to an existing Python server | `pip install mcpstat` | The handlers you instrument with the SDK-independent library; keep your server's MCP SDK installed separately. |
115
+ | Run the bundled documentation and demonstration server | `pip install "mcpstat[server]"` | Its own temperature conversion tools and other registered handlers. |
116
+
117
+ The decorator records usage; register a statistics tool such as `get_tool_usage_stats`
118
+ to query that data from Claude Code, VS Code, or another MCP client. The standalone
119
+ server does not automatically observe other MCP servers.
85
120
 
86
121
  ## Features
87
122
 
@@ -91,7 +126,11 @@ Then ask your AI assistant: *"Give me MCP usage stats"*
91
126
  - **Token tracking** - Estimate or record actual token usage
92
127
  - **Latency tracking** - Measure execution duration, identify slow tools
93
128
  - **File logging** - Optional timestamped audit trail
94
- - **Async-first** - Thread-safe via `asyncio.Lock`
129
+ - **Async-first** - Database operations run in worker threads with serialized transactions
130
+
131
+ Install `mcpstat` for the SDK-independent tracking library. The `[server]` extra includes
132
+ the SDK and the runnable `mcpstat` documentation and demonstration server. The standalone
133
+ server tracks its own calls; integrate the library into each server you want to monitor.
95
134
 
96
135
  ## Documentation
97
136
 
@@ -102,6 +141,8 @@ Then ask your AI assistant: *"Give me MCP usage stats"*
102
141
  - [API Reference](https://github.com/tekkidev/mcpstat/blob/main/docs/api.md) - Complete method reference
103
142
  - [Token Tracking](https://github.com/tekkidev/mcpstat/blob/main/docs/token-tracking.md) - Cost analysis features
104
143
  - [Latency Tracking](https://github.com/tekkidev/mcpstat/blob/main/docs/latency-tracking.md) - Performance monitoring
144
+ - [Agent Documentation Index](https://mcpstat.vadim.dev/llms.txt) - Links to plain Markdown guides and examples
145
+ - [Full Agent Reference](https://mcpstat.vadim.dev/llms-full.txt) - Detailed integration and API summaries
105
146
 
106
147
  ## Examples
107
148
 
@@ -109,7 +150,7 @@ Then ask your AI assistant: *"Give me MCP usage stats"*
109
150
  # Clone and run example server
110
151
  git clone https://github.com/tekkidev/mcpstat.git
111
152
  cd mcpstat
112
- pip install -e ".[mcp]"
153
+ pip install -e ".[dev]"
113
154
  python examples/example_server.py
114
155
  ```
115
156
 
@@ -128,6 +169,8 @@ pytest tests/
128
169
 
129
170
  MIT - see [LICENSE](https://github.com/tekkidev/mcpstat/blob/main/LICENSE) for details.
130
171
 
172
+ <!-- mcp-name: io.github.tekkidev/mcpstat -->
173
+
131
174
  ---
132
175
 
133
176
  *MCP is a trademark of its respective owners. This project is not affiliated with or endorsed by any trademark holders.*
@@ -9,38 +9,68 @@
9
9
  [![Security: bandit](https://img.shields.io/badge/security-bandit-yellow.svg)](https://github.com/PyCQA/bandit)
10
10
  [![Codecov](https://codecov.io/gh/tekkidev/mcpstat/branch/main/graph/badge.svg)](https://codecov.io/gh/tekkidev/mcpstat)
11
11
 
12
- **Usage tracking and analytics for MCP servers.** Pure Python, zero required dependencies.
12
+ **Python observability and usage analytics for MCP (Model Context Protocol) servers.**
13
13
 
14
- Track which tools get called, how often, and keep an audit trail - all in 3 lines of code.
14
+ Track tool, prompt, and resource calls, successful and failed invocations, and execution
15
+ latency in local SQLite storage. Add tracking to your existing Python MCP server and
16
+ expose its statistics as MCP tools that an assistant can query. Optional file logging
17
+ provides an audit trail.
15
18
 
16
19
  ## Installation
17
20
 
18
21
  ```bash
19
22
  pip install mcpstat
20
- ```
21
-
22
- With MCP SDK:
23
- ```bash
24
- pip install "mcpstat[mcp]"
23
+ pip install "mcpstat[server]" # Includes the SDK for the example below
25
24
  ```
26
25
 
27
26
  ## Quick Start
28
27
 
29
28
  ```python
30
- from mcp.server import Server
31
- from mcpstat import MCPStat
29
+ from mcp.server import MCPServer
30
+ from mcpstat import MCPStat, disable_sdk_tracing
32
31
 
33
- app = Server("my-server")
32
+ app = MCPServer("my-server")
33
+ disable_sdk_tracing(app)
34
34
  stat = MCPStat("my-server")
35
35
 
36
- @app.call_tool()
37
- @stat.track # ← One decorator does everything!
38
- async def handle_tool(name: str, arguments: dict):
39
- # Your logic here - latency tracked automatically
40
- return await my_logic(arguments)
36
+
37
+ @app.tool()
38
+ @stat.track(name="echo")
39
+ async def echo(message: str) -> str:
40
+ """Return a message, tracking usage and latency automatically."""
41
+ return message
42
+
43
+
44
+ @app.tool()
45
+ async def get_tool_usage_stats() -> dict:
46
+ """Return cumulative MCP usage statistics."""
47
+ return await stat.get_stats()
48
+
49
+
50
+ if __name__ == "__main__":
51
+ try:
52
+ app.run()
53
+ finally:
54
+ stat.close()
41
55
  ```
42
56
 
43
- Then ask your AI assistant: *"Give me MCP usage stats"*
57
+ Connect your assistant to this server, then ask: *"Give me MCP usage stats"*
58
+
59
+ For a complete request-to-statistics example, follow the
60
+ [weather server walkthrough](https://github.com/tekkidev/mcpstat/blob/main/docs/quickstart.md#verify-mcp-tool-usage-with-a-weather-server).
61
+ It demonstrates successful calls, an intentional failure, unused tools, and statistics
62
+ that persist after restarting the server.
63
+
64
+ ## Choose Your Integration
65
+
66
+ | Use case | Installation | What it tracks |
67
+ |----------|--------------|----------------|
68
+ | Add tracking to an existing Python server | `pip install mcpstat` | The handlers you instrument with the SDK-independent library; keep your server's MCP SDK installed separately. |
69
+ | Run the bundled documentation and demonstration server | `pip install "mcpstat[server]"` | Its own temperature conversion tools and other registered handlers. |
70
+
71
+ The decorator records usage; register a statistics tool such as `get_tool_usage_stats`
72
+ to query that data from Claude Code, VS Code, or another MCP client. The standalone
73
+ server does not automatically observe other MCP servers.
44
74
 
45
75
  ## Features
46
76
 
@@ -50,7 +80,11 @@ Then ask your AI assistant: *"Give me MCP usage stats"*
50
80
  - **Token tracking** - Estimate or record actual token usage
51
81
  - **Latency tracking** - Measure execution duration, identify slow tools
52
82
  - **File logging** - Optional timestamped audit trail
53
- - **Async-first** - Thread-safe via `asyncio.Lock`
83
+ - **Async-first** - Database operations run in worker threads with serialized transactions
84
+
85
+ Install `mcpstat` for the SDK-independent tracking library. The `[server]` extra includes
86
+ the SDK and the runnable `mcpstat` documentation and demonstration server. The standalone
87
+ server tracks its own calls; integrate the library into each server you want to monitor.
54
88
 
55
89
  ## Documentation
56
90
 
@@ -61,6 +95,8 @@ Then ask your AI assistant: *"Give me MCP usage stats"*
61
95
  - [API Reference](https://github.com/tekkidev/mcpstat/blob/main/docs/api.md) - Complete method reference
62
96
  - [Token Tracking](https://github.com/tekkidev/mcpstat/blob/main/docs/token-tracking.md) - Cost analysis features
63
97
  - [Latency Tracking](https://github.com/tekkidev/mcpstat/blob/main/docs/latency-tracking.md) - Performance monitoring
98
+ - [Agent Documentation Index](https://mcpstat.vadim.dev/llms.txt) - Links to plain Markdown guides and examples
99
+ - [Full Agent Reference](https://mcpstat.vadim.dev/llms-full.txt) - Detailed integration and API summaries
64
100
 
65
101
  ## Examples
66
102
 
@@ -68,7 +104,7 @@ Then ask your AI assistant: *"Give me MCP usage stats"*
68
104
  # Clone and run example server
69
105
  git clone https://github.com/tekkidev/mcpstat.git
70
106
  cd mcpstat
71
- pip install -e ".[mcp]"
107
+ pip install -e ".[dev]"
72
108
  python examples/example_server.py
73
109
  ```
74
110
 
@@ -87,6 +123,8 @@ pytest tests/
87
123
 
88
124
  MIT - see [LICENSE](https://github.com/tekkidev/mcpstat/blob/main/LICENSE) for details.
89
125
 
126
+ <!-- mcp-name: io.github.tekkidev/mcpstat -->
127
+
90
128
  ---
91
129
 
92
130
  *MCP is a trademark of its respective owners. This project is not affiliated with or endorsed by any trademark holders.*
@@ -0,0 +1,95 @@
1
+ # Third-Party Notices
2
+
3
+ mcpstat's optional MCP server uses the following third-party packages.
4
+ Dependencies are installed separately and retain their own license notices.
5
+
6
+ ## mcp (Model Context Protocol SDK)
7
+ - **Description**: The MCP SDK is the official Python implementation of the Model Context Protocol.
8
+ - **License**: MIT License
9
+ - **Project Details**: [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)
10
+ - **License Text**: [License Details](https://github.com/modelcontextprotocol/python-sdk/blob/main/LICENSE)
11
+
12
+ The SDK also supplies the `mcp-types` package used for MCP protocol types.
13
+ Both packages carry the following license and attribution.
14
+
15
+ ```
16
+ MIT License
17
+
18
+ Copyright (c) 2024 Anthropic, PBC
19
+
20
+ Permission is hereby granted, free of charge, to any person obtaining a copy
21
+ of this software and associated documentation files (the "Software"), to deal
22
+ in the Software without restriction, including without limitation the rights
23
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
24
+ copies of the Software, and to permit persons to whom the Software is
25
+ furnished to do so, subject to the following conditions:
26
+
27
+ The above copyright notice and this permission notice shall be included in all
28
+ copies or substantial portions of the Software.
29
+
30
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
31
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
32
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
33
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
34
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
35
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
36
+ SOFTWARE.
37
+ ```
38
+
39
+ ## jsonschema
40
+
41
+ - **Description**: Validation of MCP tool arguments against JSON Schema 2020-12.
42
+ - **License**: MIT License
43
+ - **Project Details**: [jsonschema](https://github.com/python-jsonschema/jsonschema)
44
+
45
+ ```
46
+ Copyright (c) 2013 Julian Berman
47
+
48
+ Permission is hereby granted, free of charge, to any person obtaining a copy
49
+ of this software and associated documentation files (the "Software"), to deal
50
+ in the Software without restriction, including without limitation the rights
51
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
52
+ copies of the Software, and to permit persons to whom the Software is
53
+ furnished to do so, subject to the following conditions:
54
+
55
+ The above copyright notice and this permission notice shall be included in
56
+ all copies or substantial portions of the Software.
57
+
58
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
59
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
60
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
61
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
62
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
63
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
64
+ THE SOFTWARE.
65
+ ```
66
+
67
+ ## platformdirs
68
+
69
+ - **Description**: Platform-specific locations for application data and configuration.
70
+ - **License**: MIT License
71
+ - **Project Details**: [platformdirs](https://github.com/tox-dev/platformdirs)
72
+
73
+ ```
74
+ MIT License
75
+
76
+ Copyright (c) 2010-202x The platformdirs developers
77
+
78
+ Permission is hereby granted, free of charge, to any person obtaining a copy
79
+ of this software and associated documentation files (the "Software"), to deal
80
+ in the Software without restriction, including without limitation the rights
81
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
82
+ copies of the Software, and to permit persons to whom the Software is
83
+ furnished to do so, subject to the following conditions:
84
+
85
+ The above copyright notice and this permission notice shall be included in all
86
+ copies or substantial portions of the Software.
87
+
88
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
89
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
90
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
91
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
92
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
93
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
94
+ SOFTWARE.
95
+ ```
@@ -0,0 +1,35 @@
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
+ Include public documentation resources in source and wheel distributions.
9
+ """
10
+
11
+ from pathlib import Path
12
+ from shutil import copyfile
13
+
14
+
15
+ def build() -> None:
16
+ root = Path(__file__).parent
17
+ target = root / "mcpstat" / "_docs"
18
+ target.mkdir(exist_ok=True)
19
+ for name in (
20
+ "README.md",
21
+ "llms.txt",
22
+ "llms-full.txt",
23
+ "docs/quickstart.md",
24
+ "docs/api.md",
25
+ "docs/configuration.md",
26
+ "docs/token-tracking.md",
27
+ "docs/latency-tracking.md",
28
+ ):
29
+ destination = target / name
30
+ destination.parent.mkdir(parents=True, exist_ok=True)
31
+ copyfile(root / name, destination)
32
+
33
+
34
+ if __name__ == "__main__":
35
+ build()
@@ -31,7 +31,7 @@ stat = MCPStat(
31
31
  | `log_path` | `str` | `./mcp_stat.log` | File log path |
32
32
  | `log_enabled` | `bool` | `False` | Enable file logging |
33
33
  | `metadata_presets` | `dict` | `None` | Pre-defined metadata |
34
- | `cleanup_orphans` | `bool` | `True` | Remove metadata for unregistered tools on sync |
34
+ | `cleanup_orphans` | `bool` | `True` | Deactivate unregistered tools in the catalog while retaining usage |
35
35
 
36
36
  ---
37
37
 
@@ -42,7 +42,6 @@ stat = MCPStat(
42
42
  Decorator that automatically tracks tool calls with latency measurement.
43
43
 
44
44
  ```python
45
- @app.call_tool()
46
45
  @stat.track # ← One decorator does everything!
47
46
  async def handle_tool(name: str, arguments: dict):
48
47
  return await my_logic(arguments)
@@ -89,6 +88,7 @@ await stat.record(
89
88
  primitive_type: Literal["tool", "prompt", "resource"] = "tool",
90
89
  *,
91
90
  success: bool = True,
91
+ outcome: str | None = None,
92
92
  error_msg: str | None = None,
93
93
  response_chars: int | None = None,
94
94
  input_tokens: int | None = None,
@@ -102,7 +102,7 @@ await stat.record(
102
102
  | `name` | `str` | Name of the primitive |
103
103
  | `primitive_type` | `str` | Type: `tool`, `prompt`, or `resource` |
104
104
  | `success` | `bool` | Whether invocation succeeded |
105
- | `error_msg` | `str` | Error message for failures (logged only) |
105
+ | `error_msg` | `str` | Accepted for compatibility; omitted from storage and logs |
106
106
  | `response_chars` | `int` | Response size for token estimation |
107
107
  | `input_tokens` | `int` | Actual input token count |
108
108
  | `output_tokens` | `int` | Actual output token count |
@@ -129,17 +129,17 @@ stats = await stat.get_stats(
129
129
  | Parameter | Type | Description |
130
130
  |-----------|------|-------------|
131
131
  | `include_zero` | `bool` | Include items with zero calls |
132
- | `limit` | `int` | Maximum results to return |
132
+ | `limit` | `int` | 1-1000; default returns at most 1000 rows |
133
133
  | `type_filter` | `str` | Filter by primitive type |
134
134
 
135
135
  **Returns:**
136
136
 
137
137
  ```python
138
138
  {
139
- "tracked_count": int, # Total tracked items
140
- "total_calls": int, # Sum of all call counts
141
- "zero_count": int, # Items with zero calls
142
- "latest_access": str, # Most recent timestamp
139
+ "tracked_count": int, # Total tracked items
140
+ "total_calls": int, # Sum of all call counts
141
+ "zero_count": int, # Items with zero calls
142
+ "latest_access": str, # Most recent timestamp
143
143
  "token_summary": {
144
144
  "total_input_tokens": int,
145
145
  "total_output_tokens": int,
@@ -167,9 +167,14 @@ stats = await stat.get_stats(
167
167
  "total_duration_ms": int,
168
168
  "min_duration_ms": int | None,
169
169
  "max_duration_ms": int | None,
170
- "avg_latency_ms": int,
170
+ "avg_latency_ms": int | None,
171
+ "duration_sample_count": int,
172
+ "success_count": int,
173
+ "error_count": int,
174
+ "cancelled_count": int,
175
+ "incomplete_count": int,
171
176
  }
172
- ]
177
+ ],
173
178
  }
174
179
  ```
175
180
 
@@ -203,16 +208,16 @@ catalog = await stat.get_catalog(
203
208
 
204
209
  ```python
205
210
  {
206
- "total_tracked": int, # Total tools in catalog
207
- "matched": int, # Tools matching filters
208
- "all_tags": list[str], # Complete tag inventory
211
+ "total_tracked": int, # Total tools in catalog
212
+ "matched": int, # Tools matching filters before limit
213
+ "all_tags": list[str], # Complete tag inventory
209
214
  "filters": {
210
215
  "tags": list[str],
211
216
  "query": str | None,
212
217
  },
213
218
  "include_usage": bool,
214
219
  "limit": int | None,
215
- "total_calls": int | None, # None when include_usage=False
220
+ "total_calls": int | None, # None when include_usage=False
216
221
  "results": [
217
222
  {
218
223
  "name": str,
@@ -221,10 +226,10 @@ catalog = await stat.get_catalog(
221
226
  "full_description": str | None,
222
227
  "schema_version": int,
223
228
  "updated_at": str,
224
- "call_count": int | None, # None when include_usage=False
229
+ "call_count": int | None, # None when include_usage=False
225
230
  "last_accessed": str | None,
226
231
  }
227
- ]
232
+ ],
228
233
  }
229
234
  ```
230
235
 
@@ -239,6 +244,8 @@ await stat.report_tokens(
239
244
  name: str,
240
245
  input_tokens: int,
241
246
  output_tokens: int,
247
+ *,
248
+ primitive_type: str = "tool",
242
249
  )
243
250
  ```
244
251
 
@@ -252,11 +259,7 @@ await stat.record("my_tool", "tool")
252
259
 
253
260
  # Later, when you have actual tokens
254
261
  response = await anthropic.messages.create(...)
255
- await stat.report_tokens(
256
- "my_tool",
257
- response.usage.input_tokens,
258
- response.usage.output_tokens
259
- )
262
+ await stat.report_tokens("my_tool", response.usage.input_tokens, response.usage.output_tokens)
260
263
  ```
261
264
 
262
265
  ---
@@ -274,7 +277,7 @@ Auto-extracts tags from tool names and descriptions from tool definitions.
274
277
  **Example:**
275
278
 
276
279
  ```python
277
- tools = await server.list_tools()
280
+ tools = await list_tools()
278
281
  await stat.sync_tools(tools)
279
282
  ```
280
283
 
@@ -456,13 +459,31 @@ Handle stats prompt request from MCP client.
456
459
  ```python
457
460
  from mcpstat.prompts import handle_stats_prompt
458
461
 
459
- result = await handle_stats_prompt(stat, arguments={"period": "past week"})
462
+ result = await handle_stats_prompt(stat, arguments={"period": "all time"})
460
463
  ```
461
464
 
462
465
  ---
463
466
 
464
467
  ## Utility Functions
465
468
 
469
+ ### disable_sdk_tracing()
470
+
471
+ Remove inbound MCP SDK tracing from one server instance without modifying its other
472
+ middleware or global OpenTelemetry configuration. Requires the optional MCP SDK v2
473
+ integration. Call it after constructing the server and before serving requests.
474
+
475
+ ```python
476
+ from mcp.server import MCPServer
477
+ from mcpstat import disable_sdk_tracing
478
+
479
+ app = MCPServer("my-server")
480
+ disable_sdk_tracing(app)
481
+ ```
482
+
483
+ Both `Server` and `MCPServer` are supported. Calling it again is safe. Local mcpstat
484
+ statistics remain enabled. For process-wide signals and propagation settings, see
485
+ [SDK tracing configuration](configuration.md#sdk-tracing-and-local-statistics).
486
+
466
487
  ### normalize_tags()
467
488
 
468
489
  Normalize and filter tags from text.
@@ -470,9 +491,22 @@ Normalize and filter tags from text.
470
491
  ```python
471
492
  from mcpstat.utils import normalize_tags
472
493
 
473
- tags = normalize_tags(
474
- ["Fetch", "Weather", "Data", "the"],
475
- filter_stopwords=True
476
- )
494
+ tags = normalize_tags(["Fetch", "Weather", "Data", "the"], filter_stopwords=True)
477
495
  # ["fetch", "weather", "data"]
478
496
  ```
497
+
498
+ ## Measurement and integration contracts
499
+
500
+ - SDK v2 registers low-level handlers through `Server(on_call_tool=..., on_list_tools=...)`.
501
+ The dispatch functions above are library integration fragments. See the complete
502
+ [quick start](quickstart.md) and [server example](https://github.com/tekkidev/mcpstat/blob/main/examples/example_server.py)
503
+ for the SDK adapters. Individual `MCPServer` tools use `@stat.track(name="tool_name")`.
504
+ - `outcome` accepts `success`, `error`, `cancelled`, or `incomplete`. Cancellation and
505
+ handler errors propagate. Tracking failures do not replace handler results.
506
+ - Registered unused primitives appear in statistics. Summary counts cover the complete
507
+ filtered set, while `limit` caps returned rows. Catalog entries are active tools only.
508
+ - Query text is limited to 1024 characters; tags accept up to 50 strings of 100 characters.
509
+ - Periods accept only `all time`. Other values raise `ValueError`; counters are cumulative.
510
+ - Report resources by full URI and tokens by the same primitive type as the invocation.
511
+ - Token reporting adds to an existing identity without incrementing its call count.
512
+ Measurements must be nonnegative integers. Report each measurement once.