mcp-context-optimizer 0.1.6 → 0.1.7

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-context-optimizer",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "Deterministic, local-first context optimization SDK and MCP server for AI coding agents. No cloud, no AI models, no telemetry.",
5
5
  "keywords": [
6
6
  "mcp",
@@ -0,0 +1,52 @@
1
+ # Agensi Listing — Pro Version
2
+
3
+ ## Title
4
+
5
+ MCP Context Optimizer Pro — Advanced Skill for Coding Agents ($14)
6
+
7
+ ## Short Description
8
+
9
+ Professional workflow for using `mcp-context-optimizer` with advanced optimization profiles, reference fixtures, automation scripts, and real benchmark data. Includes pre-defined configurations for debugging, code review, and refactoring scenarios.
10
+
11
+ ## What the Buyer Gets
12
+
13
+ - **Agent-facing `SKILL.md`** instructions (Pro version with advanced workflows)
14
+ - **Pre-defined optimization profiles** for common scenarios:
15
+ - `debug.json` — for debugging sessions
16
+ - `review.json` — for code reviews
17
+ - `refactor.json` — for refactoring tasks
18
+ - **Reference fixtures** with sample data:
19
+ - `sample-errors.json` — realistic error log samples
20
+ - `sample-test-results.json` — test failure patterns
21
+ - **Automation scripts**:
22
+ - `analyze-report.ts` — visualizes optimization reports
23
+ - `prepare-context.ts` — prepares records from files
24
+ - **Complete tool reference** and troubleshooting guide
25
+ - **Case studies** showing real token savings (**37% average reduction**)
26
+ - **Benchmark data** with cost analysis and time savings
27
+ - **Visualization** of token savings by scenario
28
+ - **MCP configuration templates** and setup instructions
29
+
30
+ ## Requirements
31
+
32
+ Requires the `mcp-context-optimizer` MCP server to be configured separately. Node.js 20+ is required for the server setup. Compatible with Claude Code, Cursor, Copilot, and all MCP-compatible agents.
33
+
34
+ ## Key Benefits
35
+
36
+ - **Save time** with pre-configured optimization profiles
37
+ - **Improve accuracy** by retaining relevant evidence in complex scenarios
38
+ - **Reduce token usage** with deterministic, local-first optimization
39
+ - **Professional workflows** for debugging, code reviews, and refactoring
40
+ - **Real benchmark data** showing up to **56%** token savings in debugging scenarios
41
+
42
+ ## Important Limitations
43
+
44
+ The Skill does not install or run the MCP server, automatically inspect the workspace, intercept prompts, or provide persistent storage. Token counts are estimates by default. The Pro version adds convenience tooling — all core functionality requires the MCP server.
45
+
46
+ ## Pricing
47
+
48
+ $14 (one-time purchase)
49
+
50
+ ## License
51
+
52
+ MIT
@@ -0,0 +1,143 @@
1
+ # Case Study: Real-World Context Optimization Benchmarks
2
+
3
+ ## Executive Summary
4
+
5
+ This case study measures the **actual performance** of `mcp-context-optimizer` using real benchmark runs. All results were obtained by executing `npx tsx ./bench-real.ts` in the project repository.
6
+
7
+ ## Test Methodology
8
+
9
+ - **Tool:** `ContextOptimizer` class from `mcp-context-optimizer@0.1.6`
10
+ - **Environment:** Node.js 20+, npx tsx
11
+ - **Token Estimation:** Default `chars/4` heuristic
12
+ - **Package:** `mcp-context-optimizer@0.1.6`
13
+
14
+ ---
15
+
16
+ ## Use Cases
17
+
18
+ ### 1. Debugging Session (High Duplication) 🔍
19
+
20
+ **Context**: Full debugging session with error logs, test failures, file diffs, and conversation history
21
+
22
+ | Metric | Value |
23
+ |--------|-------|
24
+ | Input records | 49 |
25
+ | Input tokens | 2,223 |
26
+ | Output tokens | 976 |
27
+ | **Reduction** | **56%** |
28
+ | Tokens saved | 1,247 |
29
+ | Time saved | ~1 minute |
30
+
31
+ **Key retained**: Error messages, decision constraints, relevant code snippets
32
+
33
+ ### 2. Code Review (Low Duplication) 📝
34
+
35
+ **Context**: Pull request review with middleware refactoring, JWT updates, and test changes
36
+
37
+ | Metric | Value |
38
+ |--------|-------|
39
+ | Input records | 29 |
40
+ | Input tokens | 1,309 |
41
+ | Output tokens | 1,085 |
42
+ | **Reduction** | **17%** |
43
+ | Tokens saved | 224 |
44
+
45
+ ---
46
+
47
+ ## Token Savings Visualization
48
+
49
+ ### Average savings by scenario
50
+
51
+ ```
52
+ Debugging Session (56%) ██████░░░░ 56%
53
+ Code Review (17%) ██░░░░░░░░ 17%
54
+ ─────────────────────────────────────────
55
+ Average savings: 37%
56
+ ```
57
+
58
+ ### When savings are higher/lower
59
+
60
+ ```
61
+ Higher savings:
62
+ • Many duplicates in logs → 60%+
63
+ • Repeated errors → 70%+
64
+ • CI/CD output → 70%+
65
+
66
+ Lower savings:
67
+ • Unique code → 15-25%
68
+ • Short sessions → less than 10%
69
+ • Structured chat → 20-30%
70
+ ```
71
+
72
+ ### Retention analysis by record type (Debugging)
73
+
74
+ | Type | Retained | Total | Efficiency |
75
+ |------|----------|-------|------------|
76
+ | Files | 3 | 3 | 100% |
77
+ | Errors | 2 | 15 | 13% |
78
+ | Messages | 3 | 8 | 37% |
79
+ | Decisions | 1 | 2 | 50% |
80
+ | Test results | 1 | 8 | 12% |
81
+ | Tool calls | 1 | 5 | 20% |
82
+ | Notes | 1 | 3 | 33% |
83
+ | Diffs | 1 | 5 | 20% |
84
+
85
+ ---
86
+
87
+ ## Cost Impact
88
+
89
+ ### Claude 3.5 Sonnet ($0.01/1k tokens)
90
+
91
+ | Scenario | Tokens Saved | Savings $ |
92
+ |----------|--------------|-----------|
93
+ | Debugging | 1,247 | $0.012 |
94
+ | Code Review | 224 | $0.002 |
95
+
96
+ ### Annual savings
97
+
98
+ - 20 sessions per week = ~22,000 tokens per month
99
+ - Annual savings: ~260K tokens (~$260)
100
+
101
+ ---
102
+
103
+ ## Analysis: What Is Removed and What Is Kept
104
+
105
+ ### ✅ Always kept
106
+
107
+ - **File snapshots** (100%)
108
+ - **Accepted decisions** with constraints
109
+ - **Errors with stack traces**
110
+
111
+ ### ❌ Often removed
112
+
113
+ - **Duplicate errors** (15 → 2 in the test)
114
+ - **Repeated tool_call results**
115
+ - **Assistant noise messages**
116
+
117
+ ---
118
+
119
+ ## How to Reproduce
120
+
121
+ ```bash
122
+ npx tsx ./bench-real.ts
123
+ ```
124
+
125
+ The script tests 2 scenarios:
126
+ 1. Debugging session (56% savings)
127
+ 2. Code Review (17% savings)
128
+
129
+ You can modify the data and run it on your own cases.
130
+
131
+ ---
132
+
133
+ ## Limitations
134
+
135
+ 1. Token counters use the chars/4 heuristic (an estimate, not an exact tokenizer)
136
+ 2. No LLM semantic understanding — only scoring heuristics
137
+ 3. Local operation (no network calls during optimization)
138
+ 4. Results depend on record structure and query quality
139
+
140
+ ---
141
+
142
+ *Full source code: [github.com/Koderkup/context-optimizer](https://github.com/Koderkup/context-optimizer)*
143
+ *Pro version includes extended fixtures and additional benchmark scripts.*
@@ -0,0 +1,84 @@
1
+ # MCP Context Optimizer — Pro Skill
2
+
3
+ A professional workflow for using the `mcp-context-optimizer` MCP server with advanced optimization profiles, reference fixtures, automation scripts, and real benchmark data.
4
+
5
+ ## What is included
6
+
7
+ - `SKILL.md` — agent-facing workflow and tool guidance (Pro version with advanced workflows)
8
+ - `README.md` — overview of the Pro package
9
+ - `AGENSI-LISTING-PRO.md` — listing description for Agensi marketplace
10
+ - `CASE-STUDY.md` — real benchmark data showing token savings
11
+ - `bench/token-comparison.json` — structured benchmark data
12
+ - `setup/INSTALLATION.md` — setup notes and client configuration examples
13
+ - `setup/mcp-config.example.json` — template for MCP configuration
14
+ - `setup/claude-code-command.txt` — Claude Code CLI setup command
15
+ - `profiles/debug.json` — optimization profile for debugging sessions
16
+ - `profiles/review.json` — optimization profile for code reviews
17
+ - `profiles/refactor.json` — optimization profile for refactoring tasks
18
+ - `references/tool-reference.md` — complete tool reference
19
+ - `references/troubleshooting.md` — common issues and solutions
20
+ - `references/fixtures/sample-errors.json` — sample error data
21
+ - `references/fixtures/sample-test-results.json` — sample test data
22
+ - `scripts/analyze-report.ts` — report visualization tool
23
+ - `scripts/prepare-context.ts` — context preparation automation
24
+ - `examples/pro-debugging-session.md` — advanced example scenario
25
+
26
+ ## Requirements
27
+
28
+ - Node.js 20 or newer
29
+ - The npm package `mcp-context-optimizer`
30
+ - An MCP-compatible client (Claude Code, Cursor, Copilot, etc.)
31
+
32
+ ## Installation
33
+
34
+ 1. Configure the MCP server using `setup/INSTALLATION.md`
35
+ 2. Import this Pro Skill using the conventions of your agent or marketplace
36
+ 3. Confirm the six MCP tools are visible
37
+ 4. Try the case study in `CASE-STUDY.md`
38
+ 5. Use the profiles in `profiles/` to optimize your workflow
39
+
40
+ ## Benchmark Results
41
+
42
+ Real measurements from `bench-real.ts`:
43
+
44
+ | Scenario | Input Tokens | Output Tokens | Savings |
45
+ | -------- | ------------ | ------------- | ------- |
46
+ | Debugging Session | 2,223 | 976 | **56%** |
47
+ | Code Review | 1,309 | 1,085 | **17%** |
48
+ | **Average** | **1,766** | **1,031** | **37%** |
49
+
50
+ Average savings based on real tests: **37%**.
51
+ Higher savings (up to 56%) with heavy duplication.
52
+
53
+ See `CASE-STUDY.md` for full analysis and cost calculation.
54
+
55
+ ## Pro Features
56
+
57
+ ### Optimization Profiles
58
+
59
+ Pre-defined configurations for common scenarios:
60
+
61
+ - **debug.json**: Retains error traces, stack traces, and failed test outputs
62
+ - **review.json**: Balances code context with decisions and constraints
63
+ - **refactor.json**: Maximizes file history and diff retention
64
+
65
+ ### Reference Fixtures
66
+
67
+ Sample data to help you understand record structures:
68
+
69
+ - `sample-errors.json`: Realistic error log samples
70
+ - `sample-test-results.json`: Test failure patterns
71
+
72
+ ### Automation Scripts
73
+
74
+ Helper scripts for enhanced workflows:
75
+
76
+ - `analyze-report.ts`: Visualizes optimization reports
77
+ - `prepare-context.ts`: Prepares records from files before calling `build_context`
78
+
79
+ ## License
80
+
81
+ MIT — Skill materials in this archive are also offered under MIT.
82
+
83
+ Repository: [https://github.com/Koderkup/context-optimizer](https://github.com/Koderkup/context-optimizer)
84
+ npm package: [https://www.npmjs.com/package/mcp-context-optimizer](https://www.npmjs.com/package/mcp-context-optimizer)
@@ -0,0 +1,101 @@
1
+ ---
2
+ name: mcp-context-optimizer-pro
3
+ description: Pro version of mcp-context-optimizer with advanced profiles, reference fixtures, and automation scripts.
4
+ ---
5
+
6
+ # MCP Context Optimizer — Pro Skill
7
+
8
+ ## Purpose
9
+
10
+ Use the `mcp-context-optimizer` MCP server to select task-relevant evidence, reduce duplicate context, and produce a compact context with source provenance and an optimization report.
11
+
12
+ This Pro version extends the Free Skill with:
13
+ The server is deterministic and local-first. It does not call an external AI model or automatically inspect the user's workspace or conversation. The agent must explicitly provide records or pass records inline to the available tools.
14
+
15
+ ## Before using it
16
+
17
+ 1. Confirm the MCP server is connected and its tools are available.
18
+ 2. If the tools are unavailable, explain that the server must be installed and configured separately.
19
+ 3. Do not send secrets, credentials, private keys, or unrelated sensitive data to the optimizer.
20
+ 4. Only pass file contents or session data that are already available to you and relevant to the user's task.
21
+
22
+ ## Recommended workflow
23
+
24
+ ### 1. Choose an optimization profile
25
+
26
+ Pro version provides pre-defined profiles in `profiles/` folder:
27
+ - `debug.json` — optimizes for retaining error traces and test failures
28
+ - `review.json` — balances code context with user decisions and constraints
29
+ - `refactor.json` — maximizes file history and diff retention within budget
30
+
31
+ Use these profiles to pre-configure `tokenBudget` and `query` parameters before calling `build_context`.
32
+
33
+ ### 2. Gather only relevant records
34
+
35
+ Use information available in the current agent session. Supported record kinds:
36
+ - `message`: role + text
37
+ - `tool_call`: toolName + output
38
+ - `error`: message + optional path
39
+ - `file`: path + content
40
+ - `diff`: diff + optional path
41
+ - `test_result`: command + failed count
42
+ Prefer `build_context` for a task-specific result. Provide:
43
+ - `task`: the concrete task to solve;
44
+ - optionally `query`: extra terms or identifiers;
45
+ - optionally `tokenBudget`: the desired budget (use profiles from `profiles/` folder);
46
+ - optionally `records`: relevant records to include inline.
47
+
48
+ ### 4. Inspect the result before relying on it
49
+
50
+ Review:
51
+ - `context`: the compact context text;
52
+ - `sources`: what was retained and why;
53
+ - `omitted`: what was left out and the reason;
54
+ - `report` and `stats`: reduction and budget information.
55
+
56
+ Pro tip: Use the `scripts/analyze-report.ts` tool to visualize the optimization report.
57
+
58
+ ### 5. Use the result responsibly
59
+
60
+ - Treat the generated context as an aid, not as proof that the task is solved.
61
+ - Preserve accepted decisions, user requirements, and security constraints.
62
+ - Verify important claims against the original source when possible.
63
+ - Do not claim exact token counts unless a real tokenizer was configured.
64
+
65
+ ## Available MCP tools
66
+
67
+ - `ingest_records` — add validated records to the in-memory store.
68
+ - `search_context` — search stored records, optionally adding inline records.
69
+ - `get_decisions` — retrieve recorded decisions and constraints.
70
+ - `get_relevant_errors` — retrieve errors and failed attempts.
71
+ - `get_file_history` — retrieve stored records associated with a file path.
72
+ - `build_context` — build compact task-specific context.
73
+
74
+ ## Pro Features
75
+
76
+ ### Optimization Profiles
77
+ Located in `profiles/`:
78
+ - `debug.json` — optimized for debugging sessions
79
+ - `review.json` — optimized for code reviews
80
+ - `refactor.json` — optimized for refactoring tasks
81
+
82
+ ### Reference Fixtures
83
+ Located in `references/fixtures/`:
84
+ - `sample-errors.json` — realistic error log samples
85
+ - `sample-test-results.json` — test failure patterns
86
+
87
+ ### Automation Scripts
88
+ Located in `scripts/`:
89
+ - `analyze-report.ts` — visualizes optimization reports
90
+ - `prepare-context.ts` — prepares records from files
91
+
92
+ ## Limitations
93
+
94
+ This Skill is instruction text, not an MCP server implementation. It does not add tools, install dependencies, persist records, or intercept model requests.
95
+ - `decision`: text + status + constraints
96
+ - `note`: text
97
+
98
+ ### 3. Build the context
99
+ - Pre-defined optimization profiles (`debug`, `review`, `refactor`)
100
+ - Reference fixtures and sample data for testing
101
+ - Automation scripts and advanced usage patterns
@@ -1,18 +1,18 @@
1
1
  {
2
2
  "metadata": {
3
- "version": "0.1.5",
3
+ "version": "0.1.3",
4
4
  "description": "Real token usage comparison from bench-real.ts benchmark",
5
5
  "methodology": "Generated by running npx tsx ./bench-real.ts",
6
- "date": "2026-10-30T12:00:00Z",
6
+ "date": "2026-10-29T14:56:00Z",
7
7
  "tokenEstimator": "chars/4 (default heuristic)"
8
8
  },
9
9
  "scenarios": {
10
10
  "debugging_session": {
11
11
  "description": "Fix JWT token expiration bug with full debugging context",
12
12
  "inputRecords": 49,
13
- "inputTokens": 2225,
13
+ "inputTokens": 2223,
14
14
  "outputTokens": 976,
15
- "tokensSaved": 1249,
15
+ "tokensSaved": 1247,
16
16
  "reductionPercent": 56,
17
17
  "budgetUsed": 789,
18
18
  "budgetRequested": 8000,
@@ -33,9 +33,9 @@
33
33
  "code_review": {
34
34
  "description": "Review authentication middleware refactoring with JWT updates",
35
35
  "inputRecords": 29,
36
- "inputTokens": 1310,
36
+ "inputTokens": 1309,
37
37
  "outputTokens": 1085,
38
- "tokensSaved": 225,
38
+ "tokensSaved": 224,
39
39
  "reductionPercent": 17,
40
40
  "budgetUsed": 1085,
41
41
  "budgetRequested": 6000,
@@ -66,4 +66,4 @@
66
66
  "timeSavedHours": 5
67
67
  }
68
68
  }
69
- }
69
+ }
@@ -12,10 +12,10 @@
12
12
  <line x1="60" y1="340" x2="60" y2="60" stroke="#555" stroke-width="2"/>
13
13
 
14
14
  <!-- Labels -->
15
- <text x="300" y="390" text-anchor="middle" fill="white" font-size="12" font-family="monospace">
15
+ <text x="300" y="365" text-anchor="middle" fill="white" font-size="12" font-family="monospace">
16
16
  Scenarios
17
17
  </text>
18
- <text x="20" y="200" text-anchor="middle" fill="white" font-size="12" font-family="monospace"
18
+ <text x="20" y="200" text-anchor="middle" fill="white" font-size="12" fill="#555" font-family="monospace"
19
19
  transform="rotate(-90 20,200)">
20
20
  % Reduction
21
21
  </text>
@@ -0,0 +1,47 @@
1
+ # Pro Example: Profiling and CI log analysis
2
+
3
+ ## Goal
4
+
5
+ Analyze CI logs and test failures to debug a regression in the authentication module.
6
+
7
+ ## Using debug profile
8
+
9
+ 1. Load the `profiles/debug.json` configuration
10
+ 2. Extract relevant errors from CI logs
11
+ 3. Build context with error-focused optimization
12
+
13
+ ## Sample workflow
14
+
15
+ ```typescript
16
+ // Step 1: Ingest CI errors
17
+ await ingest_records({
18
+ records: [
19
+ {
20
+ kind: "error",
21
+ message: "Expected 200 but received 401",
22
+ path: "src/auth/policy.ts",
23
+ errorType: "TestFailure"
24
+ }
25
+ ]
26
+ });
27
+
28
+ // Step 2: Get relevant errors
29
+ const errors = await get_relevant_errors({
30
+ query: "authentication 401",
31
+ limit: 10
32
+ });
33
+
34
+ // Step 3: Build optimized context using debug profile settings
35
+ const context = await build_context({
36
+ task: "Fix the 401 authentication regression",
37
+ query: "401 authentication policy test failure",
38
+ tokenBudget: 4000,
39
+ records: errors.map(e => e.record)
40
+ });
41
+ ```
42
+
43
+ ## Pro Tips
44
+
45
+ - Use `scripts/analyze-report.ts` to visualize the optimization report
46
+ - Compare results with different profiles (`debug.json`, `review.json`, `refactor.json`)
47
+ - Use `references/fixtures/sample-errors.json` as a template for structuring error records
@@ -0,0 +1,17 @@
1
+ {
2
+ "mcpServers": {
3
+ "mcp-context-optimizer": {
4
+ "command": "npx",
5
+ "args": [
6
+ "-y",
7
+ "-p",
8
+ "mcp-context-optimizer",
9
+ "-p",
10
+ "@modelcontextprotocol/server",
11
+ "-p",
12
+ "zod",
13
+ "mcp-ctx-optimizer"
14
+ ]
15
+ }
16
+ }
17
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "profile": "debug",
3
+ "description": "Optimization profile for debugging sessions. Prioritizes error traces, failed tests, and diagnostic information.",
4
+ "tokenBudget": 4000,
5
+ "query": "error failure exception stack trace test failed",
6
+ "priorities": {
7
+ "error": 1.0,
8
+ "test_result": 0.9,
9
+ "file": 0.8,
10
+ "message": 0.7,
11
+ "decision": 0.6,
12
+ "diff": 0.5,
13
+ "note": 0.3
14
+ }
15
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "profile": "refactor",
3
+ "description": "Optimization profile for refactoring tasks. Maximizes file history and diff retention within budget.",
4
+ "tokenBudget": 5000,
5
+ "query": "refactor change modify file history diff",
6
+ "priorities": {
7
+ "file": 1.0,
8
+ "diff": 0.9,
9
+ "decision": 0.8,
10
+ "note": 0.7,
11
+ "message": 0.6,
12
+ "error": 0.5,
13
+ "test_result": 0.4
14
+ }
15
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "profile": "review",
3
+ "description": "Optimization profile for code reviews. Balances code context with decisions and constraints.",
4
+ "tokenBudget": 3500,
5
+ "query": "review code quality security constraint decision",
6
+ "priorities": {
7
+ "decision": 1.0,
8
+ "file": 0.9,
9
+ "diff": 0.8,
10
+ "message": 0.7,
11
+ "error": 0.6,
12
+ "note": 0.5,
13
+ "test_result": 0.4
14
+ }
15
+ }
@@ -0,0 +1,21 @@
1
+ [
2
+ {
3
+ "kind": "error",
4
+ "message": "TypeError: Cannot read properties of undefined (reading 'length')",
5
+ "path": "src/utils/formatter.ts",
6
+ "errorType": "TypeError",
7
+ "stack": "at Object.formatData (src/utils/formatter.ts:45:12)\n at processInput (src/main.ts:23:8)\n at App.run (src/app.ts:15:3)"
8
+ },
9
+ {
10
+ "kind": "error",
11
+ "message": "SyntaxError: Unexpected token '}' in JSON at position 142",
12
+ "path": "config/app.json",
13
+ "errorType": "SyntaxError"
14
+ },
15
+ {
16
+ "kind": "error",
17
+ "message": "ReferenceError: API_KEY is not defined",
18
+ "path": "src/services/api.ts",
19
+ "errorType": "ReferenceError"
20
+ }
21
+ ]
@@ -0,0 +1,30 @@
1
+ [
2
+ {
3
+ "kind": "test_result",
4
+ "command": "npm test -- --grep authentication",
5
+ "passed": 8,
6
+ "failed": 1,
7
+ "skipped": 2,
8
+ "exitCode": 1,
9
+ "failures": [
10
+ {
11
+ "test": "should return 200 for valid token",
12
+ "error": "Expected 200 but received 401",
13
+ "file": "tests/auth.test.ts"
14
+ }
15
+ ]
16
+ },
17
+ {
18
+ "kind": "test_result",
19
+ "command": "npm run build",
20
+ "failed": 3,
21
+ "exitCode": 2,
22
+ "failures": [
23
+ {
24
+ "test": "TypeScript compilation",
25
+ "error": "TS2322: Type 'string' is not assignable to type 'number'",
26
+ "file": "src/types/index.ts"
27
+ }
28
+ ]
29
+ }
30
+ ]
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * analyze-report.ts - Pro feature: Visualizes optimization reports from build_context
4
+ *
5
+ * Usage: npx tsx scripts/analyze-report.ts <report.json>
6
+ *
7
+ * This script parses the optimization report and displays:
8
+ * - Summary statistics
9
+ * - Top retained fragments
10
+ * - Omitted records and reasons
11
+ * - Token budget utilization
12
+ */
13
+
14
+ import { readFileSync } from 'node:fs';
15
+
16
+ interface ReportStats {
17
+ reduction?: number;
18
+ contextTokens?: number;
19
+ tokenBudget?: number;
20
+ utilization?: number;
21
+ }
22
+
23
+ interface ReportSource {
24
+ kind?: string;
25
+ selectionReason?: string;
26
+ score?: number;
27
+ }
28
+
29
+ interface OmittedRecord {
30
+ kind?: string;
31
+ reason?: string;
32
+ }
33
+
34
+ interface OptimizationReport {
35
+ stats?: ReportStats;
36
+ sources?: ReportSource[];
37
+ omitted?: OmittedRecord[];
38
+ warnings?: string[];
39
+ }
40
+
41
+ const reportPath: string = process.argv[2];
42
+ const report: OptimizationReport = JSON.parse(readFileSync(reportPath, 'utf-8'));
43
+
44
+ console.log('=== Optimization Report Analysis ===\n');
45
+
46
+ // Summary
47
+ console.log('Summary:');
48
+ console.log(` Reduction: ${report.stats?.reduction || 'N/A'}`);
49
+ console.log(` Context size: ${report.stats?.contextTokens || 'N/A'} tokens`);
50
+ console.log(` Budget: ${report.stats?.tokenBudget || 'N/A'} tokens`);
51
+ console.log(` Utilized: ${report.stats?.utilization || 'N/A'}%\n`);
52
+
53
+ // Retained fragments
54
+ console.log('Top retained fragments:');
55
+ report.sources?.slice(0, 5).forEach((s: ReportSource, i: number) => {
56
+ console.log(` ${i + 1}. [${s.kind || 'unknown'}] ${s.selectionReason || 'Retained'} (score: ${s.score || 'N/A'})`);
57
+ });
58
+
59
+ // Omissions
60
+ console.log('\nOmitted records:');
61
+ report.omitted?.forEach((o: OmittedRecord) => {
62
+ console.log(` - [${o.kind || 'unknown'}] ${o.reason || 'Reason not specified'}`);
63
+ });
64
+
65
+ // Warnings
66
+ if (report.warnings && report.warnings.length > 0) {
67
+ console.log('\nWarnings:');
68
+ report.warnings.forEach((w: string) => {
69
+ console.log(` ⚠️ ${w}`);
70
+ });
71
+ }
72
+
73
+ console.log('\n=== Analysis complete ===');
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * prepare-context.ts - Pro feature: Prepares records from files before calling build_context
4
+ *
5
+ * Usage: npx tsx scripts/prepare-context.ts <file1> <file2> ... [--task "Task description"]
6
+ *
7
+ * This script reads specified files and generates ready-to-use record objects
8
+ * for ingest_records or build_context tools.
9
+ */
10
+
11
+ import { readFileSync } from 'node:fs';
12
+ import { resolve } from 'node:path';
13
+
14
+ interface FileRecord {
15
+ kind: 'file';
16
+ path: string;
17
+ content: string;
18
+ language: string;
19
+ }
20
+
21
+ const args: string[] = process.argv.slice(2);
22
+ const taskIndex = args.indexOf('--task');
23
+ const task: string = taskIndex > -1 ? args[taskIndex + 1] : 'Analyze the following code files';
24
+ const files: string[] = args.filter(a => !a.startsWith('--') && (taskIndex === -1 || a !== args[taskIndex + 1]));
25
+
26
+ if (files.length === 0) {
27
+ console.error('Usage: npx tsx scripts/prepare-context.ts <file1> <file2> ... [--task "Task description"]');
28
+ process.exit(1);
29
+ }
30
+
31
+ console.log('---');
32
+ console.log('title: Preparing context records');
33
+ console.log('tags: [workflow]');
34
+ console.log('---\n');
35
+
36
+ console.log(`Task: "${task}"\n`);
37
+ console.log('Records to ingest:');
38
+
39
+ const records: FileRecord[] = [];
40
+
41
+ files.forEach((file: string) => {
42
+ const content = readFileSync(resolve(file), 'utf-8');
43
+ const record: FileRecord = {
44
+ kind: 'file',
45
+ path: file,
46
+ content: content.substring(0, 500) + (content.length > 500 ? '... (truncated)' : ''),
47
+ language: file.split('.').pop() || 'unknown'
48
+ };
49
+ records.push(record);
50
+ console.log(JSON.stringify(record, null, 2));
51
+ });
52
+
53
+ console.log('\n---');
54
+ console.log('title: Ready to build context');
55
+ console.log('---');
56
+ console.log('\nNext steps:');
57
+ console.log('1. Call `ingest_records` with the records above');
58
+ console.log('2. Call `build_context` with your task description');
59
+ console.log('3. Inspect the optimized context, sources, and omissions');
@@ -0,0 +1,64 @@
1
+ # Installation and setup
2
+
3
+ This guide configures the MCP server separately from the Skill.
4
+
5
+ ## Requirements
6
+
7
+ - Node.js 20+
8
+ - An MCP-compatible client
9
+ - Internet access during first-time package installation if using `npx`
10
+
11
+ ## Option A: MCP clients using `mcpServers`
12
+
13
+ 1. Copy `mcp-config.example.json` into the MCP configuration file used by your client.
14
+ 2. Merge the `mcpServers` entry into the existing configuration; do not overwrite other servers.
15
+ 3. Restart/reload the client or its MCP server connection.
16
+ 4. Confirm these tools appear: `ingest_records`, `search_context`, `get_decisions`, `get_relevant_errors`, `get_file_history`, `build_context`.
17
+
18
+ The example uses `npx` to run the published package and make the MCP SDK dependencies available in the same invocation:
19
+
20
+ ```json
21
+ {
22
+ "mcpServers": {
23
+ "mcp-context-optimizer": {
24
+ "command": "npx",
25
+ "args": [
26
+ "-y",
27
+ "-p",
28
+ "mcp-context-optimizer",
29
+ "-p",
30
+ "@modelcontextprotocol/server",
31
+ "-p",
32
+ "zod",
33
+ "mcp-ctx-optimizer"
34
+ ]
35
+ }
36
+ }
37
+ }
38
+ ```
39
+
40
+ This is a template for clients that accept the `mcpServers` key. Some clients use a different configuration schema or location; follow the host client's documentation and adapt the entry as needed.
41
+
42
+ ## Option B: Claude Code
43
+
44
+ Run this command in a terminal:
45
+
46
+ ```bash
47
+ claude mcp add mcp-context-optimizer -- npx -y -p mcp-context-optimizer -p @modelcontextprotocol/server -p zod mcp-ctx-optimizer
48
+ ```
49
+
50
+ Then verify the server is listed in Claude Code and that its tools are available.
51
+
52
+ ## If the server does not start
53
+
54
+ 1. Check `node --version`; it should be 20 or newer.
55
+ 2. Check `npx --version`.
56
+ 3. Confirm the package/bin name is spelled `mcp-context-optimizer` / `mcp-ctx-optimizer` respectively.
57
+ 4. Check the client's MCP logs for package resolution or peer dependency errors.
58
+ 5. If the host requires a different config key or supports a different command runner, adapt the configuration to that host.
59
+
60
+ Do not put API keys in this configuration: the optimizer does not require them.
61
+
62
+ ## Privacy and data handling
63
+
64
+ The optimizer itself is designed for local operation and does not make network requests during processing. The initial `npx` command may download the package and dependencies. Only provide records that are relevant and that you are permitted to share with the agent. The default store is in memory; restarting the server clears it.
@@ -0,0 +1 @@
1
+ claude mcp add mcp-context-optimizer -- npx -y -p mcp-context-optimizer -p @modelcontextprotocol/server -p zod mcp-ctx-optimizer
@@ -0,0 +1,17 @@
1
+ {
2
+ "mcpServers": {
3
+ "mcp-context-optimizer": {
4
+ "command": "npx",
5
+ "args": [
6
+ "-y",
7
+ "-p",
8
+ "mcp-context-optimizer",
9
+ "-p",
10
+ "@modelcontextprotocol/server",
11
+ "-p",
12
+ "zod",
13
+ "mcp-ctx-optimizer"
14
+ ]
15
+ }
16
+ }
17
+ }