Skip to content

ServerContext Accepts Context Param - #162

Merged
wpak-ai merged 2 commits into
cppalliance:mainfrom
jonathanMLDev:feat/server-context-composition-api
Jun 16, 2026
Merged

ServerContext Accepts Context Param#162
wpak-ai merged 2 commits into
cppalliance:mainfrom
jonathanMLDev:feat/server-context-composition-api

Conversation

@jonathanMLDev

@jonathanMLDev jonathanMLDev commented Jun 15, 2026

Copy link
Copy Markdown
Collaborator

Summary

Adds a typed composition API to ServerContext so embedders can inject pre-built dependencies (Pinecone client, URL generators, namespace cache seed, suggest-flow seed) at construction time — without relying on process-global facades like setPineconeClient() or getDefaultServerContext().

This resolves Issue #1 (Phase 4: Setup/Composition API) from the June week 3 plan and addresses the dual-ownership problem identified in eval §5.2.

What changed

New public API

  • ServerContextComposition — optional injectables for ServerContext / factory helpers
  • NamespaceCacheSeed, SuggestionFlowSeedEntry — minimal public seed types (internal NamespaceInfo is not exported)
  • createIsolatedContext(config, composition?) — multi-tenant factory with no process-global side effects
  • createServer(config, composition?) — now accepts an optional composition object (singleton path unchanged)

ServerContext constructor (breaking, pre-1.0)

Second argument changed from client?: PineconeClient to composition?: ServerContextComposition.

Composition seeds are applied directly in the constructor:

  • URL generators via existing validation in registerUrlGenerator
  • Namespace cache primed without a Pinecone call
  • Suggest-flow seeds written directly to internal state (bypasses markSuggested to avoid config reach-through when no config is supplied)

Singleton path

  • Private pendingComposition wired into lazy getDefaultServerContext() materialization
  • Cleared alongside pendingConfig in teardownDefaultServerContext() and createServer()

Docs & helpers

  • Embedder JSDoc on resolveConfig and resolveAllianceConfig documenting the { config, composition } pairing pattern
  • createTestServerContext() extended with optional composition field

Migration

// Before
new ServerContext(config, client);

// After — preferred
ServerContext.fromClient(config, client);
// or
new ServerContext(config, { client });

Multi-tenant embedders:

const config = resolveConfig({ apiKey, indexName });
const ctx = createIsolatedContext(config, {
  client: myPineconeClient,
  urlGenerators: [['my-ns', myGenerator]],
});
await setupCoreServer({ context: ctx });

Suggest-flow gate settings (disableSuggestFlow, cacheTtlMs) remain on ServerConfig — not duplicated on composition.

Test plan

  • npm run ci passes (typecheck, lint, format, build, coverage)
  • New server-context.composition.test.ts (9 tests): composition seeding, createIsolatedContext vs createServer isolation, cache expiry refetch, setConfig preserves URL generators but clears cache/flow, seed validation, AsyncDisposable cleanup
  • Existing tests unchanged: server-context.test.ts, server-context.lifecycle.test.ts, setup-multi-instance.test.ts

Files changed

File Change
src/core/server/server-context.ts Composition types, constructor, factories, pendingComposition
src/core/index.ts Export new types + createIsolatedContext
src/core/config.ts, src/alliance/config.ts Embedder JSDoc
src/core/server/tools/test-helpers.ts composition option
src/core/server/server-context.composition.test.ts New tests
CHANGELOG.md [Unreleased] entry

Related Issue

Summary by CodeRabbit

  • New Features

    • Added createIsolatedContext() factory for creating server contexts without process-level side effects
    • Exported Zod schemas for all MCP tool success responses
  • Breaking Changes

    • ServerContext constructor now accepts optional composition parameter instead of client
    • createServer() signature updated to accept optional composition parameter
    • resolveConfig() now requires explicit Pinecone index name; root defaults removed
    • MCP experimental response fields now nested under experimental object
  • Documentation

    • Added formal deprecation policy and breaking-change release notes template
    • Clarified stable vs experimental MCP response fields

@jonathanMLDev jonathanMLDev self-assigned this Jun 15, 2026
@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@jonathanMLDev, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 40 minutes and 14 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more credits in the billing tab to continue.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7efb8d03-7800-44f1-8fa7-4079c012d312

📥 Commits

Reviewing files that changed from the base of the PR and between a7852e6 and 8110a2e.

📒 Files selected for processing (4)
  • docs/MIGRATION.md
  • src/core/server/server-context.composition.test.ts
  • src/core/server/server-context.ts
  • src/index.ts
📝 Walkthrough

Walkthrough

Introduces a ServerContextComposition interface (plus NamespaceCacheSeed and SuggestionFlowSeedEntry types) that replaces the direct PineconeClient second argument on the ServerContext constructor. Adds a createIsolatedContext factory for process-global-safe instantiation. Updates createServer, getDefaultServerContext, and teardown paths to support the new composition. Exports the new types from src/core/index.ts, updates test helpers, and adds 206 lines of Vitest coverage.

Changes

ServerContextComposition Dependency Injection

