Skip to content

Update server version handling and add tests - #63

Merged
wpak-ai merged 4 commits into
cppalliance:mainfrom
leostar0412:fix/mcp-server-version-sync
May 5, 2026
Merged

Update server version handling and add tests#63
wpak-ai merged 4 commits into
cppalliance:mainfrom
leostar0412:fix/mcp-server-version-sync

Conversation

@leostar0412

@leostar0412 leostar0412 commented May 4, 2026

Copy link
Copy Markdown
Collaborator

Pull Request

Description

The MCP server advertised SERVER_VERSION as a separate string in source, so it could fall behind the real npm package version. Clients read the version from the MCP initialize handshake, which made diagnostics and tooling misleading compared to package.json / npm ls.

This PR derives SERVER_VERSION at load time from the root package.json next to the built entrypoint (same layout as a published install under node_modules/.../package.json). parsePackageJsonVersion centralizes validation (non-empty string version field). constants.ts re-exports SERVER_VERSION from server-version.js so server.ts behavior is unchanged.

Fixes #62

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Code quality improvement
  • Performance improvement

Changes Made

  • Add src/server-version.ts: read root package.json, export SERVER_VERSION and parsePackageJsonVersion.
  • Re-export SERVER_VERSION from src/constants.ts instead of a hard-coded literal.
  • Add src/server-version.test.ts: parsing fixtures, alignment helper tests, and a live check that SERVER_VERSION matches the repo’s root package.json.

Testing

Describe the tests you ran to verify your changes:

  • All existing tests pass
  • Added new tests for changes
  • Manual testing performed

Test Configuration

  • Node.js version: (fill after node -v)
  • OS: (fill in)

Suggested verification: after npm run build, start the server and confirm the reported MCP server version matches the installed package’s version in package.json.

Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • My changes generate no new warnings or errors
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Summary by CodeRabbit

  • New Features

    • Server version is now determined at runtime from the project manifest rather than a hardcoded value.
  • Tests

    • Added coverage to verify version parsing, resolution, and alignment with the project manifest.
  • Chores

    • Updated ignore patterns to exclude temporary OS/editor files (e.g., dot-prefixed artifacts).

@coderabbitai

coderabbitai Bot commented May 4, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9466c07e-d047-4f7d-a27a-0cb5227648d3

📥 Commits

Reviewing files that changed from the base of the PR and between 868d386 and 8031f9d.

📒 Files selected for processing (2)
  • src/server-version.test.ts
  • src/server-version.ts
✅ Files skipped from review due to trivial changes (1)
  • src/server-version.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/server-version.test.ts

📝 Walkthrough

Walkthrough

The PR replaces a hardcoded SERVER_VERSION with runtime resolution from package.json (with DEFAULT_SERVER_VERSION fallback and logging), re-exports SERVER_VERSION from the resolver, adds tests for parsing/resolution behavior, and adds a .gitignore rule to ignore ._* files.

Changes

Server Version Alignment

Layer / File(s) Summary
Data Shape / Defaults
src/server-version.ts
Adds DEFAULT_SERVER_VERSION = '0.0.1' and computes default package.json path relative to the compiled output.
Parsing Logic
src/server-version.ts
Adds parsePackageJsonVersion(raw: string, pathForErrors?) to JSON-parse input, validate/trim version, log errors, and return fallback on failure.
Resolution / IO
src/server-version.ts
Adds resolveServerVersion(overridePath?) to choose manifest path, check existence, read UTF‑8 file, delegate to parser, and log+fallback on missing/read errors.
Initialization / Export
src/server-version.ts, src/constants.ts
Exports SERVER_VERSION as the immediate result of resolveServerVersion() and re-exports it from src/constants.ts (replaces the previous inline '0.1.0').
Tests
src/server-version.test.ts
Adds Vitest suite for parsePackageJsonVersion, resolveServerVersion, alignment helper, and assertion that exported SERVER_VERSION equals the live root package.json version.

Repository Ignore Update

Layer / File(s) Summary
Ignore Rules
.gitignore
Adds ._* pattern to ignore OS/editor-generated files alongside existing ignore entries.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hopped through package.json to find the truth,
No more stale strings hiding—now the server's smooth.
If files go missing, I nibble a fallback tune,
Logs tell the tale beneath the coding moon. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main changes: updating server version handling and adding tests, which aligns with the core objective of syncing SERVER_VERSION from package.json and adding test coverage.
Linked Issues check ✅ Passed The PR fully addresses issue #62 by implementing dynamic SERVER_VERSION read from package.json at load time, adding validation with parsePackageJsonVersion, and including comprehensive tests to verify the alignment.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the linked issue #62: server version syncing from package.json. The .gitignore addition for ._* files is a minor, unrelated hygiene change but does not interfere with the primary objectives.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
src/server-version.ts (1)

