mcp-counter-server
# Counter MCP Server
A Model Context Protocol (MCP) server that provides stateful counter tools for AI assistants. This solves the problem of AI's inability to reliably count items during iteration by providing explicit, accurate counter tools.
## The Problem
AI language models use probabilistic pattern matching rather than actual counting. This makes them unreliable for tasks like:
- Tracking how many files have been processed
- Counting iterations in a loop
- Maintaining progress through multi-step tasks
- Accurately tallying errors, warnings, or other metrics
## The Solution
This MCP server provides explicit counter tools that maintain accurate state. AI assistants can:
1. **Embed counter tags** directly in their output as they work
2. **Process all tags** in one call with `counter_parse_and_apply`
3. **Track multiple metrics** simultaneously with perfect accuracy
4. **Review history** to see every operation performed
## Quick Start
### Installation
```bash
git clone https://github.com/Discordit142/mcp-counter-server.git
cd mcp-counter-server
npm install
npm run build
```
### Add to VS Code
Add this to your VS Code User Settings (`Ctrl+,` → search "MCP" → Edit in settings.json):
```json
{
"mcp.servers": {
"counter": {
"type": "stdio",
"command": "node",
"args": ["<path-to-repo>/dist/index.js"]
}
}
}
```
Replace `<path-to-repo>` with the actual path to your cloned repository.
## Usage
### Method 1: Tag-Based Counting (Recommended)
Embed counter tags directly in your text as you work, then process them all at once:
```
Processing files in workspace...
Analyzing src/index.ts [+1:files_analyzed]
- Found 15 async functions [+15:async_functions]
- Found 2 interface definitions [+2:interfaces]
- Detected 3 minor issues [+3:warnings]
Analyzing package.json [+1:files_analyzed]
- Configuration validated
Analyzing README.md [+1:files_analyzed]
- Documentation complete
Analysis finished!
```
Then call `counter_parse_and_apply` with the entire text above, and get:
```json
{
"counters": {
"files_analyzed": 3,
"async_functions": 15,
"interfaces": 2,
"warnings": 3
},
"errors": []
}
```
### Tag Syntax
**Shorthand (explicit numbers required):**
- `[+N:counter_id]` - Increment by N
- `[-N:counter_id]` - Decrement by N
- `[reset:counter_id]` - Reset to 0
- `[delete:counter_id]` - Delete counter
- `[set:N:counter_id]` - Set to specific value
**Full Syntax (alternative):**
- `[-counter:counter_id:+N-]` or `[-c:counter_id:+N-]` - Increment/decrement
- `[-counter:counter_id:reset-]` - Reset
- `[-counter:counter_id:delete-]` - Delete
- `[-counter:counter_id:set:N-]` - Set value
**Examples:**
```
[+1:files] → files: 1
[+15:lines_of_code] → lines_of_code: 15
[-3:errors] → errors: -3
[reset:temp] → temp: 0
[set:100:progress] → progress: 100
[delete:old_counter] → (counter removed)
```
### Method 2: Direct Tool Calls
For simple cases, call counter tools directly:
```javascript
counter_increment(counter_id: "files_processed")
counter_increment(counter_id: "errors_found", amount: 5)
counter_get(counter_id: "files_processed") // Returns current value
counter_reset(counter_id: "errors_found") // Reset to 0
counter_delete(counter_id: "temp_counter") // Remove completely
```
## Available Tools
### `counter_parse_and_apply`
Parse counter tags from text and execute all operations in order.
**Arguments:**
- `text` (required): Text containing counter tags
- `debug` (optional): Enable debug mode for detailed results (default: false)
**Streamlined Mode (default):**
```json
{
"counters": { "files": 5, "errors": 2 },
"errors": []
}
```
**Debug Mode:**
```json
{
"counters": { "files": 5 },
"errors": [],
"processed_tags": [
{ "tag": "[+1:files]", "result": "files incremented by 1" },
{ "tag": "[+4:files]", "result": "files incremented by 4" }
]
}
```
### `counter_increment`
Increment a counter by a specified amount (creates if doesn't exist).
**Arguments:**
- `counter_id` (required): Unique identifier
- `amount` (optional): Amount to increment (default: 1, can be negative)
### `counter_get`
Get current value and metadata for a counter.
**Arguments:**
- `counter_id` (required): Counter to retrieve
### `counter_reset`
Reset a counter to 0 (preserves history).
**Arguments:**
- `counter_id` (required): Counter to reset
### `counter_list`
List all active counters with their current values.
### `counter_history`
Get operation history for a counter.
**Arguments:**
- `counter_id` (required): Counter to retrieve history for
- `limit` (optional): Max number of recent entries
### `counter_delete`
Permanently delete a counter and its history.
**Arguments:**
- `counter_id` (required): Counter to delete
## Real-World Example
```
Starting database migration...
Connecting to database... [+1:steps_completed]
Backing up existing data... [+1:steps_completed]
Processing 1000 records:
Record batch 1-100: [+100:records_processed] [+2:errors_found]
Record batch 101-200: [+100:records_processed] [+1:errors_found]
Record batch 201-1000: [+800:records_processed]
Migration complete!
Setting total records: [set:1000:total_records]
Final status:
- Steps completed: (will show 2)
- Records processed: (will show 1000)
- Errors found: (will show 3)
```
Pass this text to `counter_parse_and_apply` and get accurate counts instantly.
## Features
✅ **Accurate counting** - No probabilistic approximation
✅ **Batch processing** - Process hundreds of tags in one call
✅ **History tracking** - Every operation logged with timestamp
✅ **Multiple counters** - Track different metrics simultaneously
✅ **Persistent within session** - Counters survive across tool calls
✅ **Flexible operations** - Increment, decrement, set, reset, delete
✅ **Error handling** - Continues processing even if individual tags fail
✅ **Race-condition safe** - Per-counter locking prevents conflicts
## Development
```bash
npm run build # Compile TypeScript
npm run watch # Watch mode for development
npm run dev # Run with Node inspector
npm start # Run the compiled server
```
## Architecture
- **CounterStore**: In-memory store with per-counter locking
- **Counter**: Data structure with id, value, history, timestamps
- **parseAndApplyTags**: Regex-based tag extraction and processing
- **MCP Server**: Exposes tools via Model Context Protocol
## Use Cases
- Multi-file analysis (track files, functions, classes found)
- Long-running operations (track progress, errors, warnings)
- Batch processing (accurately count processed items)
- Quality metrics (track code quality scores across multiple files)
- Agent workflows (multiple agents incrementing shared counters)
- **Preserving calculations past context compression:** Store important calculation results as named counters (e.g., `[set:15:error_rate_percentage]`) to survive conversation summarization. AI assistants can retrieve these values later even after context is compressed.
## License
MIT License - see [LICENSE](LICENSE) file for details
## Contributing
Issues and pull requests welcome at [github.com/Discordit142/mcp-counter-server](https://github.com/Discordit142/mcp-counter-server)
TDQS
Scored across 7 tools
Tools are mostly distinct: increment, reset, delete, get, list, and history each target a unique operation. However, counter_parse_and_apply can also perform increment, reset, delete, and set actions, creating some overlap with the direct tools, though it is clearly scoped as a text-parsing batch operation.
All tools follow a consistent counter_<verb> pattern, using snake_case for multi-word verbs like parse_and_apply. The naming is uniform and predictable, making it easy to infer the tool's function from its name.
With 7 tools, the server is well-scoped for a counter management domain. Each tool serves a distinct operational need without excessive overlap or redundancy, striking a balance between completeness and simplicity.
The core counter lifecycle is well covered: create (via increment), read (get/list), update (increment/reset), and delete. However, direct decrement and set-to-arbitrary-value operations are missing, requiring agents to use counter_parse_and_apply with text, which is an awkward workaround for simple cases.