Layer / File(s) Summary
Composition types, interface, and public exports
src/core/server/server-context.ts, src/core/index.ts
NamespaceCacheSeed, SuggestionFlowSeedEntry, and ServerContextComposition are defined as new exported types/interface in server-context.ts, then re-exported alongside the new createIsolatedContext runtime export from src/core/index.ts.
ServerContext constructor, process-default wiring, and new factories
src/core/server/server-context.ts
Constructor changes from (config?, client?) to (config?, composition?), performing conditional client injection, URL generator registration, namespace cache pre-warming, and suggest-flow seeding. Adds pendingComposition process-global, wires it through getDefaultServerContext and teardown, adds createIsolatedContext, and updates createServer to accept an optional composition.
Test helper composition support
src/core/server/tools/test-helpers.ts
createTestServerContext gains a composition? option, merges it with any provided client, and switches from ServerContext.fromClient to the composition-based constructor path.
Vitest coverage for composition API
src/core/server/server-context.composition.test.ts
New test file covering all composition injection scenarios: full seed at construction, config-less construction, createIsolatedContext vs createServer process-default behavior, post-hoc setClient, expired cache refetch, setConfig state clearing, invalid seed validation, async disposal, and fromClient wrapping.
JSDoc, config comments, and CHANGELOG
src/alliance/config.ts, src/core/config.ts, CHANGELOG.md
JSDoc on resolveAllianceConfig updated to describe the embedder-pattern split; block comment added to resolveConfig clarifying ServerConfig vs ServerContextComposition responsibility; CHANGELOG updated with new types/factories and breaking-change entries.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • AuraMindNest
  • wpak-ai

Poem

🐇 A rabbit hops in, paws full of seeds,
No more globals — just what each tenant needs!
createIsolatedContext, clean and bright,
Inject your client, cache in plain sight.
The process default stays safely away,
Multi-tenant burrows, hip-hip-hooray! 🌱

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title "ServerContext Accepts Context Param" clearly summarizes the main change: ServerContext constructor now accepts a composition/context parameter for dependency injection.
Linked Issues check ✅ Passed The PR fully addresses all acceptance criteria from issue #153: composition parameter accepted, injected dependencies override self-construction, backward compatibility preserved, dual-instance isolation verified, singleton path updated, and comprehensive test coverage provided.
Out of Scope Changes check ✅ Passed All changes directly support the composition API objective: documentation updates clarify the embedder pattern, exports enable public API usage, test helpers integrate the new feature, and no unrelated modifications are present.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

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

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@codecov

codecov Bot commented Jun 15, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (main@ba5429f). Learn more about missing BASE report.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #162   +/-   ##
=======================================
  Coverage        ?   87.56%           
=======================================
  Files           ?       40           
  Lines           ?     1664           
  Branches        ?      554           
=======================================
  Hits            ?     1457           
  Misses          ?      207           
  Partials        ?        0           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@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/core/server/server-context.composition.test.ts (1)

54-70: ⚡ Quick win

Consider splitting unrelated assertions into separate tests.

Line 69 creates a new ServerContext instance unrelated to the one tested in lines 57-67. While both assertions are correct, testing two different construction scenarios in a single test case may reduce clarity.

♻️ Suggested split
-  it('constructs with suggestionFlowSeed and no config without throwing', () => {
+  it('constructs with suggestionFlowSeed and no config without throwing', () => {
     expect(
       () =>
         new ServerContext(undefined, {
           suggestionFlowSeed: [
             {
               namespace: 'wg21',
               recommended_tool: 'fast',
               suggested_fields: ['title'],
               user_query: 'contracts',
             },
           ],
         })
     ).not.toThrow();
+  });

-    expect(() => new ServerContext(undefined, {}).getConfig()).toThrow(/Missing Pinecone API key/);
+  it('throws when getConfig is called without Pinecone API key', () => {
+    expect(() => new ServerContext(undefined, {}).getConfig()).toThrow(/Missing Pinecone API key/);
   });
🤖 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/core/server/server-context.composition.test.ts` around lines 54 - 70,
Split the test into two separate test cases. The first test should verify that
ServerContext constructs successfully with suggestionFlowSeed and no config
without throwing (keep the existing assertion for this). Create a second
separate test that verifies ServerContext with undefined config throws the
Pinecone API key error when getConfig() is called. Each test should focus on a
single scenario to improve clarity.
🤖 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/core/server/server-context.ts`:
- Around line 91-95: The namespaceCacheSeed.data and
suggestionFlowSeed[*].suggested_fields payloads are currently stored by
reference, which allows external mutations of these seed objects to affect
multiple contexts that reuse the same seed instance. Clone these injected seed
payloads (both the data structures in namespaceCacheSeed and suggested_fields
arrays in suggestionFlowSeed) to create independent copies that prevent state
aliasing between contexts. Use appropriate deep cloning for nested arrays and
objects to ensure complete isolation.

---

Nitpick comments:
In `@src/core/server/server-context.composition.test.ts`:
- Around line 54-70: Split the test into two separate test cases. The first test
should verify that ServerContext constructs successfully with suggestionFlowSeed
and no config without throwing (keep the existing assertion for this). Create a
second separate test that verifies ServerContext with undefined config throws
the Pinecone API key error when getConfig() is called. Each test should focus on
a single scenario to improve clarity.
🪄 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: 75f6d175-3796-4204-8a9b-07e4e10e718f

📥 Commits

Reviewing files that changed from the base of the PR and between ba5429f and a7852e6.

📒 Files selected for processing (7)
  • CHANGELOG.md
  • src/alliance/config.ts
  • src/core/config.ts
  • src/core/index.ts
  • src/core/server/server-context.composition.test.ts
  • src/core/server/server-context.ts
  • src/core/server/tools/test-helpers.ts

Comment thread src/core/server/server-context.ts
@leostar0412
leostar0412 requested a review from wpak-ai June 15, 2026 21:36
@wpak-ai
wpak-ai merged commit 435dcdd into cppalliance:main Jun 16, 2026
12 checks passed
@jonathanMLDev
jonathanMLDev deleted the feat/server-context-composition-api branch June 22, 2026 18:32
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.

Setup/Composition API — ServerContext Accepts Context Param

3 participants