16-19: ⚡ Quick win

Harden version validation to reject whitespace-only values.

Line 16 accepts " " as valid because it only checks .length. Trimming before validation avoids emitting effectively empty server metadata.

Proposed diff
 export function parsePackageJsonVersion(raw: string, pathForErrors = 'package.json'): string {
   const parsed = JSON.parse(raw) as { version?: unknown };
-  if (typeof parsed.version !== 'string' || parsed.version.length === 0) {
+  if (typeof parsed.version !== 'string' || parsed.version.trim().length === 0) {
     throw new Error(`Invalid or missing "version" in ${pathForErrors}`);
   }
-  return parsed.version;
+  return parsed.version.trim();
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/server-version.ts` around lines 16 - 19, The current validation in
server-version.ts checks only parsed.version.length, which accepts
whitespace-only strings; update the validation in the code that reads
parsed.version to trim the value and reject empty/whitespace-only strings (e.g.,
check typeof parsed.version === 'string' and parsed.version.trim().length > 0),
and return the trimmed version instead of the original so downstream consumers
get a normalized version; reference parsed.version and pathForErrors in your
change.
src/server-version.test.ts (1)

28-35: ⚡ Quick win

Add parser negative-path tests to lock validation behavior.

Current tests validate happy paths only. Add cases for malformed JSON, missing version, and empty/whitespace version so parser guarantees are regression-safe.

Proposed diff
 describe('parsePackageJsonVersion', () => {
   it('extracts version from several package.json shapes', () => {
     expect(parsePackageJsonVersion(PACKAGE_JSON_FIXTURES[0])).toBe('0.1.0');
     expect(parsePackageJsonVersion(PACKAGE_JSON_FIXTURES[1])).toBe('1.0.0');
     expect(parsePackageJsonVersion(PACKAGE_JSON_FIXTURES[2])).toBe('0.1.6');
     expect(parsePackageJsonVersion(PACKAGE_JSON_FIXTURES[3])).toBe('2.3.4');
   });
+
+  it('throws on malformed or invalid version fields', () => {
+    expect(() => parsePackageJsonVersion('{')).toThrow();
+    expect(() => parsePackageJsonVersion(JSON.stringify({ name: 'x' }))).toThrow();
+    expect(() => parsePackageJsonVersion(JSON.stringify({ version: '' }))).toThrow();
+    expect(() => parsePackageJsonVersion(JSON.stringify({ version: '   ' }))).toThrow();
+  });
 });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/server-version.test.ts` around lines 28 - 35, Add negative-path unit
tests for parsePackageJsonVersion to cover malformed JSON, missing version
fields, and empty/whitespace version strings so behavior is regression-safe:
update the test suite in src/server-version.test.ts (the
describe('parsePackageJsonVersion') block) to include new it cases that call
parsePackageJsonVersion with fixtures representing (1) invalid JSON input
(should throw or return the defined error/undefined behavior your parser uses),
(2) an object missing the version property (should return undefined or throw per
current contract), and (3) version set to '' or '   ' (should be treated as
invalid); reuse PACKAGE_JSON_FIXTURES or add new fixture entries and assert the
expected error/return values consistent with parsePackageJsonVersion's specified
behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/server-version.test.ts`:
- Around line 28-35: Add negative-path unit tests for parsePackageJsonVersion to
cover malformed JSON, missing version fields, and empty/whitespace version
strings so behavior is regression-safe: update the test suite in
src/server-version.test.ts (the describe('parsePackageJsonVersion') block) to
include new it cases that call parsePackageJsonVersion with fixtures
representing (1) invalid JSON input (should throw or return the defined
error/undefined behavior your parser uses), (2) an object missing the version
property (should return undefined or throw per current contract), and (3)
version set to '' or '   ' (should be treated as invalid); reuse
PACKAGE_JSON_FIXTURES or add new fixture entries and assert the expected
error/return values consistent with parsePackageJsonVersion's specified
behavior.

In `@src/server-version.ts`:
- Around line 16-19: The current validation in server-version.ts checks only
parsed.version.length, which accepts whitespace-only strings; update the
validation in the code that reads parsed.version to trim the value and reject
empty/whitespace-only strings (e.g., check typeof parsed.version === 'string'
and parsed.version.trim().length > 0), and return the trimmed version instead of
the original so downstream consumers get a normalized version; reference
parsed.version and pathForErrors in your change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9f41149a-0356-43cd-a924-c447305bd90e

📥 Commits

Reviewing files that changed from the base of the PR and between 4f3b1db and d0529f6.

📒 Files selected for processing (4)
  • .gitignore
  • src/constants.ts
  • src/server-version.test.ts
  • src/server-version.ts

@leostar0412
leostar0412 requested a review from jonathanMLDev May 4, 2026 19:13
@leostar0412 leostar0412 self-assigned this May 4, 2026
Comment thread src/server-version.ts Outdated
Comment thread src/server-version.ts Outdated
Introduce custom error classes for handling invalid or missing version fields in package.json. Update the version parsing logic to utilize these errors and add corresponding tests to ensure proper functionality. This enhances the robustness of server version management.
@leostar0412
leostar0412 requested a review from jonathanMLDev May 4, 2026 21:32

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/server-version.test.ts (1)

29-59: ⚡ Quick win

Add explicit tests for malformed JSON and missing version.

Current coverage is good, but Line 20 (missing version) and Line 34 (JSON parse failure) in the production parser are still untested. Adding those two cases will lock in fallback behavior.

Suggested test additions
 describe('parsePackageJsonVersion', () => {
+  it('returns default when version field is missing', () => {
+    const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+    try {
+      expect(parsePackageJsonVersion(JSON.stringify({ name: 'pkg' }))).toBe('0.0.1');
+      expect(logSpy).toHaveBeenCalled();
+    } finally {
+      logSpy.mockRestore();
+    }
+  });
+
+  it('returns default when package.json is malformed JSON', () => {
+    const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+    try {
+      expect(parsePackageJsonVersion('{')).toBe('0.0.1');
+      expect(logSpy).toHaveBeenCalled();
+    } finally {
+      logSpy.mockRestore();
+    }
+  });
+
   it('extracts version from several package.json shapes', () => {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/server-version.test.ts` around lines 29 - 59, Add two tests for
parsePackageJsonVersion: one that passes malformed JSON (e.g. a non-JSON string)
and asserts it returns the default '0.0.1' and that console.log was called, and
another that passes JSON with the version property missing (e.g.
JSON.stringify({})) and asserts the same default return and a console.log call;
use vi.spyOn(console, 'log').mockImplementation(() => {}) around each assertion
and restore the spy in finally blocks to mirror the existing tests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/server-version.ts`:
- Around line 21-63: The diagnostics in parsePackageJsonVersion and
resolveServerVersion are written to stdout via console.log and will corrupt the
stdio protocol; change all diagnostic console.log calls in
parsePackageJsonVersion (the messages for missing/invalid "version", empty
"version", and parse error) and in resolveServerVersion (the "package.json not
found" and "could not read" messages) to use console.error instead so
diagnostics go to stderr; update the console.log -> console.error for those five
messages and keep the same message text and error-detail construction.

---

Nitpick comments:
In `@src/server-version.test.ts`:
- Around line 29-59: Add two tests for parsePackageJsonVersion: one that passes
malformed JSON (e.g. a non-JSON string) and asserts it returns the default
'0.0.1' and that console.log was called, and another that passes JSON with the
version property missing (e.g. JSON.stringify({})) and asserts the same default
return and a console.log call; use vi.spyOn(console,
'log').mockImplementation(() => {}) around each assertion and restore the spy in
finally blocks to mirror the existing tests.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 31740c02-fd4c-4a5e-8070-6857bf4e80fe

📥 Commits

Reviewing files that changed from the base of the PR and between 506f89c and 868d386.

📒 Files selected for processing (2)
  • src/server-version.test.ts
  • src/server-version.ts

Comment thread src/server-version.ts Outdated
@leostar0412
leostar0412 requested review from jonathanMLDev and removed request for jonathanMLDev May 5, 2026 05:04
…ror instead of console.log for invalid version cases
@leostar0412
leostar0412 requested a review from wpak-ai May 5, 2026 16:47
@wpak-ai
wpak-ai merged commit 2b05008 into cppalliance:main May 5, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Align MCP SERVER_VERSION with package.json (fix stale 0.1.0 vs published version)

3 participants